main.py 31 KB

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