main.py 33 KB

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