main.py 61 KB

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