main.py 30 KB

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