main.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  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 pipes
  9. import re
  10. import subprocess
  11. import sys
  12. from distutils.spawn import find_executable
  13. from inspect import getdoc
  14. from operator import attrgetter
  15. import docker
  16. from . import errors
  17. from . import signals
  18. from .. import __version__
  19. from ..bundle import get_image_digests
  20. from ..bundle import MissingDigests
  21. from ..bundle import serialize_bundle
  22. from ..config import ConfigurationError
  23. from ..config import parse_environment
  24. from ..config import parse_labels
  25. from ..config import resolve_build_args
  26. from ..config.environment import Environment
  27. from ..config.serialize import serialize_config
  28. from ..config.types import VolumeSpec
  29. from ..const import COMPOSEFILE_V2_2 as V2_2
  30. from ..const import IS_WINDOWS_PLATFORM
  31. from ..errors import StreamParseError
  32. from ..progress_stream import StreamOutputError
  33. from ..project import NoSuchService
  34. from ..project import OneOffFilter
  35. from ..project import ProjectError
  36. from ..service import BuildAction
  37. from ..service import BuildError
  38. from ..service import ConvergenceStrategy
  39. from ..service import ImageType
  40. from ..service import NeedsBuildError
  41. from ..service import OperationFailedError
  42. from .command import get_config_from_options
  43. from .command import project_from_options
  44. from .docopt_command import DocoptDispatcher
  45. from .docopt_command import get_handler
  46. from .docopt_command import NoSuchCommand
  47. from .errors import UserError
  48. from .formatter import ConsoleWarningFormatter
  49. from .formatter import Formatter
  50. from .log_printer import build_log_presenters
  51. from .log_printer import LogPrinter
  52. from .utils import get_version_info
  53. from .utils import human_readable_file_size
  54. from .utils import yesno
  55. if not IS_WINDOWS_PLATFORM:
  56. from dockerpty.pty import PseudoTerminal, RunOperation, ExecOperation
  57. log = logging.getLogger(__name__)
  58. console_handler = logging.StreamHandler(sys.stderr)
  59. def main():
  60. signals.ignore_sigpipe()
  61. try:
  62. command = dispatch()
  63. command()
  64. except (KeyboardInterrupt, signals.ShutdownException):
  65. log.error("Aborting.")
  66. sys.exit(1)
  67. except (UserError, NoSuchService, ConfigurationError,
  68. ProjectError, OperationFailedError) as e:
  69. log.error(e.msg)
  70. sys.exit(1)
  71. except BuildError as e:
  72. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  73. sys.exit(1)
  74. except StreamOutputError as e:
  75. log.error(e)
  76. sys.exit(1)
  77. except NeedsBuildError as e:
  78. log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name)
  79. sys.exit(1)
  80. except NoSuchCommand as e:
  81. commands = "\n".join(parse_doc_section("commands:", getdoc(e.supercommand)))
  82. log.error("No such command: %s\n\n%s", e.command, commands)
  83. sys.exit(1)
  84. except (errors.ConnectionError, StreamParseError):
  85. sys.exit(1)
  86. def dispatch():
  87. setup_logging()
  88. dispatcher = DocoptDispatcher(
  89. TopLevelCommand,
  90. {'options_first': True, 'version': get_version_info('compose')})
  91. options, handler, command_options = dispatcher.parse(sys.argv[1:])
  92. setup_console_handler(console_handler,
  93. options.get('--verbose'),
  94. options.get('--no-ansi'),
  95. options.get("--log-level"))
  96. setup_parallel_logger(options.get('--no-ansi'))
  97. if options.get('--no-ansi'):
  98. command_options['--no-color'] = True
  99. return functools.partial(perform_command, options, handler, command_options)
  100. def perform_command(options, handler, command_options):
  101. if options['COMMAND'] in ('help', 'version'):
  102. # Skip looking up the compose file.
  103. handler(command_options)
  104. return
  105. if options['COMMAND'] == 'config':
  106. command = TopLevelCommand(None, options=options)
  107. handler(command, command_options)
  108. return
  109. project = project_from_options('.', options)
  110. command = TopLevelCommand(project, options=options)
  111. with errors.handle_connection_errors(project.client):
  112. handler(command, command_options)
  113. def setup_logging():
  114. root_logger = logging.getLogger()
  115. root_logger.addHandler(console_handler)
  116. root_logger.setLevel(logging.DEBUG)
  117. # Disable requests logging
  118. logging.getLogger("requests").propagate = False
  119. def setup_parallel_logger(noansi):
  120. if noansi:
  121. import compose.parallel
  122. compose.parallel.ParallelStreamWriter.set_noansi()
  123. def setup_console_handler(handler, verbose, noansi=False, level=None):
  124. if handler.stream.isatty() and noansi is False:
  125. format_class = ConsoleWarningFormatter
  126. else:
  127. format_class = logging.Formatter
  128. if verbose:
  129. handler.setFormatter(format_class('%(name)s.%(funcName)s: %(message)s'))
  130. loglevel = logging.DEBUG
  131. else:
  132. handler.setFormatter(format_class())
  133. loglevel = logging.INFO
  134. if level is not None:
  135. levels = {
  136. 'DEBUG': logging.DEBUG,
  137. 'INFO': logging.INFO,
  138. 'WARNING': logging.WARNING,
  139. 'ERROR': logging.ERROR,
  140. 'CRITICAL': logging.CRITICAL,
  141. }
  142. loglevel = levels.get(level.upper())
  143. if loglevel is None:
  144. raise UserError(
  145. 'Invalid value for --log-level. Expected one of DEBUG, INFO, WARNING, ERROR, CRITICAL.'
  146. )
  147. handler.setLevel(loglevel)
  148. # stolen from docopt master
  149. def parse_doc_section(name, source):
  150. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  151. re.IGNORECASE | re.MULTILINE)
  152. return [s.strip() for s in pattern.findall(source)]
  153. class TopLevelCommand(object):
  154. """Define and run multi-container applications with Docker.
  155. Usage:
  156. docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  157. docker-compose -h|--help
  158. Options:
  159. -f, --file FILE Specify an alternate compose file
  160. (default: docker-compose.yml)
  161. -p, --project-name NAME Specify an alternate project name
  162. (default: directory name)
  163. --verbose Show more output
  164. --log-level LEVEL Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  165. --no-ansi Do not print ANSI control characters
  166. -v, --version Print version and exit
  167. -H, --host HOST Daemon socket to connect to
  168. --tls Use TLS; implied by --tlsverify
  169. --tlscacert CA_PATH Trust certs signed only by this CA
  170. --tlscert CLIENT_CERT_PATH Path to TLS certificate file
  171. --tlskey TLS_KEY_PATH Path to TLS key file
  172. --tlsverify Use TLS and verify the remote
  173. --skip-hostname-check Don't check the daemon's hostname against the
  174. name specified in the client certificate
  175. --project-directory PATH Specify an alternate working directory
  176. (default: the path of the Compose file)
  177. --compatibility If set, Compose will attempt to convert deploy
  178. keys in v3 files to their non-Swarm equivalent
  179. Commands:
  180. build Build or rebuild services
  181. bundle Generate a Docker bundle from the Compose file
  182. config Validate and view the Compose file
  183. create Create services
  184. down Stop and remove containers, networks, images, and volumes
  185. events Receive real time events from containers
  186. exec Execute a command in a running container
  187. help Get help on a command
  188. images List images
  189. kill Kill containers
  190. logs View output from containers
  191. pause Pause services
  192. port Print the public port for a port binding
  193. ps List containers
  194. pull Pull service images
  195. push Push service images
  196. restart Restart services
  197. rm Remove stopped containers
  198. run Run a one-off command
  199. scale Set number of containers for a service
  200. start Start services
  201. stop Stop services
  202. top Display the running processes
  203. unpause Unpause services
  204. up Create and start containers
  205. version Show the Docker-Compose version information
  206. """
  207. def __init__(self, project, project_dir='.', options=None):
  208. self.project = project
  209. self.project_dir = '.'
  210. self.toplevel_options = options or {}
  211. def build(self, options):
  212. """
  213. Build or rebuild services.
  214. Services are built once and then tagged as `project_service`,
  215. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  216. contents of its build directory, you can run `docker-compose build` to rebuild it.
  217. Usage: build [options] [--build-arg key=val...] [SERVICE...]
  218. Options:
  219. --compress Compress the build context using gzip.
  220. --force-rm Always remove intermediate containers.
  221. --no-cache Do not use cache when building the image.
  222. --pull Always attempt to pull a newer version of the image.
  223. -m, --memory MEM Sets memory limit for the build container.
  224. --build-arg key=val Set build-time variables for services.
  225. --parallel Build images in parallel.
  226. """
  227. service_names = options['SERVICE']
  228. build_args = options.get('--build-arg', None)
  229. if build_args:
  230. if not service_names and docker.utils.version_lt(self.project.client.api_version, '1.25'):
  231. raise UserError(
  232. '--build-arg is only supported when services are specified for API version < 1.25.'
  233. ' Please use a Compose file version > 2.2 or specify which services to build.'
  234. )
  235. environment = Environment.from_env_file(self.project_dir)
  236. build_args = resolve_build_args(build_args, environment)
  237. self.project.build(
  238. service_names=options['SERVICE'],
  239. no_cache=bool(options.get('--no-cache', False)),
  240. pull=bool(options.get('--pull', False)),
  241. force_rm=bool(options.get('--force-rm', False)),
  242. memory=options.get('--memory'),
  243. build_args=build_args,
  244. gzip=options.get('--compress', False),
  245. parallel_build=options.get('--parallel', False),
  246. )
  247. def bundle(self, options):
  248. """
  249. Generate a Distributed Application Bundle (DAB) from the Compose file.
  250. Images must have digests stored, which requires interaction with a
  251. Docker registry. If digests aren't stored for all images, you can fetch
  252. them with `docker-compose pull` or `docker-compose push`. To push images
  253. automatically when bundling, pass `--push-images`. Only services with
  254. a `build` option specified will have their images pushed.
  255. Usage: bundle [options]
  256. Options:
  257. --push-images Automatically push images for any services
  258. which have a `build` option specified.
  259. -o, --output PATH Path to write the bundle file to.
  260. Defaults to "<project name>.dab".
  261. """
  262. compose_config = get_config_from_options(self.project_dir, self.toplevel_options)
  263. output = options["--output"]
  264. if not output:
  265. output = "{}.dab".format(self.project.name)
  266. image_digests = image_digests_for_project(self.project, options['--push-images'])
  267. with open(output, 'w') as f:
  268. f.write(serialize_bundle(compose_config, image_digests))
  269. log.info("Wrote bundle to {}".format(output))
  270. def config(self, options):
  271. """
  272. Validate and view the Compose file.
  273. Usage: config [options]
  274. Options:
  275. --resolve-image-digests Pin image tags to digests.
  276. -q, --quiet Only validate the configuration, don't print
  277. anything.
  278. --services Print the service names, one per line.
  279. --volumes Print the volume names, one per line.
  280. --hash="*" Print the service config hash, one per line.
  281. Set "service1,service2" for a list of specified services
  282. or use the wildcard symbol to display all services
  283. """
  284. compose_config = get_config_from_options(self.project_dir, self.toplevel_options)
  285. image_digests = None
  286. if options['--resolve-image-digests']:
  287. self.project = project_from_options('.', self.toplevel_options)
  288. with errors.handle_connection_errors(self.project.client):
  289. image_digests = image_digests_for_project(self.project)
  290. if options['--quiet']:
  291. return
  292. if options['--services']:
  293. print('\n'.join(service['name'] for service in compose_config.services))
  294. return
  295. if options['--volumes']:
  296. print('\n'.join(volume for volume in compose_config.volumes))
  297. return
  298. if options['--hash'] is not None:
  299. h = options['--hash']
  300. self.project = project_from_options('.', self.toplevel_options)
  301. services = [svc for svc in options['--hash'].split(',')] if h != '*' else None
  302. with errors.handle_connection_errors(self.project.client):
  303. for service in self.project.get_services(services):
  304. print('{} {}'.format(service.name, service.config_hash))
  305. return
  306. print(serialize_config(compose_config, image_digests))
  307. def create(self, options):
  308. """
  309. Creates containers for a service.
  310. This command is deprecated. Use the `up` command with `--no-start` instead.
  311. Usage: create [options] [SERVICE...]
  312. Options:
  313. --force-recreate Recreate containers even if their configuration and
  314. image haven't changed. Incompatible with --no-recreate.
  315. --no-recreate If containers already exist, don't recreate them.
  316. Incompatible with --force-recreate.
  317. --no-build Don't build an image, even if it's missing.
  318. --build Build images before creating containers.
  319. """
  320. service_names = options['SERVICE']
  321. log.warn(
  322. 'The create command is deprecated. '
  323. 'Use the up command with the --no-start flag instead.'
  324. )
  325. self.project.create(
  326. service_names=service_names,
  327. strategy=convergence_strategy_from_opts(options),
  328. do_build=build_action_from_opts(options),
  329. )
  330. def down(self, options):
  331. """
  332. Stops containers and removes containers, networks, volumes, and images
  333. created by `up`.
  334. By default, the only things removed are:
  335. - Containers for services defined in the Compose file
  336. - Networks defined in the `networks` section of the Compose file
  337. - The default network, if one is used
  338. Networks and volumes defined as `external` are never removed.
  339. Usage: down [options]
  340. Options:
  341. --rmi type Remove images. Type must be one of:
  342. 'all': Remove all images used by any service.
  343. 'local': Remove only images that don't have a
  344. custom tag set by the `image` field.
  345. -v, --volumes Remove named volumes declared in the `volumes`
  346. section of the Compose file and anonymous volumes
  347. attached to containers.
  348. --remove-orphans Remove containers for services not defined in the
  349. Compose file
  350. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  351. (default: 10)
  352. """
  353. environment = Environment.from_env_file(self.project_dir)
  354. ignore_orphans = environment.get_boolean('COMPOSE_IGNORE_ORPHANS')
  355. if ignore_orphans and options['--remove-orphans']:
  356. raise UserError("COMPOSE_IGNORE_ORPHANS and --remove-orphans cannot be combined.")
  357. image_type = image_type_from_opt('--rmi', options['--rmi'])
  358. timeout = timeout_from_opts(options)
  359. self.project.down(
  360. image_type,
  361. options['--volumes'],
  362. options['--remove-orphans'],
  363. timeout=timeout,
  364. ignore_orphans=ignore_orphans)
  365. def events(self, options):
  366. """
  367. Receive real time events from containers.
  368. Usage: events [options] [SERVICE...]
  369. Options:
  370. --json Output events as a stream of json objects
  371. """
  372. def format_event(event):
  373. attributes = ["%s=%s" % item for item in event['attributes'].items()]
  374. return ("{time} {type} {action} {id} ({attrs})").format(
  375. attrs=", ".join(sorted(attributes)),
  376. **event)
  377. def json_format_event(event):
  378. event['time'] = event['time'].isoformat()
  379. event.pop('container')
  380. return json.dumps(event)
  381. for event in self.project.events():
  382. formatter = json_format_event if options['--json'] else format_event
  383. print(formatter(event))
  384. sys.stdout.flush()
  385. def exec_command(self, options):
  386. """
  387. Execute a command in a running container
  388. Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]
  389. Options:
  390. -d, --detach Detached mode: Run command in the background.
  391. --privileged Give extended privileges to the process.
  392. -u, --user USER Run the command as this user.
  393. -T Disable pseudo-tty allocation. By default `docker-compose exec`
  394. allocates a TTY.
  395. --index=index index of the container if there are multiple
  396. instances of a service [default: 1]
  397. -e, --env KEY=VAL Set environment variables (can be used multiple times,
  398. not supported in API < 1.25)
  399. -w, --workdir DIR Path to workdir directory for this command.
  400. """
  401. environment = Environment.from_env_file(self.project_dir)
  402. use_cli = not environment.get_boolean('COMPOSE_INTERACTIVE_NO_CLI')
  403. index = int(options.get('--index'))
  404. service = self.project.get_service(options['SERVICE'])
  405. detach = options.get('--detach')
  406. if options['--env'] and docker.utils.version_lt(self.project.client.api_version, '1.25'):
  407. raise UserError("Setting environment for exec is not supported in API < 1.25 (%s)"
  408. % self.project.client.api_version)
  409. if options['--workdir'] and docker.utils.version_lt(self.project.client.api_version, '1.35'):
  410. raise UserError("Setting workdir for exec is not supported in API < 1.35 (%s)"
  411. % self.project.client.api_version)
  412. try:
  413. container = service.get_container(number=index)
  414. except ValueError as e:
  415. raise UserError(str(e))
  416. command = [options['COMMAND']] + options['ARGS']
  417. tty = not options["-T"]
  418. if IS_WINDOWS_PLATFORM or use_cli and not detach:
  419. sys.exit(call_docker(
  420. build_exec_command(options, container.id, command),
  421. self.toplevel_options)
  422. )
  423. create_exec_options = {
  424. "privileged": options["--privileged"],
  425. "user": options["--user"],
  426. "tty": tty,
  427. "stdin": True,
  428. "workdir": options["--workdir"],
  429. }
  430. if docker.utils.version_gte(self.project.client.api_version, '1.25'):
  431. create_exec_options["environment"] = options["--env"]
  432. exec_id = container.create_exec(command, **create_exec_options)
  433. if detach:
  434. container.start_exec(exec_id, tty=tty, stream=True)
  435. return
  436. signals.set_signal_handler_to_shutdown()
  437. try:
  438. operation = ExecOperation(
  439. self.project.client,
  440. exec_id,
  441. interactive=tty,
  442. )
  443. pty = PseudoTerminal(self.project.client, operation)
  444. pty.start()
  445. except signals.ShutdownException:
  446. log.info("received shutdown exception: closing")
  447. exit_code = self.project.client.exec_inspect(exec_id).get("ExitCode")
  448. sys.exit(exit_code)
  449. @classmethod
  450. def help(cls, options):
  451. """
  452. Get help on a command.
  453. Usage: help [COMMAND]
  454. """
  455. if options['COMMAND']:
  456. subject = get_handler(cls, options['COMMAND'])
  457. else:
  458. subject = cls
  459. print(getdoc(subject))
  460. def images(self, options):
  461. """
  462. List images used by the created containers.
  463. Usage: images [options] [SERVICE...]
  464. Options:
  465. -q, --quiet Only display IDs
  466. """
  467. containers = sorted(
  468. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  469. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  470. key=attrgetter('name'))
  471. if options['--quiet']:
  472. for image in set(c.image for c in containers):
  473. print(image.split(':')[1])
  474. else:
  475. headers = [
  476. 'Container',
  477. 'Repository',
  478. 'Tag',
  479. 'Image Id',
  480. 'Size'
  481. ]
  482. rows = []
  483. for container in containers:
  484. image_config = container.image_config
  485. repo_tags = (
  486. image_config['RepoTags'][0].rsplit(':', 1) if image_config['RepoTags']
  487. else ('<none>', '<none>')
  488. )
  489. image_id = image_config['Id'].split(':')[1][:12]
  490. size = human_readable_file_size(image_config['Size'])
  491. rows.append([
  492. container.name,
  493. repo_tags[0],
  494. repo_tags[1],
  495. image_id,
  496. size
  497. ])
  498. print(Formatter().table(headers, rows))
  499. def kill(self, options):
  500. """
  501. Force stop service containers.
  502. Usage: kill [options] [SERVICE...]
  503. Options:
  504. -s SIGNAL SIGNAL to send to the container.
  505. Default signal is SIGKILL.
  506. """
  507. signal = options.get('-s', 'SIGKILL')
  508. self.project.kill(service_names=options['SERVICE'], signal=signal)
  509. def logs(self, options):
  510. """
  511. View output from containers.
  512. Usage: logs [options] [SERVICE...]
  513. Options:
  514. --no-color Produce monochrome output.
  515. -f, --follow Follow log output.
  516. -t, --timestamps Show timestamps.
  517. --tail="all" Number of lines to show from the end of the logs
  518. for each container.
  519. """
  520. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  521. tail = options['--tail']
  522. if tail is not None:
  523. if tail.isdigit():
  524. tail = int(tail)
  525. elif tail != 'all':
  526. raise UserError("tail flag must be all or a number")
  527. log_args = {
  528. 'follow': options['--follow'],
  529. 'tail': tail,
  530. 'timestamps': options['--timestamps']
  531. }
  532. print("Attaching to", list_containers(containers))
  533. log_printer_from_project(
  534. self.project,
  535. containers,
  536. options['--no-color'],
  537. log_args,
  538. event_stream=self.project.events(service_names=options['SERVICE'])).run()
  539. def pause(self, options):
  540. """
  541. Pause services.
  542. Usage: pause [SERVICE...]
  543. """
  544. containers = self.project.pause(service_names=options['SERVICE'])
  545. exit_if(not containers, 'No containers to pause', 1)
  546. def port(self, options):
  547. """
  548. Print the public port for a port binding.
  549. Usage: port [options] SERVICE PRIVATE_PORT
  550. Options:
  551. --protocol=proto tcp or udp [default: tcp]
  552. --index=index index of the container if there are multiple
  553. instances of a service [default: 1]
  554. """
  555. index = int(options.get('--index'))
  556. service = self.project.get_service(options['SERVICE'])
  557. try:
  558. container = service.get_container(number=index)
  559. except ValueError as e:
  560. raise UserError(str(e))
  561. print(container.get_local_port(
  562. options['PRIVATE_PORT'],
  563. protocol=options.get('--protocol') or 'tcp') or '')
  564. def ps(self, options):
  565. """
  566. List containers.
  567. Usage: ps [options] [SERVICE...]
  568. Options:
  569. -q, --quiet Only display IDs
  570. --services Display services
  571. --filter KEY=VAL Filter services by a property
  572. """
  573. if options['--quiet'] and options['--services']:
  574. raise UserError('--quiet and --services cannot be combined')
  575. if options['--services']:
  576. filt = build_filter(options.get('--filter'))
  577. services = self.project.services
  578. if filt:
  579. services = filter_services(filt, services, self.project)
  580. print('\n'.join(service.name for service in services))
  581. return
  582. containers = sorted(
  583. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  584. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  585. key=attrgetter('name'))
  586. if options['--quiet']:
  587. for container in containers:
  588. print(container.id)
  589. else:
  590. headers = [
  591. 'Name',
  592. 'Command',
  593. 'State',
  594. 'Ports',
  595. ]
  596. rows = []
  597. for container in containers:
  598. command = container.human_readable_command
  599. if len(command) > 30:
  600. command = '%s ...' % command[:26]
  601. rows.append([
  602. container.name,
  603. command,
  604. container.human_readable_state,
  605. container.human_readable_ports,
  606. ])
  607. print(Formatter().table(headers, rows))
  608. def pull(self, options):
  609. """
  610. Pulls images for services defined in a Compose file, but does not start the containers.
  611. Usage: pull [options] [SERVICE...]
  612. Options:
  613. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  614. --parallel Deprecated, pull multiple images in parallel (enabled by default).
  615. --no-parallel Disable parallel pulling.
  616. -q, --quiet Pull without printing progress information
  617. --include-deps Also pull services declared as dependencies
  618. """
  619. if options.get('--parallel'):
  620. log.warn('--parallel option is deprecated and will be removed in future versions.')
  621. self.project.pull(
  622. service_names=options['SERVICE'],
  623. ignore_pull_failures=options.get('--ignore-pull-failures'),
  624. parallel_pull=not options.get('--no-parallel'),
  625. silent=options.get('--quiet'),
  626. include_deps=options.get('--include-deps'),
  627. )
  628. def push(self, options):
  629. """
  630. Pushes images for services.
  631. Usage: push [options] [SERVICE...]
  632. Options:
  633. --ignore-push-failures Push what it can and ignores images with push failures.
  634. """
  635. self.project.push(
  636. service_names=options['SERVICE'],
  637. ignore_push_failures=options.get('--ignore-push-failures')
  638. )
  639. def rm(self, options):
  640. """
  641. Removes stopped service containers.
  642. By default, anonymous volumes attached to containers will not be removed. You
  643. can override this with `-v`. To list all volumes, use `docker volume ls`.
  644. Any data which is not in a volume will be lost.
  645. Usage: rm [options] [SERVICE...]
  646. Options:
  647. -f, --force Don't ask to confirm removal
  648. -s, --stop Stop the containers, if required, before removing
  649. -v Remove any anonymous volumes attached to containers
  650. -a, --all Deprecated - no effect.
  651. """
  652. if options.get('--all'):
  653. log.warn(
  654. '--all flag is obsolete. This is now the default behavior '
  655. 'of `docker-compose rm`'
  656. )
  657. one_off = OneOffFilter.include
  658. if options.get('--stop'):
  659. self.project.stop(service_names=options['SERVICE'], one_off=one_off)
  660. all_containers = self.project.containers(
  661. service_names=options['SERVICE'], stopped=True, one_off=one_off
  662. )
  663. stopped_containers = [c for c in all_containers if not c.is_running]
  664. if len(stopped_containers) > 0:
  665. print("Going to remove", list_containers(stopped_containers))
  666. if options.get('--force') \
  667. or yesno("Are you sure? [yN] ", default=False):
  668. self.project.remove_stopped(
  669. service_names=options['SERVICE'],
  670. v=options.get('-v', False),
  671. one_off=one_off
  672. )
  673. else:
  674. print("No stopped containers")
  675. def run(self, options):
  676. """
  677. Run a one-off command on a service.
  678. For example:
  679. $ docker-compose run web python manage.py shell
  680. By default, linked services will be started, unless they are already
  681. running. If you do not want to start linked services, use
  682. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  683. Usage:
  684. run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...]
  685. SERVICE [COMMAND] [ARGS...]
  686. Options:
  687. -d, --detach Detached mode: Run container in the background, print
  688. new container name.
  689. --name NAME Assign a name to the container
  690. --entrypoint CMD Override the entrypoint of the image.
  691. -e KEY=VAL Set an environment variable (can be used multiple times)
  692. -l, --label KEY=VAL Add or override a label (can be used multiple times)
  693. -u, --user="" Run as specified username or uid
  694. --no-deps Don't start linked services.
  695. --rm Remove container after run. Ignored in detached mode.
  696. -p, --publish=[] Publish a container's port(s) to the host
  697. --service-ports Run command with the service's ports enabled and mapped
  698. to the host.
  699. --use-aliases Use the service's network aliases in the network(s) the
  700. container connects to.
  701. -v, --volume=[] Bind mount a volume (default [])
  702. -T Disable pseudo-tty allocation. By default `docker-compose run`
  703. allocates a TTY.
  704. -w, --workdir="" Working directory inside the container
  705. """
  706. service = self.project.get_service(options['SERVICE'])
  707. detach = options.get('--detach')
  708. if options['--publish'] and options['--service-ports']:
  709. raise UserError(
  710. 'Service port mapping and manual port mapping '
  711. 'can not be used together'
  712. )
  713. if options['COMMAND'] is not None:
  714. command = [options['COMMAND']] + options['ARGS']
  715. elif options['--entrypoint'] is not None:
  716. command = []
  717. else:
  718. command = service.options.get('command')
  719. container_options = build_container_options(options, detach, command)
  720. run_one_off_container(
  721. container_options, self.project, service, options,
  722. self.toplevel_options, self.project_dir
  723. )
  724. def scale(self, options):
  725. """
  726. Set number of containers to run for a service.
  727. Numbers are specified in the form `service=num` as arguments.
  728. For example:
  729. $ docker-compose scale web=2 worker=3
  730. This command is deprecated. Use the up command with the `--scale` flag
  731. instead.
  732. Usage: scale [options] [SERVICE=NUM...]
  733. Options:
  734. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  735. (default: 10)
  736. """
  737. timeout = timeout_from_opts(options)
  738. if self.project.config_version == V2_2:
  739. raise UserError(
  740. 'The scale command is incompatible with the v2.2 format. '
  741. 'Use the up command with the --scale flag instead.'
  742. )
  743. else:
  744. log.warn(
  745. 'The scale command is deprecated. '
  746. 'Use the up command with the --scale flag instead.'
  747. )
  748. for service_name, num in parse_scale_args(options['SERVICE=NUM']).items():
  749. self.project.get_service(service_name).scale(num, timeout=timeout)
  750. def start(self, options):
  751. """
  752. Start existing containers.
  753. Usage: start [SERVICE...]
  754. """
  755. containers = self.project.start(service_names=options['SERVICE'])
  756. exit_if(not containers, 'No containers to start', 1)
  757. def stop(self, options):
  758. """
  759. Stop running containers without removing them.
  760. They can be started again with `docker-compose start`.
  761. Usage: stop [options] [SERVICE...]
  762. Options:
  763. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  764. (default: 10)
  765. """
  766. timeout = timeout_from_opts(options)
  767. self.project.stop(service_names=options['SERVICE'], timeout=timeout)
  768. def restart(self, options):
  769. """
  770. Restart running containers.
  771. Usage: restart [options] [SERVICE...]
  772. Options:
  773. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  774. (default: 10)
  775. """
  776. timeout = timeout_from_opts(options)
  777. containers = self.project.restart(service_names=options['SERVICE'], timeout=timeout)
  778. exit_if(not containers, 'No containers to restart', 1)
  779. def top(self, options):
  780. """
  781. Display the running processes
  782. Usage: top [SERVICE...]
  783. """
  784. containers = sorted(
  785. self.project.containers(service_names=options['SERVICE'], stopped=False) +
  786. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  787. key=attrgetter('name')
  788. )
  789. for idx, container in enumerate(containers):
  790. if idx > 0:
  791. print()
  792. top_data = self.project.client.top(container.name)
  793. headers = top_data.get("Titles")
  794. rows = []
  795. for process in top_data.get("Processes", []):
  796. rows.append(process)
  797. print(container.name)
  798. print(Formatter().table(headers, rows))
  799. def unpause(self, options):
  800. """
  801. Unpause services.
  802. Usage: unpause [SERVICE...]
  803. """
  804. containers = self.project.unpause(service_names=options['SERVICE'])
  805. exit_if(not containers, 'No containers to unpause', 1)
  806. def up(self, options):
  807. """
  808. Builds, (re)creates, starts, and attaches to containers for a service.
  809. Unless they are already running, this command also starts any linked services.
  810. The `docker-compose up` command aggregates the output of each container. When
  811. the command exits, all containers are stopped. Running `docker-compose up -d`
  812. starts the containers in the background and leaves them running.
  813. If there are existing containers for a service, and the service's configuration
  814. or image was changed after the container's creation, `docker-compose up` picks
  815. up the changes by stopping and recreating the containers (preserving mounted
  816. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  817. flag.
  818. If you want to force Compose to stop and recreate all containers, use the
  819. `--force-recreate` flag.
  820. Usage: up [options] [--scale SERVICE=NUM...] [SERVICE...]
  821. Options:
  822. -d, --detach Detached mode: Run containers in the background,
  823. print new container names. Incompatible with
  824. --abort-on-container-exit.
  825. --no-color Produce monochrome output.
  826. --quiet-pull Pull without printing progress information
  827. --no-deps Don't start linked services.
  828. --force-recreate Recreate containers even if their configuration
  829. and image haven't changed.
  830. --always-recreate-deps Recreate dependent containers.
  831. Incompatible with --no-recreate.
  832. --no-recreate If containers already exist, don't recreate
  833. them. Incompatible with --force-recreate and -V.
  834. --no-build Don't build an image, even if it's missing.
  835. --no-start Don't start the services after creating them.
  836. --build Build images before starting containers.
  837. --abort-on-container-exit Stops all containers if any container was
  838. stopped. Incompatible with -d.
  839. -t, --timeout TIMEOUT Use this timeout in seconds for container
  840. shutdown when attached or when containers are
  841. already running. (default: 10)
  842. -V, --renew-anon-volumes Recreate anonymous volumes instead of retrieving
  843. data from the previous containers.
  844. --remove-orphans Remove containers for services not defined
  845. in the Compose file.
  846. --exit-code-from SERVICE Return the exit code of the selected service
  847. container. Implies --abort-on-container-exit.
  848. --scale SERVICE=NUM Scale SERVICE to NUM instances. Overrides the
  849. `scale` setting in the Compose file if present.
  850. """
  851. start_deps = not options['--no-deps']
  852. always_recreate_deps = options['--always-recreate-deps']
  853. exit_value_from = exitval_from_opts(options, self.project)
  854. cascade_stop = options['--abort-on-container-exit']
  855. service_names = options['SERVICE']
  856. timeout = timeout_from_opts(options)
  857. remove_orphans = options['--remove-orphans']
  858. detached = options.get('--detach')
  859. no_start = options.get('--no-start')
  860. if detached and (cascade_stop or exit_value_from):
  861. raise UserError("--abort-on-container-exit and -d cannot be combined.")
  862. environment = Environment.from_env_file(self.project_dir)
  863. ignore_orphans = environment.get_boolean('COMPOSE_IGNORE_ORPHANS')
  864. if ignore_orphans and remove_orphans:
  865. raise UserError("COMPOSE_IGNORE_ORPHANS and --remove-orphans cannot be combined.")
  866. opts = ['--detach', '--abort-on-container-exit', '--exit-code-from']
  867. for excluded in [x for x in opts if options.get(x) and no_start]:
  868. raise UserError('--no-start and {} cannot be combined.'.format(excluded))
  869. with up_shutdown_context(self.project, service_names, timeout, detached):
  870. warn_for_swarm_mode(self.project.client)
  871. def up(rebuild):
  872. return self.project.up(
  873. service_names=service_names,
  874. start_deps=start_deps,
  875. strategy=convergence_strategy_from_opts(options),
  876. do_build=build_action_from_opts(options),
  877. timeout=timeout,
  878. detached=detached,
  879. remove_orphans=remove_orphans,
  880. ignore_orphans=ignore_orphans,
  881. scale_override=parse_scale_args(options['--scale']),
  882. start=not no_start,
  883. always_recreate_deps=always_recreate_deps,
  884. reset_container_image=rebuild,
  885. renew_anonymous_volumes=options.get('--renew-anon-volumes'),
  886. silent=options.get('--quiet-pull'),
  887. )
  888. try:
  889. to_attach = up(False)
  890. except docker.errors.ImageNotFound as e:
  891. log.error(
  892. "The image for the service you're trying to recreate has been removed. "
  893. "If you continue, volume data could be lost. Consider backing up your data "
  894. "before continuing.\n".format(e.explanation)
  895. )
  896. res = yesno("Continue with the new image? [yN]", False)
  897. if res is None or not res:
  898. raise e
  899. to_attach = up(True)
  900. if detached or no_start:
  901. return
  902. attached_containers = filter_containers_to_service_names(to_attach, service_names)
  903. log_printer = log_printer_from_project(
  904. self.project,
  905. attached_containers,
  906. options['--no-color'],
  907. {'follow': True},
  908. cascade_stop,
  909. event_stream=self.project.events(service_names=service_names))
  910. print("Attaching to", list_containers(log_printer.containers))
  911. cascade_starter = log_printer.run()
  912. if cascade_stop:
  913. print("Aborting on container exit...")
  914. all_containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  915. exit_code = compute_exit_code(
  916. exit_value_from, attached_containers, cascade_starter, all_containers
  917. )
  918. self.project.stop(service_names=service_names, timeout=timeout)
  919. if exit_value_from:
  920. exit_code = compute_service_exit_code(exit_value_from, attached_containers)
  921. sys.exit(exit_code)
  922. @classmethod
  923. def version(cls, options):
  924. """
  925. Show version informations
  926. Usage: version [--short]
  927. Options:
  928. --short Shows only Compose's version number.
  929. """
  930. if options['--short']:
  931. print(__version__)
  932. else:
  933. print(get_version_info('full'))
  934. def compute_service_exit_code(exit_value_from, attached_containers):
  935. candidates = list(filter(
  936. lambda c: c.service == exit_value_from,
  937. attached_containers))
  938. if not candidates:
  939. log.error(
  940. 'No containers matching the spec "{0}" '
  941. 'were run.'.format(exit_value_from)
  942. )
  943. return 2
  944. if len(candidates) > 1:
  945. exit_values = filter(
  946. lambda e: e != 0,
  947. [c.inspect()['State']['ExitCode'] for c in candidates]
  948. )
  949. return exit_values[0]
  950. return candidates[0].inspect()['State']['ExitCode']
  951. def compute_exit_code(exit_value_from, attached_containers, cascade_starter, all_containers):
  952. exit_code = 0
  953. for e in all_containers:
  954. if (not e.is_running and cascade_starter == e.name):
  955. if not e.exit_code == 0:
  956. exit_code = e.exit_code
  957. break
  958. return exit_code
  959. def convergence_strategy_from_opts(options):
  960. no_recreate = options['--no-recreate']
  961. force_recreate = options['--force-recreate']
  962. renew_anonymous_volumes = options.get('--renew-anon-volumes')
  963. if force_recreate and no_recreate:
  964. raise UserError("--force-recreate and --no-recreate cannot be combined.")
  965. if no_recreate and renew_anonymous_volumes:
  966. raise UserError('--no-recreate and --renew-anon-volumes cannot be combined.')
  967. if force_recreate or renew_anonymous_volumes:
  968. return ConvergenceStrategy.always
  969. if no_recreate:
  970. return ConvergenceStrategy.never
  971. return ConvergenceStrategy.changed
  972. def timeout_from_opts(options):
  973. timeout = options.get('--timeout')
  974. return None if timeout is None else int(timeout)
  975. def image_digests_for_project(project, allow_push=False):
  976. try:
  977. return get_image_digests(
  978. project,
  979. allow_push=allow_push
  980. )
  981. except MissingDigests as e:
  982. def list_images(images):
  983. return "\n".join(" {}".format(name) for name in sorted(images))
  984. paras = ["Some images are missing digests."]
  985. if e.needs_push:
  986. command_hint = (
  987. "Use `docker-compose push {}` to push them. "
  988. .format(" ".join(sorted(e.needs_push)))
  989. )
  990. paras += [
  991. "The following images can be pushed:",
  992. list_images(e.needs_push),
  993. command_hint,
  994. ]
  995. if e.needs_pull:
  996. command_hint = (
  997. "Use `docker-compose pull {}` to pull them. "
  998. .format(" ".join(sorted(e.needs_pull)))
  999. )
  1000. paras += [
  1001. "The following images need to be pulled:",
  1002. list_images(e.needs_pull),
  1003. command_hint,
  1004. ]
  1005. raise UserError("\n\n".join(paras))
  1006. def exitval_from_opts(options, project):
  1007. exit_value_from = options.get('--exit-code-from')
  1008. if exit_value_from:
  1009. if not options.get('--abort-on-container-exit'):
  1010. log.warn('using --exit-code-from implies --abort-on-container-exit')
  1011. options['--abort-on-container-exit'] = True
  1012. if exit_value_from not in [s.name for s in project.get_services()]:
  1013. log.error('No service named "%s" was found in your compose file.',
  1014. exit_value_from)
  1015. sys.exit(2)
  1016. return exit_value_from
  1017. def image_type_from_opt(flag, value):
  1018. if not value:
  1019. return ImageType.none
  1020. try:
  1021. return ImageType[value]
  1022. except KeyError:
  1023. raise UserError("%s flag must be one of: all, local" % flag)
  1024. def build_action_from_opts(options):
  1025. if options['--build'] and options['--no-build']:
  1026. raise UserError("--build and --no-build can not be combined.")
  1027. if options['--build']:
  1028. return BuildAction.force
  1029. if options['--no-build']:
  1030. return BuildAction.skip
  1031. return BuildAction.none
  1032. def build_container_options(options, detach, command):
  1033. container_options = {
  1034. 'command': command,
  1035. 'tty': not (detach or options['-T'] or not sys.stdin.isatty()),
  1036. 'stdin_open': not detach,
  1037. 'detach': detach,
  1038. }
  1039. if options['-e']:
  1040. container_options['environment'] = Environment.from_command_line(
  1041. parse_environment(options['-e'])
  1042. )
  1043. if options['--label']:
  1044. container_options['labels'] = parse_labels(options['--label'])
  1045. if options.get('--entrypoint') is not None:
  1046. container_options['entrypoint'] = (
  1047. [""] if options['--entrypoint'] == '' else options['--entrypoint']
  1048. )
  1049. if options['--rm']:
  1050. container_options['restart'] = None
  1051. if options['--user']:
  1052. container_options['user'] = options.get('--user')
  1053. if not options['--service-ports']:
  1054. container_options['ports'] = []
  1055. if options['--publish']:
  1056. container_options['ports'] = options.get('--publish')
  1057. if options['--name']:
  1058. container_options['name'] = options['--name']
  1059. if options['--workdir']:
  1060. container_options['working_dir'] = options['--workdir']
  1061. if options['--volume']:
  1062. volumes = [VolumeSpec.parse(i) for i in options['--volume']]
  1063. container_options['volumes'] = volumes
  1064. return container_options
  1065. def run_one_off_container(container_options, project, service, options, toplevel_options,
  1066. project_dir='.'):
  1067. if not options['--no-deps']:
  1068. deps = service.get_dependency_names()
  1069. if deps:
  1070. project.up(
  1071. service_names=deps,
  1072. start_deps=True,
  1073. strategy=ConvergenceStrategy.never,
  1074. rescale=False
  1075. )
  1076. project.initialize()
  1077. container = service.create_container(
  1078. quiet=True,
  1079. one_off=True,
  1080. **container_options)
  1081. use_network_aliases = options['--use-aliases']
  1082. if options.get('--detach'):
  1083. service.start_container(container, use_network_aliases)
  1084. print(container.name)
  1085. return
  1086. def remove_container(force=False):
  1087. if options['--rm']:
  1088. project.client.remove_container(container.id, force=True, v=True)
  1089. environment = Environment.from_env_file(project_dir)
  1090. use_cli = not environment.get_boolean('COMPOSE_INTERACTIVE_NO_CLI')
  1091. signals.set_signal_handler_to_shutdown()
  1092. signals.set_signal_handler_to_hang_up()
  1093. try:
  1094. try:
  1095. if IS_WINDOWS_PLATFORM or use_cli:
  1096. service.connect_container_to_networks(container, use_network_aliases)
  1097. exit_code = call_docker(
  1098. ["start", "--attach", "--interactive", container.id],
  1099. toplevel_options
  1100. )
  1101. else:
  1102. operation = RunOperation(
  1103. project.client,
  1104. container.id,
  1105. interactive=not options['-T'],
  1106. logs=False,
  1107. )
  1108. pty = PseudoTerminal(project.client, operation)
  1109. sockets = pty.sockets()
  1110. service.start_container(container, use_network_aliases)
  1111. pty.start(sockets)
  1112. exit_code = container.wait()
  1113. except (signals.ShutdownException):
  1114. project.client.stop(container.id)
  1115. exit_code = 1
  1116. except (signals.ShutdownException, signals.HangUpException):
  1117. project.client.kill(container.id)
  1118. remove_container(force=True)
  1119. sys.exit(2)
  1120. remove_container()
  1121. sys.exit(exit_code)
  1122. def log_printer_from_project(
  1123. project,
  1124. containers,
  1125. monochrome,
  1126. log_args,
  1127. cascade_stop=False,
  1128. event_stream=None,
  1129. ):
  1130. return LogPrinter(
  1131. containers,
  1132. build_log_presenters(project.service_names, monochrome),
  1133. event_stream or project.events(),
  1134. cascade_stop=cascade_stop,
  1135. log_args=log_args)
  1136. def filter_containers_to_service_names(containers, service_names):
  1137. if not service_names:
  1138. return containers
  1139. return [
  1140. container
  1141. for container in containers if container.service in service_names
  1142. ]
  1143. @contextlib.contextmanager
  1144. def up_shutdown_context(project, service_names, timeout, detached):
  1145. if detached:
  1146. yield
  1147. return
  1148. signals.set_signal_handler_to_shutdown()
  1149. try:
  1150. try:
  1151. yield
  1152. except signals.ShutdownException:
  1153. print("Gracefully stopping... (press Ctrl+C again to force)")
  1154. project.stop(service_names=service_names, timeout=timeout)
  1155. except signals.ShutdownException:
  1156. project.kill(service_names=service_names)
  1157. sys.exit(2)
  1158. def list_containers(containers):
  1159. return ", ".join(c.name for c in containers)
  1160. def exit_if(condition, message, exit_code):
  1161. if condition:
  1162. log.error(message)
  1163. raise SystemExit(exit_code)
  1164. def call_docker(args, dockeropts):
  1165. executable_path = find_executable('docker')
  1166. if not executable_path:
  1167. raise UserError(errors.docker_not_found_msg("Couldn't find `docker` binary."))
  1168. tls = dockeropts.get('--tls', False)
  1169. ca_cert = dockeropts.get('--tlscacert')
  1170. cert = dockeropts.get('--tlscert')
  1171. key = dockeropts.get('--tlskey')
  1172. verify = dockeropts.get('--tlsverify')
  1173. host = dockeropts.get('--host')
  1174. tls_options = []
  1175. if tls:
  1176. tls_options.append('--tls')
  1177. if ca_cert:
  1178. tls_options.extend(['--tlscacert', ca_cert])
  1179. if cert:
  1180. tls_options.extend(['--tlscert', cert])
  1181. if key:
  1182. tls_options.extend(['--tlskey', key])
  1183. if verify:
  1184. tls_options.append('--tlsverify')
  1185. if host:
  1186. tls_options.extend(['--host', host.lstrip('=')])
  1187. args = [executable_path] + tls_options + args
  1188. log.debug(" ".join(map(pipes.quote, args)))
  1189. return subprocess.call(args)
  1190. def parse_scale_args(options):
  1191. res = {}
  1192. for s in options:
  1193. if '=' not in s:
  1194. raise UserError('Arguments to scale should be in the form service=num')
  1195. service_name, num = s.split('=', 1)
  1196. try:
  1197. num = int(num)
  1198. except ValueError:
  1199. raise UserError(
  1200. 'Number of containers for service "%s" is not a number' % service_name
  1201. )
  1202. res[service_name] = num
  1203. return res
  1204. def build_exec_command(options, container_id, command):
  1205. args = ["exec"]
  1206. if options["--detach"]:
  1207. args += ["--detach"]
  1208. else:
  1209. args += ["--interactive"]
  1210. if not options["-T"]:
  1211. args += ["--tty"]
  1212. if options["--privileged"]:
  1213. args += ["--privileged"]
  1214. if options["--user"]:
  1215. args += ["--user", options["--user"]]
  1216. if options["--env"]:
  1217. for env_variable in options["--env"]:
  1218. args += ["--env", env_variable]
  1219. if options["--workdir"]:
  1220. args += ["--workdir", options["--workdir"]]
  1221. args += [container_id]
  1222. args += command
  1223. return args
  1224. def has_container_with_state(containers, state):
  1225. states = {
  1226. 'running': lambda c: c.is_running,
  1227. 'stopped': lambda c: not c.is_running,
  1228. 'paused': lambda c: c.is_paused,
  1229. 'restarting': lambda c: c.is_restarting,
  1230. }
  1231. for container in containers:
  1232. if state not in states:
  1233. raise UserError("Invalid state: %s" % state)
  1234. if states[state](container):
  1235. return True
  1236. def filter_services(filt, services, project):
  1237. def should_include(service):
  1238. for f in filt:
  1239. if f == 'status':
  1240. state = filt[f]
  1241. containers = project.containers([service.name], stopped=True)
  1242. if not has_container_with_state(containers, state):
  1243. return False
  1244. elif f == 'source':
  1245. source = filt[f]
  1246. if source == 'image' or source == 'build':
  1247. if source not in service.options:
  1248. return False
  1249. else:
  1250. raise UserError("Invalid value for source filter: %s" % source)
  1251. else:
  1252. raise UserError("Invalid filter: %s" % f)
  1253. return True
  1254. return filter(should_include, services)
  1255. def build_filter(arg):
  1256. filt = {}
  1257. if arg is not None:
  1258. if '=' not in arg:
  1259. raise UserError("Arguments to --filter should be in form KEY=VAL")
  1260. key, val = arg.split('=', 1)
  1261. filt[key] = val
  1262. return filt
  1263. def warn_for_swarm_mode(client):
  1264. info = client.info()
  1265. if info.get('Swarm', {}).get('LocalNodeState') == 'active':
  1266. if info.get('ServerVersion', '').startswith('ucp'):
  1267. # UCP does multi-node scheduling with traditional Compose files.
  1268. return
  1269. log.warn(
  1270. "The Docker Engine you're using is running in swarm mode.\n\n"
  1271. "Compose does not use swarm mode to deploy services to multiple nodes in a swarm. "
  1272. "All containers will be scheduled on the current node.\n\n"
  1273. "To deploy your application across the swarm, "
  1274. "use `docker stack deploy`.\n"
  1275. )