main.py 40 KB

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