main.py 32 KB

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