main.py 61 KB

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