1
0

main.py 32 KB

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