main.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. from __future__ import absolute_import
  2. from __future__ import print_function
  3. from __future__ import unicode_literals
  4. import contextlib
  5. import functools
  6. import json
  7. import logging
  8. import pipes
  9. import re
  10. import subprocess
  11. import sys
  12. from distutils.spawn import find_executable
  13. from inspect import getdoc
  14. from operator import attrgetter
  15. from . import errors
  16. from . import signals
  17. from .. import __version__
  18. from ..bundle import get_image_digests
  19. from ..bundle import MissingDigests
  20. from ..bundle import serialize_bundle
  21. from ..config import ConfigurationError
  22. from ..config import parse_environment
  23. from ..config.environment import Environment
  24. from ..config.serialize import serialize_config
  25. from ..const import IS_WINDOWS_PLATFORM
  26. from ..errors import StreamParseError
  27. from ..progress_stream import StreamOutputError
  28. from ..project import NoSuchService
  29. from ..project import OneOffFilter
  30. from ..project import ProjectError
  31. from ..service import BuildAction
  32. from ..service import BuildError
  33. from ..service import ConvergenceStrategy
  34. from ..service import ImageType
  35. from ..service import NeedsBuildError
  36. from ..service import OperationFailedError
  37. from .command import get_config_from_options
  38. from .command import project_from_options
  39. from .docopt_command import DocoptDispatcher
  40. from .docopt_command import get_handler
  41. from .docopt_command import NoSuchCommand
  42. from .errors import UserError
  43. from .formatter import ConsoleWarningFormatter
  44. from .formatter import Formatter
  45. from .log_printer import build_log_presenters
  46. from .log_printer import LogPrinter
  47. from .utils import get_version_info
  48. from .utils import human_readable_file_size
  49. from .utils import yesno
  50. if not IS_WINDOWS_PLATFORM:
  51. from dockerpty.pty import PseudoTerminal, RunOperation, ExecOperation
  52. log = logging.getLogger(__name__)
  53. console_handler = logging.StreamHandler(sys.stderr)
  54. def main():
  55. try:
  56. command = dispatch()
  57. command()
  58. except (KeyboardInterrupt, signals.ShutdownException):
  59. log.error("Aborting.")
  60. sys.exit(1)
  61. except (UserError, NoSuchService, ConfigurationError,
  62. ProjectError, OperationFailedError) as e:
  63. log.error(e.msg)
  64. sys.exit(1)
  65. except BuildError as e:
  66. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  67. sys.exit(1)
  68. except StreamOutputError as e:
  69. log.error(e)
  70. sys.exit(1)
  71. except NeedsBuildError as e:
  72. log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name)
  73. sys.exit(1)
  74. except NoSuchCommand as e:
  75. commands = "\n".join(parse_doc_section("commands:", getdoc(e.supercommand)))
  76. log.error("No such command: %s\n\n%s", e.command, commands)
  77. sys.exit(1)
  78. except (errors.ConnectionError, StreamParseError):
  79. sys.exit(1)
  80. def dispatch():
  81. setup_logging()
  82. dispatcher = DocoptDispatcher(
  83. TopLevelCommand,
  84. {'options_first': True, 'version': get_version_info('compose')})
  85. options, handler, command_options = dispatcher.parse(sys.argv[1:])
  86. setup_console_handler(console_handler, options.get('--verbose'))
  87. return functools.partial(perform_command, options, handler, command_options)
  88. def perform_command(options, handler, command_options):
  89. if options['COMMAND'] in ('help', 'version'):
  90. # Skip looking up the compose file.
  91. handler(command_options)
  92. return
  93. if options['COMMAND'] in ('config', 'bundle'):
  94. command = TopLevelCommand(None)
  95. handler(command, options, command_options)
  96. return
  97. project = project_from_options('.', options)
  98. command = TopLevelCommand(project)
  99. with errors.handle_connection_errors(project.client):
  100. handler(command, command_options)
  101. def setup_logging():
  102. root_logger = logging.getLogger()
  103. root_logger.addHandler(console_handler)
  104. root_logger.setLevel(logging.DEBUG)
  105. # Disable requests logging
  106. logging.getLogger("requests").propagate = False
  107. def setup_console_handler(handler, verbose):
  108. if handler.stream.isatty():
  109. format_class = ConsoleWarningFormatter
  110. else:
  111. format_class = logging.Formatter
  112. if verbose:
  113. handler.setFormatter(format_class('%(name)s.%(funcName)s: %(message)s'))
  114. handler.setLevel(logging.DEBUG)
  115. else:
  116. handler.setFormatter(format_class())
  117. handler.setLevel(logging.INFO)
  118. # stolen from docopt master
  119. def parse_doc_section(name, source):
  120. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  121. re.IGNORECASE | re.MULTILINE)
  122. return [s.strip() for s in pattern.findall(source)]
  123. class TopLevelCommand(object):
  124. """Define and run multi-container applications with Docker.
  125. Usage:
  126. docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  127. docker-compose -h|--help
  128. Options:
  129. -f, --file FILE Specify an alternate compose file (default: docker-compose.yml)
  130. -p, --project-name NAME Specify an alternate project name (default: directory name)
  131. --verbose Show more output
  132. -v, --version Print version and exit
  133. -H, --host HOST Daemon socket to connect to
  134. --tls Use TLS; implied by --tlsverify
  135. --tlscacert CA_PATH Trust certs signed only by this CA
  136. --tlscert CLIENT_CERT_PATH Path to TLS certificate file
  137. --tlskey TLS_KEY_PATH Path to TLS key file
  138. --tlsverify Use TLS and verify the remote
  139. --skip-hostname-check Don't check the daemon's hostname against the name specified
  140. in the client certificate (for example if your docker host
  141. is an IP address)
  142. Commands:
  143. build Build or rebuild services
  144. bundle Generate a Docker bundle from the Compose file
  145. config Validate and view the compose file
  146. create Create services
  147. down Stop and remove containers, networks, images, and volumes
  148. events Receive real time events from containers
  149. exec Execute a command in a running container
  150. help Get help on a command
  151. images List images
  152. kill Kill containers
  153. logs View output from containers
  154. pause Pause services
  155. port Print the public port for a port binding
  156. ps List containers
  157. pull Pull service images
  158. push Push service images
  159. restart Restart services
  160. rm Remove stopped containers
  161. run Run a one-off command
  162. scale Set number of containers for a service
  163. start Start services
  164. stop Stop services
  165. top Display the running processes
  166. unpause Unpause services
  167. up Create and start containers
  168. version Show the Docker-Compose version information
  169. """
  170. def __init__(self, project, project_dir='.'):
  171. self.project = project
  172. self.project_dir = '.'
  173. def build(self, options):
  174. """
  175. Build or rebuild services.
  176. Services are built once and then tagged as `project_service`,
  177. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  178. contents of its build directory, you can run `docker-compose build` to rebuild it.
  179. Usage: build [options] [SERVICE...]
  180. Options:
  181. --force-rm Always remove intermediate containers.
  182. --no-cache Do not use cache when building the image.
  183. --pull Always attempt to pull a newer version of the image.
  184. """
  185. self.project.build(
  186. service_names=options['SERVICE'],
  187. no_cache=bool(options.get('--no-cache', False)),
  188. pull=bool(options.get('--pull', False)),
  189. force_rm=bool(options.get('--force-rm', False)))
  190. def bundle(self, config_options, options):
  191. """
  192. Generate a Distributed Application Bundle (DAB) from the Compose file.
  193. Images must have digests stored, which requires interaction with a
  194. Docker registry. If digests aren't stored for all images, you can fetch
  195. them with `docker-compose pull` or `docker-compose push`. To push images
  196. automatically when bundling, pass `--push-images`. Only services with
  197. a `build` option specified will have their images pushed.
  198. Usage: bundle [options]
  199. Options:
  200. --push-images Automatically push images for any services
  201. which have a `build` option specified.
  202. -o, --output PATH Path to write the bundle file to.
  203. Defaults to "<project name>.dab".
  204. """
  205. self.project = project_from_options('.', config_options)
  206. compose_config = get_config_from_options(self.project_dir, config_options)
  207. output = options["--output"]
  208. if not output:
  209. output = "{}.dab".format(self.project.name)
  210. with errors.handle_connection_errors(self.project.client):
  211. try:
  212. image_digests = get_image_digests(
  213. self.project,
  214. allow_push=options['--push-images'],
  215. )
  216. except MissingDigests as e:
  217. def list_images(images):
  218. return "\n".join(" {}".format(name) for name in sorted(images))
  219. paras = ["Some images are missing digests."]
  220. if e.needs_push:
  221. command_hint = (
  222. "Use `docker-compose push {}` to push them. "
  223. "You can do this automatically with `docker-compose bundle --push-images`."
  224. .format(" ".join(sorted(e.needs_push)))
  225. )
  226. paras += [
  227. "The following images can be pushed:",
  228. list_images(e.needs_push),
  229. command_hint,
  230. ]
  231. if e.needs_pull:
  232. command_hint = (
  233. "Use `docker-compose pull {}` to pull them. "
  234. .format(" ".join(sorted(e.needs_pull)))
  235. )
  236. paras += [
  237. "The following images need to be pulled:",
  238. list_images(e.needs_pull),
  239. command_hint,
  240. ]
  241. raise UserError("\n\n".join(paras))
  242. with open(output, 'w') as f:
  243. f.write(serialize_bundle(compose_config, image_digests))
  244. log.info("Wrote bundle to {}".format(output))
  245. def config(self, config_options, options):
  246. """
  247. Validate and view the compose file.
  248. Usage: config [options]
  249. Options:
  250. -q, --quiet Only validate the configuration, don't print
  251. anything.
  252. --services Print the service names, one per line.
  253. --volumes Print the volume names, one per line.
  254. """
  255. compose_config = get_config_from_options(self.project_dir, config_options)
  256. if options['--quiet']:
  257. return
  258. if options['--services']:
  259. print('\n'.join(service['name'] for service in compose_config.services))
  260. return
  261. if options['--volumes']:
  262. print('\n'.join(volume for volume in compose_config.volumes))
  263. return
  264. print(serialize_config(compose_config))
  265. def create(self, options):
  266. """
  267. Creates containers for a service.
  268. Usage: create [options] [SERVICE...]
  269. Options:
  270. --force-recreate Recreate containers even if their configuration and
  271. image haven't changed. Incompatible with --no-recreate.
  272. --no-recreate If containers already exist, don't recreate them.
  273. Incompatible with --force-recreate.
  274. --no-build Don't build an image, even if it's missing.
  275. --build Build images before creating containers.
  276. """
  277. service_names = options['SERVICE']
  278. self.project.create(
  279. service_names=service_names,
  280. strategy=convergence_strategy_from_opts(options),
  281. do_build=build_action_from_opts(options),
  282. )
  283. def down(self, options):
  284. """
  285. Stops containers and removes containers, networks, volumes, and images
  286. created by `up`.
  287. By default, the only things removed are:
  288. - Containers for services defined in the Compose file
  289. - Networks defined in the `networks` section of the Compose file
  290. - The default network, if one is used
  291. Networks and volumes defined as `external` are never removed.
  292. Usage: down [options]
  293. Options:
  294. --rmi type Remove images. Type must be one of:
  295. 'all': Remove all images used by any service.
  296. 'local': Remove only images that don't have a custom tag
  297. set by the `image` field.
  298. -v, --volumes Remove named volumes declared in the `volumes` section
  299. of the Compose file and anonymous volumes
  300. attached to containers.
  301. --remove-orphans Remove containers for services not defined in the
  302. Compose file
  303. """
  304. image_type = image_type_from_opt('--rmi', options['--rmi'])
  305. self.project.down(image_type, options['--volumes'], options['--remove-orphans'])
  306. def events(self, options):
  307. """
  308. Receive real time events from containers.
  309. Usage: events [options] [SERVICE...]
  310. Options:
  311. --json Output events as a stream of json objects
  312. """
  313. def format_event(event):
  314. attributes = ["%s=%s" % item for item in event['attributes'].items()]
  315. return ("{time} {type} {action} {id} ({attrs})").format(
  316. attrs=", ".join(sorted(attributes)),
  317. **event)
  318. def json_format_event(event):
  319. event['time'] = event['time'].isoformat()
  320. event.pop('container')
  321. return json.dumps(event)
  322. for event in self.project.events():
  323. formatter = json_format_event if options['--json'] else format_event
  324. print(formatter(event))
  325. sys.stdout.flush()
  326. def exec_command(self, options):
  327. """
  328. Execute a command in a running container
  329. Usage: exec [options] SERVICE COMMAND [ARGS...]
  330. Options:
  331. -d Detached mode: Run command in the background.
  332. --privileged Give extended privileges to the process.
  333. --user USER Run the command as this user.
  334. -T Disable pseudo-tty allocation. By default `docker-compose exec`
  335. allocates a TTY.
  336. --index=index index of the container if there are multiple
  337. instances of a service [default: 1]
  338. """
  339. index = int(options.get('--index'))
  340. service = self.project.get_service(options['SERVICE'])
  341. detach = options['-d']
  342. try:
  343. container = service.get_container(number=index)
  344. except ValueError as e:
  345. raise UserError(str(e))
  346. command = [options['COMMAND']] + options['ARGS']
  347. tty = not options["-T"]
  348. if IS_WINDOWS_PLATFORM and not detach:
  349. args = ["exec"]
  350. if options["-d"]:
  351. args += ["--detach"]
  352. else:
  353. args += ["--interactive"]
  354. if not options["-T"]:
  355. args += ["--tty"]
  356. if options["--privileged"]:
  357. args += ["--privileged"]
  358. if options["--user"]:
  359. args += ["--user", options["--user"]]
  360. args += [container.id]
  361. args += command
  362. sys.exit(call_docker(args))
  363. create_exec_options = {
  364. "privileged": options["--privileged"],
  365. "user": options["--user"],
  366. "tty": tty,
  367. "stdin": tty,
  368. }
  369. exec_id = container.create_exec(command, **create_exec_options)
  370. if detach:
  371. container.start_exec(exec_id, tty=tty)
  372. return
  373. signals.set_signal_handler_to_shutdown()
  374. try:
  375. operation = ExecOperation(
  376. self.project.client,
  377. exec_id,
  378. interactive=tty,
  379. )
  380. pty = PseudoTerminal(self.project.client, operation)
  381. pty.start()
  382. except signals.ShutdownException:
  383. log.info("received shutdown exception: closing")
  384. exit_code = self.project.client.exec_inspect(exec_id).get("ExitCode")
  385. sys.exit(exit_code)
  386. @classmethod
  387. def help(cls, options):
  388. """
  389. Get help on a command.
  390. Usage: help [COMMAND]
  391. """
  392. if options['COMMAND']:
  393. subject = get_handler(cls, options['COMMAND'])
  394. else:
  395. subject = cls
  396. print(getdoc(subject))
  397. def images(self, options):
  398. """
  399. List images used by the created containers.
  400. Usage: images [options] [SERVICE...]
  401. Options:
  402. -q Only display IDs
  403. """
  404. containers = sorted(
  405. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  406. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  407. key=attrgetter('name'))
  408. if options['-q']:
  409. for image in set(c.image for c in containers):
  410. print(image.split(':')[1])
  411. else:
  412. headers = [
  413. 'Container',
  414. 'Repository',
  415. 'Tag',
  416. 'Image Id',
  417. 'Size'
  418. ]
  419. rows = []
  420. for container in containers:
  421. image_config = container.image_config
  422. repo_tags = image_config['RepoTags'][0].split(':')
  423. image_id = image_config['Id'].split(':')[1][:12]
  424. size = human_readable_file_size(image_config['Size'])
  425. rows.append([
  426. container.name,
  427. repo_tags[0],
  428. repo_tags[1],
  429. image_id,
  430. size
  431. ])
  432. print(Formatter().table(headers, rows))
  433. def kill(self, options):
  434. """
  435. Force stop service containers.
  436. Usage: kill [options] [SERVICE...]
  437. Options:
  438. -s SIGNAL SIGNAL to send to the container.
  439. Default signal is SIGKILL.
  440. """
  441. signal = options.get('-s', 'SIGKILL')
  442. self.project.kill(service_names=options['SERVICE'], signal=signal)
  443. def logs(self, options):
  444. """
  445. View output from containers.
  446. Usage: logs [options] [SERVICE...]
  447. Options:
  448. --no-color Produce monochrome output.
  449. -f, --follow Follow log output.
  450. -t, --timestamps Show timestamps.
  451. --tail="all" Number of lines to show from the end of the logs
  452. for each container.
  453. """
  454. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  455. tail = options['--tail']
  456. if tail is not None:
  457. if tail.isdigit():
  458. tail = int(tail)
  459. elif tail != 'all':
  460. raise UserError("tail flag must be all or a number")
  461. log_args = {
  462. 'follow': options['--follow'],
  463. 'tail': tail,
  464. 'timestamps': options['--timestamps']
  465. }
  466. print("Attaching to", list_containers(containers))
  467. log_printer_from_project(
  468. self.project,
  469. containers,
  470. options['--no-color'],
  471. log_args,
  472. event_stream=self.project.events(service_names=options['SERVICE'])).run()
  473. def pause(self, options):
  474. """
  475. Pause services.
  476. Usage: pause [SERVICE...]
  477. """
  478. containers = self.project.pause(service_names=options['SERVICE'])
  479. exit_if(not containers, 'No containers to pause', 1)
  480. def port(self, options):
  481. """
  482. Print the public port for a port binding.
  483. Usage: port [options] SERVICE PRIVATE_PORT
  484. Options:
  485. --protocol=proto tcp or udp [default: tcp]
  486. --index=index index of the container if there are multiple
  487. instances of a service [default: 1]
  488. """
  489. index = int(options.get('--index'))
  490. service = self.project.get_service(options['SERVICE'])
  491. try:
  492. container = service.get_container(number=index)
  493. except ValueError as e:
  494. raise UserError(str(e))
  495. print(container.get_local_port(
  496. options['PRIVATE_PORT'],
  497. protocol=options.get('--protocol') or 'tcp') or '')
  498. def ps(self, options):
  499. """
  500. List containers.
  501. Usage: ps [options] [SERVICE...]
  502. Options:
  503. -q Only display IDs
  504. """
  505. containers = sorted(
  506. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  507. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  508. key=attrgetter('name'))
  509. if options['-q']:
  510. for container in containers:
  511. print(container.id)
  512. else:
  513. headers = [
  514. 'Name',
  515. 'Command',
  516. 'State',
  517. 'Ports',
  518. ]
  519. rows = []
  520. for container in containers:
  521. command = container.human_readable_command
  522. if len(command) > 30:
  523. command = '%s ...' % command[:26]
  524. rows.append([
  525. container.name,
  526. command,
  527. container.human_readable_state,
  528. container.human_readable_ports,
  529. ])
  530. print(Formatter().table(headers, rows))
  531. def pull(self, options):
  532. """
  533. Pulls images for services.
  534. Usage: pull [options] [SERVICE...]
  535. Options:
  536. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  537. --parallel Pull multiple images in parallel.
  538. """
  539. self.project.pull(
  540. service_names=options['SERVICE'],
  541. ignore_pull_failures=options.get('--ignore-pull-failures'),
  542. parallel_pull=options.get('--parallel')
  543. )
  544. def push(self, options):
  545. """
  546. Pushes images for services.
  547. Usage: push [options] [SERVICE...]
  548. Options:
  549. --ignore-push-failures Push what it can and ignores images with push failures.
  550. """
  551. self.project.push(
  552. service_names=options['SERVICE'],
  553. ignore_push_failures=options.get('--ignore-push-failures')
  554. )
  555. def rm(self, options):
  556. """
  557. Removes stopped service containers.
  558. By default, anonymous volumes attached to containers will not be removed. You
  559. can override this with `-v`. To list all volumes, use `docker volume ls`.
  560. Any data which is not in a volume will be lost.
  561. Usage: rm [options] [SERVICE...]
  562. Options:
  563. -f, --force Don't ask to confirm removal
  564. -v Remove any anonymous volumes attached to containers
  565. -a, --all Deprecated - no effect.
  566. """
  567. if options.get('--all'):
  568. log.warn(
  569. '--all flag is obsolete. This is now the default behavior '
  570. 'of `docker-compose rm`'
  571. )
  572. one_off = OneOffFilter.include
  573. all_containers = self.project.containers(
  574. service_names=options['SERVICE'], stopped=True, one_off=one_off
  575. )
  576. stopped_containers = [c for c in all_containers if not c.is_running]
  577. if len(stopped_containers) > 0:
  578. print("Going to remove", list_containers(stopped_containers))
  579. if options.get('--force') \
  580. or yesno("Are you sure? [yN] ", default=False):
  581. self.project.remove_stopped(
  582. service_names=options['SERVICE'],
  583. v=options.get('-v', False),
  584. one_off=one_off
  585. )
  586. else:
  587. print("No stopped containers")
  588. def run(self, options):
  589. """
  590. Run a one-off command on a service.
  591. For example:
  592. $ docker-compose run web python manage.py shell
  593. By default, linked services will be started, unless they are already
  594. running. If you do not want to start linked services, use
  595. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  596. Usage: run [options] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  597. Options:
  598. -d Detached mode: Run container in the background, print
  599. new container name.
  600. --name NAME Assign a name to the container
  601. --entrypoint CMD Override the entrypoint of the image.
  602. -e KEY=VAL Set an environment variable (can be used multiple times)
  603. -u, --user="" Run as specified username or uid
  604. --no-deps Don't start linked services.
  605. --rm Remove container after run. Ignored in detached mode.
  606. -p, --publish=[] Publish a container's port(s) to the host
  607. --service-ports Run command with the service's ports enabled and mapped
  608. to the host.
  609. -T Disable pseudo-tty allocation. By default `docker-compose run`
  610. allocates a TTY.
  611. -w, --workdir="" Working directory inside the container
  612. """
  613. service = self.project.get_service(options['SERVICE'])
  614. detach = options['-d']
  615. if options['--publish'] and options['--service-ports']:
  616. raise UserError(
  617. 'Service port mapping and manual port mapping '
  618. 'can not be used together'
  619. )
  620. if options['COMMAND'] is not None:
  621. command = [options['COMMAND']] + options['ARGS']
  622. elif options['--entrypoint'] is not None:
  623. command = []
  624. else:
  625. command = service.options.get('command')
  626. container_options = build_container_options(options, detach, command)
  627. run_one_off_container(container_options, self.project, service, options)
  628. def scale(self, options):
  629. """
  630. Set number of containers to run for a service.
  631. Numbers are specified in the form `service=num` as arguments.
  632. For example:
  633. $ docker-compose scale web=2 worker=3
  634. Usage: scale [options] [SERVICE=NUM...]
  635. Options:
  636. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  637. (default: 10)
  638. """
  639. timeout = timeout_from_opts(options)
  640. for s in options['SERVICE=NUM']:
  641. if '=' not in s:
  642. raise UserError('Arguments to scale should be in the form service=num')
  643. service_name, num = s.split('=', 1)
  644. try:
  645. num = int(num)
  646. except ValueError:
  647. raise UserError('Number of containers for service "%s" is not a '
  648. 'number' % service_name)
  649. self.project.get_service(service_name).scale(num, timeout=timeout)
  650. def start(self, options):
  651. """
  652. Start existing containers.
  653. Usage: start [SERVICE...]
  654. """
  655. containers = self.project.start(service_names=options['SERVICE'])
  656. exit_if(not containers, 'No containers to start', 1)
  657. def stop(self, options):
  658. """
  659. Stop running containers without removing them.
  660. They can be started again with `docker-compose start`.
  661. Usage: stop [options] [SERVICE...]
  662. Options:
  663. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  664. (default: 10)
  665. """
  666. timeout = timeout_from_opts(options)
  667. self.project.stop(service_names=options['SERVICE'], timeout=timeout)
  668. def restart(self, options):
  669. """
  670. Restart running containers.
  671. Usage: restart [options] [SERVICE...]
  672. Options:
  673. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  674. (default: 10)
  675. """
  676. timeout = timeout_from_opts(options)
  677. containers = self.project.restart(service_names=options['SERVICE'], timeout=timeout)
  678. exit_if(not containers, 'No containers to restart', 1)
  679. def top(self, options):
  680. """
  681. Display the running processes
  682. Usage: top [SERVICE...]
  683. """
  684. containers = sorted(
  685. self.project.containers(service_names=options['SERVICE'], stopped=False) +
  686. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  687. key=attrgetter('name')
  688. )
  689. for idx, container in enumerate(containers):
  690. if idx > 0:
  691. print()
  692. top_data = self.project.client.top(container.name)
  693. headers = top_data.get("Titles")
  694. rows = []
  695. for process in top_data.get("Processes", []):
  696. rows.append(process)
  697. print(container.name)
  698. print(Formatter().table(headers, rows))
  699. def unpause(self, options):
  700. """
  701. Unpause services.
  702. Usage: unpause [SERVICE...]
  703. """
  704. containers = self.project.unpause(service_names=options['SERVICE'])
  705. exit_if(not containers, 'No containers to unpause', 1)
  706. def up(self, options):
  707. """
  708. Builds, (re)creates, starts, and attaches to containers for a service.
  709. Unless they are already running, this command also starts any linked services.
  710. The `docker-compose up` command aggregates the output of each container. When
  711. the command exits, all containers are stopped. Running `docker-compose up -d`
  712. starts the containers in the background and leaves them running.
  713. If there are existing containers for a service, and the service's configuration
  714. or image was changed after the container's creation, `docker-compose up` picks
  715. up the changes by stopping and recreating the containers (preserving mounted
  716. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  717. flag.
  718. If you want to force Compose to stop and recreate all containers, use the
  719. `--force-recreate` flag.
  720. Usage: up [options] [SERVICE...]
  721. Options:
  722. -d Detached mode: Run containers in the background,
  723. print new container names.
  724. Incompatible with --abort-on-container-exit.
  725. --no-color Produce monochrome output.
  726. --no-deps Don't start linked services.
  727. --force-recreate Recreate containers even if their configuration
  728. and image haven't changed.
  729. Incompatible with --no-recreate.
  730. --no-recreate If containers already exist, don't recreate them.
  731. Incompatible with --force-recreate.
  732. --no-build Don't build an image, even if it's missing.
  733. --build Build images before starting containers.
  734. --abort-on-container-exit Stops all containers if any container was stopped.
  735. Incompatible with -d.
  736. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  737. when attached or when containers are already
  738. running. (default: 10)
  739. --remove-orphans Remove containers for services not
  740. defined in the Compose file
  741. --exit-code-from SERVICE Return the exit code of the selected service container.
  742. Requires --abort-on-container-exit.
  743. """
  744. start_deps = not options['--no-deps']
  745. exit_value_from = exitval_from_opts(options, self.project)
  746. cascade_stop = options['--abort-on-container-exit']
  747. service_names = options['SERVICE']
  748. timeout = timeout_from_opts(options)
  749. remove_orphans = options['--remove-orphans']
  750. detached = options.get('-d')
  751. if detached and cascade_stop:
  752. raise UserError("--abort-on-container-exit and -d cannot be combined.")
  753. with up_shutdown_context(self.project, service_names, timeout, detached):
  754. to_attach = self.project.up(
  755. service_names=service_names,
  756. start_deps=start_deps,
  757. strategy=convergence_strategy_from_opts(options),
  758. do_build=build_action_from_opts(options),
  759. timeout=timeout,
  760. detached=detached,
  761. remove_orphans=remove_orphans)
  762. if detached:
  763. return
  764. attached_containers = filter_containers_to_service_names(to_attach, service_names)
  765. log_printer = log_printer_from_project(
  766. self.project,
  767. attached_containers,
  768. options['--no-color'],
  769. {'follow': True},
  770. cascade_stop,
  771. event_stream=self.project.events(service_names=service_names))
  772. print("Attaching to", list_containers(log_printer.containers))
  773. cascade_starter = log_printer.run()
  774. if cascade_stop:
  775. print("Aborting on container exit...")
  776. exit_code = 0
  777. if exit_value_from:
  778. candidates = filter(
  779. lambda c: c.service == exit_value_from,
  780. attached_containers)
  781. if not candidates:
  782. log.error(
  783. 'No containers matching the spec "{0}" '
  784. 'were run.'.format(exit_value_from)
  785. )
  786. exit_code = 2
  787. elif len(candidates) > 1:
  788. exit_values = filter(
  789. lambda e: e != 0,
  790. [c.inspect()['State']['ExitCode'] for c in candidates]
  791. )
  792. exit_code = exit_values[0]
  793. else:
  794. exit_code = candidates[0].inspect()['State']['ExitCode']
  795. else:
  796. for e in self.project.containers(service_names=options['SERVICE'], stopped=True):
  797. if (not e.is_running and cascade_starter == e.name):
  798. if not e.exit_code == 0:
  799. exit_code = e.exit_code
  800. break
  801. self.project.stop(service_names=service_names, timeout=timeout)
  802. sys.exit(exit_code)
  803. @classmethod
  804. def version(cls, options):
  805. """
  806. Show version informations
  807. Usage: version [--short]
  808. Options:
  809. --short Shows only Compose's version number.
  810. """
  811. if options['--short']:
  812. print(__version__)
  813. else:
  814. print(get_version_info('full'))
  815. def convergence_strategy_from_opts(options):
  816. no_recreate = options['--no-recreate']
  817. force_recreate = options['--force-recreate']
  818. if force_recreate and no_recreate:
  819. raise UserError("--force-recreate and --no-recreate cannot be combined.")
  820. if force_recreate:
  821. return ConvergenceStrategy.always
  822. if no_recreate:
  823. return ConvergenceStrategy.never
  824. return ConvergenceStrategy.changed
  825. def timeout_from_opts(options):
  826. timeout = options.get('--timeout')
  827. return None if timeout is None else int(timeout)
  828. def exitval_from_opts(options, project):
  829. exit_value_from = options.get('--exit-code-from')
  830. if exit_value_from:
  831. if not options.get('--abort-on-container-exit'):
  832. log.warn('using --exit-code-from implies --abort-on-container-exit')
  833. options['--abort-on-container-exit'] = True
  834. if exit_value_from not in [s.name for s in project.get_services()]:
  835. log.error('No service named "%s" was found in your compose file.',
  836. exit_value_from)
  837. sys.exit(2)
  838. return exit_value_from
  839. def image_type_from_opt(flag, value):
  840. if not value:
  841. return ImageType.none
  842. try:
  843. return ImageType[value]
  844. except KeyError:
  845. raise UserError("%s flag must be one of: all, local" % flag)
  846. def build_action_from_opts(options):
  847. if options['--build'] and options['--no-build']:
  848. raise UserError("--build and --no-build can not be combined.")
  849. if options['--build']:
  850. return BuildAction.force
  851. if options['--no-build']:
  852. return BuildAction.skip
  853. return BuildAction.none
  854. def build_container_options(options, detach, command):
  855. container_options = {
  856. 'command': command,
  857. 'tty': not (detach or options['-T'] or not sys.stdin.isatty()),
  858. 'stdin_open': not detach,
  859. 'detach': detach,
  860. }
  861. if options['-e']:
  862. container_options['environment'] = Environment.from_command_line(
  863. parse_environment(options['-e'])
  864. )
  865. if options['--entrypoint']:
  866. container_options['entrypoint'] = options.get('--entrypoint')
  867. if options['--rm']:
  868. container_options['restart'] = None
  869. if options['--user']:
  870. container_options['user'] = options.get('--user')
  871. if not options['--service-ports']:
  872. container_options['ports'] = []
  873. if options['--publish']:
  874. container_options['ports'] = options.get('--publish')
  875. if options['--name']:
  876. container_options['name'] = options['--name']
  877. if options['--workdir']:
  878. container_options['working_dir'] = options['--workdir']
  879. return container_options
  880. def run_one_off_container(container_options, project, service, options):
  881. if not options['--no-deps']:
  882. deps = service.get_dependency_names()
  883. if deps:
  884. project.up(
  885. service_names=deps,
  886. start_deps=True,
  887. strategy=ConvergenceStrategy.never)
  888. project.initialize()
  889. container = service.create_container(
  890. quiet=True,
  891. one_off=True,
  892. **container_options)
  893. if options['-d']:
  894. service.start_container(container)
  895. print(container.name)
  896. return
  897. def remove_container(force=False):
  898. if options['--rm']:
  899. project.client.remove_container(container.id, force=True, v=True)
  900. signals.set_signal_handler_to_shutdown()
  901. try:
  902. try:
  903. if IS_WINDOWS_PLATFORM:
  904. service.connect_container_to_networks(container)
  905. exit_code = call_docker(["start", "--attach", "--interactive", container.id])
  906. else:
  907. operation = RunOperation(
  908. project.client,
  909. container.id,
  910. interactive=not options['-T'],
  911. logs=False,
  912. )
  913. pty = PseudoTerminal(project.client, operation)
  914. sockets = pty.sockets()
  915. service.start_container(container)
  916. pty.start(sockets)
  917. exit_code = container.wait()
  918. except signals.ShutdownException:
  919. project.client.stop(container.id)
  920. exit_code = 1
  921. except signals.ShutdownException:
  922. project.client.kill(container.id)
  923. remove_container(force=True)
  924. sys.exit(2)
  925. remove_container()
  926. sys.exit(exit_code)
  927. def log_printer_from_project(
  928. project,
  929. containers,
  930. monochrome,
  931. log_args,
  932. cascade_stop=False,
  933. event_stream=None,
  934. ):
  935. return LogPrinter(
  936. containers,
  937. build_log_presenters(project.service_names, monochrome),
  938. event_stream or project.events(),
  939. cascade_stop=cascade_stop,
  940. log_args=log_args)
  941. def filter_containers_to_service_names(containers, service_names):
  942. if not service_names:
  943. return containers
  944. return [
  945. container
  946. for container in containers if container.service in service_names
  947. ]
  948. @contextlib.contextmanager
  949. def up_shutdown_context(project, service_names, timeout, detached):
  950. if detached:
  951. yield
  952. return
  953. signals.set_signal_handler_to_shutdown()
  954. try:
  955. try:
  956. yield
  957. except signals.ShutdownException:
  958. print("Gracefully stopping... (press Ctrl+C again to force)")
  959. project.stop(service_names=service_names, timeout=timeout)
  960. except signals.ShutdownException:
  961. project.kill(service_names=service_names)
  962. sys.exit(2)
  963. def list_containers(containers):
  964. return ", ".join(c.name for c in containers)
  965. def exit_if(condition, message, exit_code):
  966. if condition:
  967. log.error(message)
  968. raise SystemExit(exit_code)
  969. def call_docker(args):
  970. executable_path = find_executable('docker')
  971. if not executable_path:
  972. raise UserError(errors.docker_not_found_msg("Couldn't find `docker` binary."))
  973. args = [executable_path] + args
  974. log.debug(" ".join(map(pipes.quote, args)))
  975. return subprocess.call(args)