main.py 28 KB

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