main.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. from __future__ import absolute_import
  2. from __future__ import print_function
  3. from __future__ import unicode_literals
  4. import contextlib
  5. import json
  6. import logging
  7. import re
  8. import sys
  9. from inspect import getdoc
  10. from operator import attrgetter
  11. from docker.errors import APIError
  12. from requests.exceptions import ReadTimeout
  13. from . import signals
  14. from .. import __version__
  15. from ..config import config
  16. from ..config import ConfigurationError
  17. from ..config import parse_environment
  18. from ..config.serialize import serialize_config
  19. from ..const import DEFAULT_TIMEOUT
  20. from ..const import HTTP_TIMEOUT
  21. from ..const import IS_WINDOWS_PLATFORM
  22. from ..progress_stream import StreamOutputError
  23. from ..project import NoSuchService
  24. from ..service import BuildError
  25. from ..service import ConvergenceStrategy
  26. from ..service import ImageType
  27. from ..service import NeedsBuildError
  28. from .command import friendly_error_message
  29. from .command import get_config_path_from_options
  30. from .command import project_from_options
  31. from .docopt_command import DocoptCommand
  32. from .docopt_command import NoSuchCommand
  33. from .errors import UserError
  34. from .formatter import ConsoleWarningFormatter
  35. from .formatter import Formatter
  36. from .log_printer import LogPrinter
  37. from .utils import get_version_info
  38. from .utils import yesno
  39. if not IS_WINDOWS_PLATFORM:
  40. from dockerpty.pty import PseudoTerminal, RunOperation
  41. log = logging.getLogger(__name__)
  42. console_handler = logging.StreamHandler(sys.stderr)
  43. def main():
  44. setup_logging()
  45. try:
  46. command = TopLevelCommand()
  47. command.sys_dispatch()
  48. except KeyboardInterrupt:
  49. log.error("Aborting.")
  50. sys.exit(1)
  51. except (UserError, NoSuchService, ConfigurationError) as e:
  52. log.error(e.msg)
  53. sys.exit(1)
  54. except NoSuchCommand as e:
  55. commands = "\n".join(parse_doc_section("commands:", getdoc(e.supercommand)))
  56. log.error("No such command: %s\n\n%s", e.command, commands)
  57. sys.exit(1)
  58. except APIError as e:
  59. log.error(e.explanation)
  60. sys.exit(1)
  61. except BuildError as e:
  62. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  63. sys.exit(1)
  64. except StreamOutputError as e:
  65. log.error(e)
  66. sys.exit(1)
  67. except NeedsBuildError as e:
  68. log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name)
  69. sys.exit(1)
  70. except ReadTimeout as e:
  71. log.error(
  72. "An HTTP request took too long to complete. Retry with --verbose to "
  73. "obtain debug information.\n"
  74. "If you encounter this issue regularly because of slow network "
  75. "conditions, consider setting COMPOSE_HTTP_TIMEOUT to a higher "
  76. "value (current value: %s)." % HTTP_TIMEOUT
  77. )
  78. sys.exit(1)
  79. def setup_logging():
  80. root_logger = logging.getLogger()
  81. root_logger.addHandler(console_handler)
  82. root_logger.setLevel(logging.DEBUG)
  83. # Disable requests logging
  84. logging.getLogger("requests").propagate = False
  85. def setup_console_handler(handler, verbose):
  86. if handler.stream.isatty():
  87. format_class = ConsoleWarningFormatter
  88. else:
  89. format_class = logging.Formatter
  90. if verbose:
  91. handler.setFormatter(format_class('%(name)s.%(funcName)s: %(message)s'))
  92. handler.setLevel(logging.DEBUG)
  93. else:
  94. handler.setFormatter(format_class())
  95. handler.setLevel(logging.INFO)
  96. # stolen from docopt master
  97. def parse_doc_section(name, source):
  98. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  99. re.IGNORECASE | re.MULTILINE)
  100. return [s.strip() for s in pattern.findall(source)]
  101. class TopLevelCommand(DocoptCommand):
  102. """Define and run multi-container applications with Docker.
  103. Usage:
  104. docker-compose [-f=<arg>...] [options] [COMMAND] [ARGS...]
  105. docker-compose -h|--help
  106. Options:
  107. -f, --file FILE Specify an alternate compose file (default: docker-compose.yml)
  108. -p, --project-name NAME Specify an alternate project name (default: directory name)
  109. --verbose Show more output
  110. -v, --version Print version and exit
  111. Commands:
  112. build Build or rebuild services
  113. config Validate and view the compose file
  114. create Create services
  115. down Stop and remove containers, networks, images, and volumes
  116. events Receive real time events from containers
  117. help Get help on a command
  118. kill Kill containers
  119. logs View output from containers
  120. pause Pause services
  121. port Print the public port for a port binding
  122. ps List containers
  123. pull Pulls service images
  124. restart Restart services
  125. rm Remove stopped containers
  126. run Run a one-off command
  127. scale Set number of containers for a service
  128. start Start services
  129. stop Stop services
  130. unpause Unpause services
  131. up Create and start containers
  132. version Show the Docker-Compose version information
  133. """
  134. base_dir = '.'
  135. def docopt_options(self):
  136. options = super(TopLevelCommand, self).docopt_options()
  137. options['version'] = get_version_info('compose')
  138. return options
  139. def perform_command(self, options, handler, command_options):
  140. setup_console_handler(console_handler, options.get('--verbose'))
  141. if options['COMMAND'] in ('help', 'version'):
  142. # Skip looking up the compose file.
  143. handler(None, command_options)
  144. return
  145. if options['COMMAND'] == 'config':
  146. handler(options, command_options)
  147. return
  148. project = project_from_options(self.base_dir, options)
  149. with friendly_error_message():
  150. handler(project, command_options)
  151. def build(self, project, options):
  152. """
  153. Build or rebuild services.
  154. Services are built once and then tagged as `project_service`,
  155. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  156. contents of its build directory, you can run `docker-compose build` to rebuild it.
  157. Usage: build [options] [SERVICE...]
  158. Options:
  159. --force-rm Always remove intermediate containers.
  160. --no-cache Do not use cache when building the image.
  161. --pull Always attempt to pull a newer version of the image.
  162. """
  163. project.build(
  164. service_names=options['SERVICE'],
  165. no_cache=bool(options.get('--no-cache', False)),
  166. pull=bool(options.get('--pull', False)),
  167. force_rm=bool(options.get('--force-rm', False)))
  168. def config(self, config_options, options):
  169. """
  170. Validate and view the compose file.
  171. Usage: config [options]
  172. Options:
  173. -q, --quiet Only validate the configuration, don't print
  174. anything.
  175. --services Print the service names, one per line.
  176. """
  177. config_path = get_config_path_from_options(config_options)
  178. compose_config = config.load(config.find(self.base_dir, config_path))
  179. if options['--quiet']:
  180. return
  181. if options['--services']:
  182. print('\n'.join(service['name'] for service in compose_config.services))
  183. return
  184. print(serialize_config(compose_config))
  185. def create(self, project, options):
  186. """
  187. Creates containers for a service.
  188. Usage: create [options] [SERVICE...]
  189. Options:
  190. --force-recreate Recreate containers even if their configuration and
  191. image haven't changed. Incompatible with --no-recreate.
  192. --no-recreate If containers already exist, don't recreate them.
  193. Incompatible with --force-recreate.
  194. --no-build Don't build an image, even if it's missing
  195. """
  196. service_names = options['SERVICE']
  197. project.create(
  198. service_names=service_names,
  199. strategy=convergence_strategy_from_opts(options),
  200. do_build=not options['--no-build']
  201. )
  202. def down(self, project, options):
  203. """
  204. Stop containers and remove containers, networks, volumes, and images
  205. created by `up`. Only containers and networks are removed by default.
  206. Usage: down [options]
  207. Options:
  208. --rmi type Remove images, type may be one of: 'all' to remove
  209. all images, or 'local' to remove only images that
  210. don't have an custom name set by the `image` field
  211. -v, --volumes Remove data volumes
  212. """
  213. image_type = image_type_from_opt('--rmi', options['--rmi'])
  214. project.down(image_type, options['--volumes'])
  215. def events(self, project, options):
  216. """
  217. Receive real time events from containers.
  218. Usage: events [options] [SERVICE...]
  219. Options:
  220. --json Output events as a stream of json objects
  221. """
  222. def format_event(event):
  223. attributes = ["%s=%s" % item for item in event['attributes'].items()]
  224. return ("{time} {type} {action} {id} ({attrs})").format(
  225. attrs=", ".join(sorted(attributes)),
  226. **event)
  227. def json_format_event(event):
  228. event['time'] = event['time'].isoformat()
  229. return json.dumps(event)
  230. for event in project.events():
  231. formatter = json_format_event if options['--json'] else format_event
  232. print(formatter(event))
  233. sys.stdout.flush()
  234. def help(self, project, options):
  235. """
  236. Get help on a command.
  237. Usage: help COMMAND
  238. """
  239. handler = self.get_handler(options['COMMAND'])
  240. raise SystemExit(getdoc(handler))
  241. def kill(self, project, options):
  242. """
  243. Force stop service containers.
  244. Usage: kill [options] [SERVICE...]
  245. Options:
  246. -s SIGNAL SIGNAL to send to the container.
  247. Default signal is SIGKILL.
  248. """
  249. signal = options.get('-s', 'SIGKILL')
  250. project.kill(service_names=options['SERVICE'], signal=signal)
  251. def logs(self, project, options):
  252. """
  253. View output from containers.
  254. Usage: logs [options] [SERVICE...]
  255. Options:
  256. --no-color Produce monochrome output.
  257. """
  258. containers = project.containers(service_names=options['SERVICE'], stopped=True)
  259. monochrome = options['--no-color']
  260. print("Attaching to", list_containers(containers))
  261. LogPrinter(containers, monochrome=monochrome).run()
  262. def pause(self, project, options):
  263. """
  264. Pause services.
  265. Usage: pause [SERVICE...]
  266. """
  267. containers = project.pause(service_names=options['SERVICE'])
  268. exit_if(not containers, 'No containers to pause', 1)
  269. def port(self, project, options):
  270. """
  271. Print the public port for a port binding.
  272. Usage: port [options] SERVICE PRIVATE_PORT
  273. Options:
  274. --protocol=proto tcp or udp [default: tcp]
  275. --index=index index of the container if there are multiple
  276. instances of a service [default: 1]
  277. """
  278. index = int(options.get('--index'))
  279. service = project.get_service(options['SERVICE'])
  280. try:
  281. container = service.get_container(number=index)
  282. except ValueError as e:
  283. raise UserError(str(e))
  284. print(container.get_local_port(
  285. options['PRIVATE_PORT'],
  286. protocol=options.get('--protocol') or 'tcp') or '')
  287. def ps(self, project, options):
  288. """
  289. List containers.
  290. Usage: ps [options] [SERVICE...]
  291. Options:
  292. -q Only display IDs
  293. """
  294. containers = sorted(
  295. project.containers(service_names=options['SERVICE'], stopped=True) +
  296. project.containers(service_names=options['SERVICE'], one_off=True),
  297. key=attrgetter('name'))
  298. if options['-q']:
  299. for container in containers:
  300. print(container.id)
  301. else:
  302. headers = [
  303. 'Name',
  304. 'Command',
  305. 'State',
  306. 'Ports',
  307. ]
  308. rows = []
  309. for container in containers:
  310. command = container.human_readable_command
  311. if len(command) > 30:
  312. command = '%s ...' % command[:26]
  313. rows.append([
  314. container.name,
  315. command,
  316. container.human_readable_state,
  317. container.human_readable_ports,
  318. ])
  319. print(Formatter().table(headers, rows))
  320. def pull(self, project, options):
  321. """
  322. Pulls images for services.
  323. Usage: pull [options] [SERVICE...]
  324. Options:
  325. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  326. """
  327. project.pull(
  328. service_names=options['SERVICE'],
  329. ignore_pull_failures=options.get('--ignore-pull-failures')
  330. )
  331. def rm(self, project, options):
  332. """
  333. Remove stopped service containers.
  334. By default, volumes attached to containers will not be removed. You can see all
  335. volumes with `docker volume ls`.
  336. Any data which is not in a volume will be lost.
  337. Usage: rm [options] [SERVICE...]
  338. Options:
  339. -f, --force Don't ask to confirm removal
  340. -v Remove volumes associated with containers
  341. """
  342. all_containers = project.containers(service_names=options['SERVICE'], stopped=True)
  343. stopped_containers = [c for c in all_containers if not c.is_running]
  344. if len(stopped_containers) > 0:
  345. print("Going to remove", list_containers(stopped_containers))
  346. if options.get('--force') \
  347. or yesno("Are you sure? [yN] ", default=False):
  348. project.remove_stopped(
  349. service_names=options['SERVICE'],
  350. v=options.get('-v', False)
  351. )
  352. else:
  353. print("No stopped containers")
  354. def run(self, project, options):
  355. """
  356. Run a one-off command on a service.
  357. For example:
  358. $ docker-compose run web python manage.py shell
  359. By default, linked services will be started, unless they are already
  360. running. If you do not want to start linked services, use
  361. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  362. Usage: run [options] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  363. Options:
  364. -d Detached mode: Run container in the background, print
  365. new container name.
  366. --name NAME Assign a name to the container
  367. --entrypoint CMD Override the entrypoint of the image.
  368. -e KEY=VAL Set an environment variable (can be used multiple times)
  369. -u, --user="" Run as specified username or uid
  370. --no-deps Don't start linked services.
  371. --rm Remove container after run. Ignored in detached mode.
  372. -p, --publish=[] Publish a container's port(s) to the host
  373. --service-ports Run command with the service's ports enabled and mapped
  374. to the host.
  375. -T Disable pseudo-tty allocation. By default `docker-compose run`
  376. allocates a TTY.
  377. """
  378. service = project.get_service(options['SERVICE'])
  379. detach = options['-d']
  380. if IS_WINDOWS_PLATFORM and not detach:
  381. raise UserError(
  382. "Interactive mode is not yet supported on Windows.\n"
  383. "Please pass the -d flag when using `docker-compose run`."
  384. )
  385. if options['COMMAND']:
  386. command = [options['COMMAND']] + options['ARGS']
  387. else:
  388. command = service.options.get('command')
  389. container_options = {
  390. 'command': command,
  391. 'tty': not (detach or options['-T'] or not sys.stdin.isatty()),
  392. 'stdin_open': not detach,
  393. 'detach': detach,
  394. }
  395. if options['-e']:
  396. container_options['environment'] = parse_environment(options['-e'])
  397. if options['--entrypoint']:
  398. container_options['entrypoint'] = options.get('--entrypoint')
  399. if options['--rm']:
  400. container_options['restart'] = None
  401. if options['--user']:
  402. container_options['user'] = options.get('--user')
  403. if not options['--service-ports']:
  404. container_options['ports'] = []
  405. if options['--publish']:
  406. container_options['ports'] = options.get('--publish')
  407. if options['--publish'] and options['--service-ports']:
  408. raise UserError(
  409. 'Service port mapping and manual port mapping '
  410. 'can not be used togather'
  411. )
  412. if options['--name']:
  413. container_options['name'] = options['--name']
  414. run_one_off_container(container_options, project, service, options)
  415. def scale(self, project, options):
  416. """
  417. Set number of containers to run for a service.
  418. Numbers are specified in the form `service=num` as arguments.
  419. For example:
  420. $ docker-compose scale web=2 worker=3
  421. Usage: scale [options] [SERVICE=NUM...]
  422. Options:
  423. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  424. (default: 10)
  425. """
  426. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  427. for s in options['SERVICE=NUM']:
  428. if '=' not in s:
  429. raise UserError('Arguments to scale should be in the form service=num')
  430. service_name, num = s.split('=', 1)
  431. try:
  432. num = int(num)
  433. except ValueError:
  434. raise UserError('Number of containers for service "%s" is not a '
  435. 'number' % service_name)
  436. project.get_service(service_name).scale(num, timeout=timeout)
  437. def start(self, project, options):
  438. """
  439. Start existing containers.
  440. Usage: start [SERVICE...]
  441. """
  442. containers = project.start(service_names=options['SERVICE'])
  443. exit_if(not containers, 'No containers to start', 1)
  444. def stop(self, project, options):
  445. """
  446. Stop running containers without removing them.
  447. They can be started again with `docker-compose start`.
  448. Usage: stop [options] [SERVICE...]
  449. Options:
  450. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  451. (default: 10)
  452. """
  453. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  454. project.stop(service_names=options['SERVICE'], timeout=timeout)
  455. def restart(self, project, options):
  456. """
  457. Restart running containers.
  458. Usage: restart [options] [SERVICE...]
  459. Options:
  460. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  461. (default: 10)
  462. """
  463. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  464. containers = project.restart(service_names=options['SERVICE'], timeout=timeout)
  465. exit_if(not containers, 'No containers to restart', 1)
  466. def unpause(self, project, options):
  467. """
  468. Unpause services.
  469. Usage: unpause [SERVICE...]
  470. """
  471. containers = project.unpause(service_names=options['SERVICE'])
  472. exit_if(not containers, 'No containers to unpause', 1)
  473. def up(self, project, options):
  474. """
  475. Builds, (re)creates, starts, and attaches to containers for a service.
  476. Unless they are already running, this command also starts any linked services.
  477. The `docker-compose up` command aggregates the output of each container. When
  478. the command exits, all containers are stopped. Running `docker-compose up -d`
  479. starts the containers in the background and leaves them running.
  480. If there are existing containers for a service, and the service's configuration
  481. or image was changed after the container's creation, `docker-compose up` picks
  482. up the changes by stopping and recreating the containers (preserving mounted
  483. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  484. flag.
  485. If you want to force Compose to stop and recreate all containers, use the
  486. `--force-recreate` flag.
  487. Usage: up [options] [SERVICE...]
  488. Options:
  489. -d Detached mode: Run containers in the background,
  490. print new container names.
  491. Incompatible with --abort-on-container-exit.
  492. --no-color Produce monochrome output.
  493. --no-deps Don't start linked services.
  494. --force-recreate Recreate containers even if their configuration
  495. and image haven't changed.
  496. Incompatible with --no-recreate.
  497. --no-recreate If containers already exist, don't recreate them.
  498. Incompatible with --force-recreate.
  499. --no-build Don't build an image, even if it's missing
  500. --abort-on-container-exit Stops all containers if any container was stopped.
  501. Incompatible with -d.
  502. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  503. when attached or when containers are already
  504. running. (default: 10)
  505. """
  506. monochrome = options['--no-color']
  507. start_deps = not options['--no-deps']
  508. cascade_stop = options['--abort-on-container-exit']
  509. service_names = options['SERVICE']
  510. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  511. detached = options.get('-d')
  512. if detached and cascade_stop:
  513. raise UserError("--abort-on-container-exit and -d cannot be combined.")
  514. with up_shutdown_context(project, service_names, timeout, detached):
  515. to_attach = project.up(
  516. service_names=service_names,
  517. start_deps=start_deps,
  518. strategy=convergence_strategy_from_opts(options),
  519. do_build=not options['--no-build'],
  520. timeout=timeout,
  521. detached=detached)
  522. if detached:
  523. return
  524. log_printer = build_log_printer(to_attach, service_names, monochrome, cascade_stop)
  525. print("Attaching to", list_containers(log_printer.containers))
  526. log_printer.run()
  527. def version(self, project, options):
  528. """
  529. Show version informations
  530. Usage: version [--short]
  531. Options:
  532. --short Shows only Compose's version number.
  533. """
  534. if options['--short']:
  535. print(__version__)
  536. else:
  537. print(get_version_info('full'))
  538. def convergence_strategy_from_opts(options):
  539. no_recreate = options['--no-recreate']
  540. force_recreate = options['--force-recreate']
  541. if force_recreate and no_recreate:
  542. raise UserError("--force-recreate and --no-recreate cannot be combined.")
  543. if force_recreate:
  544. return ConvergenceStrategy.always
  545. if no_recreate:
  546. return ConvergenceStrategy.never
  547. return ConvergenceStrategy.changed
  548. def image_type_from_opt(flag, value):
  549. if not value:
  550. return ImageType.none
  551. try:
  552. return ImageType[value]
  553. except KeyError:
  554. raise UserError("%s flag must be one of: all, local" % flag)
  555. def run_one_off_container(container_options, project, service, options):
  556. if not options['--no-deps']:
  557. deps = service.get_linked_service_names()
  558. if deps:
  559. project.up(
  560. service_names=deps,
  561. start_deps=True,
  562. strategy=ConvergenceStrategy.never)
  563. project.initialize()
  564. container = service.create_container(
  565. quiet=True,
  566. one_off=True,
  567. **container_options)
  568. if options['-d']:
  569. service.start_container(container)
  570. print(container.name)
  571. return
  572. def remove_container(force=False):
  573. if options['--rm']:
  574. project.client.remove_container(container.id, force=True)
  575. signals.set_signal_handler_to_shutdown()
  576. try:
  577. try:
  578. operation = RunOperation(
  579. project.client,
  580. container.id,
  581. interactive=not options['-T'],
  582. logs=False,
  583. )
  584. pty = PseudoTerminal(project.client, operation)
  585. sockets = pty.sockets()
  586. service.start_container(container)
  587. pty.start(sockets)
  588. exit_code = container.wait()
  589. except signals.ShutdownException:
  590. project.client.stop(container.id)
  591. exit_code = 1
  592. except signals.ShutdownException:
  593. project.client.kill(container.id)
  594. remove_container(force=True)
  595. sys.exit(2)
  596. remove_container()
  597. sys.exit(exit_code)
  598. def build_log_printer(containers, service_names, monochrome, cascade_stop):
  599. if service_names:
  600. containers = [
  601. container
  602. for container in containers if container.service in service_names
  603. ]
  604. return LogPrinter(containers, monochrome=monochrome, cascade_stop=cascade_stop)
  605. @contextlib.contextmanager
  606. def up_shutdown_context(project, service_names, timeout, detached):
  607. if detached:
  608. yield
  609. return
  610. signals.set_signal_handler_to_shutdown()
  611. try:
  612. try:
  613. yield
  614. except signals.ShutdownException:
  615. print("Gracefully stopping... (press Ctrl+C again to force)")
  616. project.stop(service_names=service_names, timeout=timeout)
  617. except signals.ShutdownException:
  618. project.kill(service_names=service_names)
  619. sys.exit(2)
  620. def list_containers(containers):
  621. return ", ".join(c.name for c in containers)
  622. def exit_if(condition, message, exit_code):
  623. if condition:
  624. log.error(message)
  625. raise SystemExit(exit_code)