main.py 31 KB

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