main.py 31 KB

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