main.py 29 KB

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