main.py 32 KB

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