main.py 30 KB

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