main.py 31 KB

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