main.py 33 KB

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