main.py 26 KB

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