main.py 32 KB

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