main.py 26 KB

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