main.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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. --profiles Print the profile names, one per line.
  331. --services Print the service names, one per line.
  332. --volumes Print the volume names, one per line.
  333. --hash="*" Print the service config hash, one per line.
  334. Set "service1,service2" for a list of specified services
  335. or use the wildcard symbol to display all services.
  336. """
  337. additional_options = {'--no-interpolate': options.get('--no-interpolate')}
  338. compose_config = get_config_from_options('.', self.toplevel_options, additional_options)
  339. image_digests = None
  340. if options['--resolve-image-digests']:
  341. self.project = project_from_options('.', self.toplevel_options, additional_options)
  342. with errors.handle_connection_errors(self.project.client):
  343. image_digests = image_digests_for_project(self.project)
  344. if options['--quiet']:
  345. return
  346. if options['--profiles']:
  347. profiles = set()
  348. for service in compose_config.services:
  349. if 'profiles' in service:
  350. for profile in service['profiles']:
  351. profiles.add(profile)
  352. print('\n'.join(sorted(profiles)))
  353. return
  354. if options['--services']:
  355. print('\n'.join(service['name'] for service in compose_config.services))
  356. return
  357. if options['--volumes']:
  358. print('\n'.join(volume for volume in compose_config.volumes))
  359. return
  360. if options['--hash'] is not None:
  361. h = options['--hash']
  362. self.project = project_from_options('.', self.toplevel_options, additional_options)
  363. services = [svc for svc in options['--hash'].split(',')] if h != '*' else None
  364. with errors.handle_connection_errors(self.project.client):
  365. for service in self.project.get_services(services):
  366. print('{} {}'.format(service.name, service.config_hash))
  367. return
  368. print(serialize_config(compose_config, image_digests, not options['--no-interpolate']))
  369. @metrics()
  370. def create(self, options):
  371. """
  372. Creates containers for a service.
  373. This command is deprecated. Use the `up` command with `--no-start` instead.
  374. Usage: create [options] [SERVICE...]
  375. Options:
  376. --force-recreate Recreate containers even if their configuration and
  377. image haven't changed. Incompatible with --no-recreate.
  378. --no-recreate If containers already exist, don't recreate them.
  379. Incompatible with --force-recreate.
  380. --no-build Don't build an image, even if it's missing.
  381. --build Build images before creating containers.
  382. """
  383. service_names = options['SERVICE']
  384. log.warning(
  385. 'The create command is deprecated. '
  386. 'Use the up command with the --no-start flag instead.'
  387. )
  388. self.project.create(
  389. service_names=service_names,
  390. strategy=convergence_strategy_from_opts(options),
  391. do_build=build_action_from_opts(options),
  392. )
  393. @metrics()
  394. def down(self, options):
  395. """
  396. Stops containers and removes containers, networks, volumes, and images
  397. created by `up`.
  398. By default, the only things removed are:
  399. - Containers for services defined in the Compose file
  400. - Networks defined in the `networks` section of the Compose file
  401. - The default network, if one is used
  402. Networks and volumes defined as `external` are never removed.
  403. Usage: down [options]
  404. Options:
  405. --rmi type Remove images. Type must be one of:
  406. 'all': Remove all images used by any service.
  407. 'local': Remove only images that don't have a
  408. custom tag set by the `image` field.
  409. -v, --volumes Remove named volumes declared in the `volumes`
  410. section of the Compose file and anonymous volumes
  411. attached to containers.
  412. --remove-orphans Remove containers for services not defined in the
  413. Compose file
  414. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  415. (default: 10)
  416. """
  417. ignore_orphans = self.toplevel_environment.get_boolean('COMPOSE_IGNORE_ORPHANS')
  418. if ignore_orphans and options['--remove-orphans']:
  419. raise UserError("COMPOSE_IGNORE_ORPHANS and --remove-orphans cannot be combined.")
  420. image_type = image_type_from_opt('--rmi', options['--rmi'])
  421. timeout = timeout_from_opts(options)
  422. self.project.down(
  423. image_type,
  424. options['--volumes'],
  425. options['--remove-orphans'],
  426. timeout=timeout,
  427. ignore_orphans=ignore_orphans)
  428. def events(self, options):
  429. """
  430. Receive real time events from containers.
  431. Usage: events [options] [--] [SERVICE...]
  432. Options:
  433. --json Output events as a stream of json objects
  434. """
  435. def format_event(event):
  436. attributes = ["%s=%s" % item for item in event['attributes'].items()]
  437. return ("{time} {type} {action} {id} ({attrs})").format(
  438. attrs=", ".join(sorted(attributes)),
  439. **event)
  440. def json_format_event(event):
  441. event['time'] = event['time'].isoformat()
  442. event.pop('container')
  443. return json.dumps(event)
  444. for event in self.project.events():
  445. formatter = json_format_event if options['--json'] else format_event
  446. print(formatter(event))
  447. sys.stdout.flush()
  448. @metrics("exec")
  449. def exec_command(self, options):
  450. """
  451. Execute a command in a running container
  452. Usage: exec [options] [-e KEY=VAL...] [--] SERVICE COMMAND [ARGS...]
  453. Options:
  454. -d, --detach Detached mode: Run command in the background.
  455. --privileged Give extended privileges to the process.
  456. -u, --user USER Run the command as this user.
  457. -T Disable pseudo-tty allocation. By default `docker-compose exec`
  458. allocates a TTY.
  459. --index=index index of the container if there are multiple
  460. instances of a service [default: 1]
  461. -e, --env KEY=VAL Set environment variables (can be used multiple times,
  462. not supported in API < 1.25)
  463. -w, --workdir DIR Path to workdir directory for this command.
  464. """
  465. use_cli = not self.toplevel_environment.get_boolean('COMPOSE_INTERACTIVE_NO_CLI')
  466. index = int(options.get('--index'))
  467. service = self.project.get_service(options['SERVICE'])
  468. detach = options.get('--detach')
  469. if options['--env'] and docker.utils.version_lt(self.project.client.api_version, '1.25'):
  470. raise UserError("Setting environment for exec is not supported in API < 1.25 (%s)"
  471. % self.project.client.api_version)
  472. if options['--workdir'] and docker.utils.version_lt(self.project.client.api_version, '1.35'):
  473. raise UserError("Setting workdir for exec is not supported in API < 1.35 (%s)"
  474. % self.project.client.api_version)
  475. try:
  476. container = service.get_container(number=index)
  477. except ValueError as e:
  478. raise UserError(str(e))
  479. command = [options['COMMAND']] + options['ARGS']
  480. tty = not options["-T"]
  481. if IS_WINDOWS_PLATFORM or use_cli and not detach:
  482. sys.exit(call_docker(
  483. build_exec_command(options, container.id, command),
  484. self.toplevel_options, self.toplevel_environment)
  485. )
  486. create_exec_options = {
  487. "privileged": options["--privileged"],
  488. "user": options["--user"],
  489. "tty": tty,
  490. "stdin": True,
  491. "workdir": options["--workdir"],
  492. }
  493. if docker.utils.version_gte(self.project.client.api_version, '1.25'):
  494. create_exec_options["environment"] = options["--env"]
  495. exec_id = container.create_exec(command, **create_exec_options)
  496. if detach:
  497. container.start_exec(exec_id, tty=tty, stream=True)
  498. return
  499. signals.set_signal_handler_to_shutdown()
  500. try:
  501. operation = ExecOperation(
  502. self.project.client,
  503. exec_id,
  504. interactive=tty,
  505. )
  506. pty = PseudoTerminal(self.project.client, operation)
  507. pty.start()
  508. except signals.ShutdownException:
  509. log.info("received shutdown exception: closing")
  510. exit_code = self.project.client.exec_inspect(exec_id).get("ExitCode")
  511. sys.exit(exit_code)
  512. @classmethod
  513. @metrics()
  514. def help(cls, options):
  515. """
  516. Get help on a command.
  517. Usage: help [COMMAND]
  518. """
  519. if options['COMMAND']:
  520. subject = get_handler(cls, options['COMMAND'])
  521. else:
  522. subject = cls
  523. print(getdoc(subject))
  524. @metrics()
  525. def images(self, options):
  526. """
  527. List images used by the created containers.
  528. Usage: images [options] [--] [SERVICE...]
  529. Options:
  530. -q, --quiet Only display IDs
  531. """
  532. containers = sorted(
  533. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  534. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  535. key=attrgetter('name'))
  536. if options['--quiet']:
  537. for image in {c.image for c in containers}:
  538. print(image.split(':')[1])
  539. return
  540. def add_default_tag(img_name):
  541. if ':' not in img_name.split('/')[-1]:
  542. return '{}:latest'.format(img_name)
  543. return img_name
  544. headers = [
  545. 'Container',
  546. 'Repository',
  547. 'Tag',
  548. 'Image Id',
  549. 'Size'
  550. ]
  551. rows = []
  552. for container in containers:
  553. image_config = container.image_config
  554. service = self.project.get_service(container.service)
  555. index = 0
  556. img_name = add_default_tag(service.image_name)
  557. if img_name in image_config['RepoTags']:
  558. index = image_config['RepoTags'].index(img_name)
  559. repo_tags = (
  560. image_config['RepoTags'][index].rsplit(':', 1) if image_config['RepoTags']
  561. else ('<none>', '<none>')
  562. )
  563. image_id = image_config['Id'].split(':')[1][:12]
  564. size = human_readable_file_size(image_config['Size'])
  565. rows.append([
  566. container.name,
  567. repo_tags[0],
  568. repo_tags[1],
  569. image_id,
  570. size
  571. ])
  572. print(Formatter.table(headers, rows))
  573. @metrics()
  574. def kill(self, options):
  575. """
  576. Force stop service containers.
  577. Usage: kill [options] [--] [SERVICE...]
  578. Options:
  579. -s SIGNAL SIGNAL to send to the container.
  580. Default signal is SIGKILL.
  581. """
  582. signal = options.get('-s', 'SIGKILL')
  583. self.project.kill(service_names=options['SERVICE'], signal=signal)
  584. @metrics()
  585. def logs(self, options):
  586. """
  587. View output from containers.
  588. Usage: logs [options] [--] [SERVICE...]
  589. Options:
  590. --no-color Produce monochrome output.
  591. -f, --follow Follow log output.
  592. -t, --timestamps Show timestamps.
  593. --tail="all" Number of lines to show from the end of the logs
  594. for each container.
  595. --no-log-prefix Don't print prefix in logs.
  596. """
  597. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  598. tail = options['--tail']
  599. if tail is not None:
  600. if tail.isdigit():
  601. tail = int(tail)
  602. elif tail != 'all':
  603. raise UserError("tail flag must be all or a number")
  604. log_args = {
  605. 'follow': options['--follow'],
  606. 'tail': tail,
  607. 'timestamps': options['--timestamps']
  608. }
  609. print("Attaching to", list_containers(containers))
  610. log_printer_from_project(
  611. self.project,
  612. containers,
  613. options['--no-color'],
  614. log_args,
  615. event_stream=self.project.events(service_names=options['SERVICE']),
  616. keep_prefix=not options['--no-log-prefix']).run()
  617. @metrics()
  618. def pause(self, options):
  619. """
  620. Pause services.
  621. Usage: pause [SERVICE...]
  622. """
  623. containers = self.project.pause(service_names=options['SERVICE'])
  624. exit_if(not containers, 'No containers to pause', 1)
  625. @metrics()
  626. def port(self, options):
  627. """
  628. Print the public port for a port binding.
  629. Usage: port [options] [--] SERVICE PRIVATE_PORT
  630. Options:
  631. --protocol=proto tcp or udp [default: tcp]
  632. --index=index index of the container if there are multiple
  633. instances of a service [default: 1]
  634. """
  635. index = int(options.get('--index'))
  636. service = self.project.get_service(options['SERVICE'])
  637. try:
  638. container = service.get_container(number=index)
  639. except ValueError as e:
  640. raise UserError(str(e))
  641. print(container.get_local_port(
  642. options['PRIVATE_PORT'],
  643. protocol=options.get('--protocol') or 'tcp') or '')
  644. @metrics()
  645. def ps(self, options):
  646. """
  647. List containers.
  648. Usage: ps [options] [--] [SERVICE...]
  649. Options:
  650. -q, --quiet Only display IDs
  651. --services Display services
  652. --filter KEY=VAL Filter services by a property
  653. -a, --all Show all stopped containers (including those created by the run command)
  654. """
  655. if options['--quiet'] and options['--services']:
  656. raise UserError('--quiet and --services cannot be combined')
  657. if options['--services']:
  658. filt = build_filter(options.get('--filter'))
  659. services = self.project.services
  660. if filt:
  661. services = filter_services(filt, services, self.project)
  662. print('\n'.join(service.name for service in services))
  663. return
  664. if options['--all']:
  665. containers = sorted(self.project.containers(service_names=options['SERVICE'],
  666. one_off=OneOffFilter.include, stopped=True),
  667. key=attrgetter('name'))
  668. else:
  669. containers = sorted(
  670. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  671. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  672. key=attrgetter('name'))
  673. if options['--quiet']:
  674. for container in containers:
  675. print(container.id)
  676. else:
  677. headers = [
  678. 'Name',
  679. 'Command',
  680. 'State',
  681. 'Ports',
  682. ]
  683. rows = []
  684. for container in containers:
  685. command = container.human_readable_command
  686. if len(command) > 30:
  687. command = '%s ...' % command[:26]
  688. rows.append([
  689. container.name,
  690. command,
  691. container.human_readable_state,
  692. container.human_readable_ports,
  693. ])
  694. print(Formatter.table(headers, rows))
  695. @metrics()
  696. def pull(self, options):
  697. """
  698. Pulls images for services defined in a Compose file, but does not start the containers.
  699. Usage: pull [options] [--] [SERVICE...]
  700. Options:
  701. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  702. --parallel Deprecated, pull multiple images in parallel (enabled by default).
  703. --no-parallel Disable parallel pulling.
  704. -q, --quiet Pull without printing progress information
  705. --include-deps Also pull services declared as dependencies
  706. """
  707. if options.get('--parallel'):
  708. log.warning('--parallel option is deprecated and will be removed in future versions.')
  709. self.project.pull(
  710. service_names=options['SERVICE'],
  711. ignore_pull_failures=options.get('--ignore-pull-failures'),
  712. parallel_pull=not options.get('--no-parallel'),
  713. silent=options.get('--quiet'),
  714. include_deps=options.get('--include-deps'),
  715. )
  716. @metrics()
  717. def push(self, options):
  718. """
  719. Pushes images for services.
  720. Usage: push [options] [--] [SERVICE...]
  721. Options:
  722. --ignore-push-failures Push what it can and ignores images with push failures.
  723. """
  724. self.project.push(
  725. service_names=options['SERVICE'],
  726. ignore_push_failures=options.get('--ignore-push-failures')
  727. )
  728. @metrics()
  729. def rm(self, options):
  730. """
  731. Removes stopped service containers.
  732. By default, anonymous volumes attached to containers will not be removed. You
  733. can override this with `-v`. To list all volumes, use `docker volume ls`.
  734. Any data which is not in a volume will be lost.
  735. Usage: rm [options] [--] [SERVICE...]
  736. Options:
  737. -f, --force Don't ask to confirm removal
  738. -s, --stop Stop the containers, if required, before removing
  739. -v Remove any anonymous volumes attached to containers
  740. -a, --all Deprecated - no effect.
  741. """
  742. if options.get('--all'):
  743. log.warning(
  744. '--all flag is obsolete. This is now the default behavior '
  745. 'of `docker-compose rm`'
  746. )
  747. one_off = OneOffFilter.include
  748. if options.get('--stop'):
  749. self.project.stop(service_names=options['SERVICE'], one_off=one_off)
  750. all_containers = self.project.containers(
  751. service_names=options['SERVICE'], stopped=True, one_off=one_off
  752. )
  753. stopped_containers = [c for c in all_containers if not c.is_running]
  754. if len(stopped_containers) > 0:
  755. print("Going to remove", list_containers(stopped_containers))
  756. if options.get('--force') \
  757. or yesno("Are you sure? [yN] ", default=False):
  758. self.project.remove_stopped(
  759. service_names=options['SERVICE'],
  760. v=options.get('-v', False),
  761. one_off=one_off
  762. )
  763. else:
  764. print("No stopped containers")
  765. @metrics()
  766. def run(self, options):
  767. """
  768. Run a one-off command on a service.
  769. For example:
  770. $ docker-compose run web python manage.py shell
  771. By default, linked services will be started, unless they are already
  772. running. If you do not want to start linked services, use
  773. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  774. Usage:
  775. run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] [--]
  776. SERVICE [COMMAND] [ARGS...]
  777. Options:
  778. -d, --detach Detached mode: Run container in the background, print
  779. new container name.
  780. --name NAME Assign a name to the container
  781. --entrypoint CMD Override the entrypoint of the image.
  782. -e KEY=VAL Set an environment variable (can be used multiple times)
  783. -l, --label KEY=VAL Add or override a label (can be used multiple times)
  784. -u, --user="" Run as specified username or uid
  785. --no-deps Don't start linked services.
  786. --rm Remove container after run. Ignored in detached mode.
  787. -p, --publish=[] Publish a container's port(s) to the host
  788. --service-ports Run command with the service's ports enabled and mapped
  789. to the host.
  790. --use-aliases Use the service's network aliases in the network(s) the
  791. container connects to.
  792. -v, --volume=[] Bind mount a volume (default [])
  793. -T Disable pseudo-tty allocation. By default `docker-compose run`
  794. allocates a TTY.
  795. -w, --workdir="" Working directory inside the container
  796. """
  797. service = self.project.get_service(options['SERVICE'])
  798. detach = options.get('--detach')
  799. if options['--publish'] and options['--service-ports']:
  800. raise UserError(
  801. 'Service port mapping and manual port mapping '
  802. 'can not be used together'
  803. )
  804. if options['COMMAND'] is not None:
  805. command = [options['COMMAND']] + options['ARGS']
  806. elif options['--entrypoint'] is not None:
  807. command = []
  808. else:
  809. command = service.options.get('command')
  810. options['stdin_open'] = service.options.get('stdin_open', True)
  811. container_options = build_one_off_container_options(options, detach, command)
  812. run_one_off_container(
  813. container_options, self.project, service, options,
  814. self.toplevel_options, self.toplevel_environment
  815. )
  816. @metrics()
  817. def scale(self, options):
  818. """
  819. Set number of containers to run for a service.
  820. Numbers are specified in the form `service=num` as arguments.
  821. For example:
  822. $ docker-compose scale web=2 worker=3
  823. This command is deprecated. Use the up command with the `--scale` flag
  824. instead.
  825. Usage: scale [options] [SERVICE=NUM...]
  826. Options:
  827. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  828. (default: 10)
  829. """
  830. timeout = timeout_from_opts(options)
  831. log.warning(
  832. 'The scale command is deprecated. '
  833. 'Use the up command with the --scale flag instead.'
  834. )
  835. for service_name, num in parse_scale_args(options['SERVICE=NUM']).items():
  836. self.project.get_service(service_name).scale(num, timeout=timeout)
  837. @metrics()
  838. def start(self, options):
  839. """
  840. Start existing containers.
  841. Usage: start [SERVICE...]
  842. """
  843. containers = self.project.start(service_names=options['SERVICE'])
  844. exit_if(not containers, 'No containers to start', 1)
  845. @metrics()
  846. def stop(self, options):
  847. """
  848. Stop running containers without removing them.
  849. They can be started again with `docker-compose start`.
  850. Usage: stop [options] [--] [SERVICE...]
  851. Options:
  852. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  853. (default: 10)
  854. """
  855. timeout = timeout_from_opts(options)
  856. self.project.stop(service_names=options['SERVICE'], timeout=timeout)
  857. @metrics()
  858. def restart(self, options):
  859. """
  860. Restart running containers.
  861. Usage: restart [options] [--] [SERVICE...]
  862. Options:
  863. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  864. (default: 10)
  865. """
  866. timeout = timeout_from_opts(options)
  867. containers = self.project.restart(service_names=options['SERVICE'], timeout=timeout)
  868. exit_if(not containers, 'No containers to restart', 1)
  869. @metrics()
  870. def top(self, options):
  871. """
  872. Display the running processes
  873. Usage: top [SERVICE...]
  874. """
  875. containers = sorted(
  876. self.project.containers(service_names=options['SERVICE'], stopped=False) +
  877. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  878. key=attrgetter('name')
  879. )
  880. for idx, container in enumerate(containers):
  881. if idx > 0:
  882. print()
  883. top_data = self.project.client.top(container.name)
  884. headers = top_data.get("Titles")
  885. rows = []
  886. for process in top_data.get("Processes", []):
  887. rows.append(process)
  888. print(container.name)
  889. print(Formatter.table(headers, rows))
  890. @metrics()
  891. def unpause(self, options):
  892. """
  893. Unpause services.
  894. Usage: unpause [SERVICE...]
  895. """
  896. containers = self.project.unpause(service_names=options['SERVICE'])
  897. exit_if(not containers, 'No containers to unpause', 1)
  898. @metrics()
  899. def up(self, options):
  900. """
  901. Builds, (re)creates, starts, and attaches to containers for a service.
  902. Unless they are already running, this command also starts any linked services.
  903. The `docker-compose up` command aggregates the output of each container. When
  904. the command exits, all containers are stopped. Running `docker-compose up -d`
  905. starts the containers in the background and leaves them running.
  906. If there are existing containers for a service, and the service's configuration
  907. or image was changed after the container's creation, `docker-compose up` picks
  908. up the changes by stopping and recreating the containers (preserving mounted
  909. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  910. flag.
  911. If you want to force Compose to stop and recreate all containers, use the
  912. `--force-recreate` flag.
  913. Usage: up [options] [--scale SERVICE=NUM...] [--] [SERVICE...]
  914. Options:
  915. -d, --detach Detached mode: Run containers in the background,
  916. print new container names. Incompatible with
  917. --abort-on-container-exit.
  918. --no-color Produce monochrome output.
  919. --quiet-pull Pull without printing progress information
  920. --no-deps Don't start linked services.
  921. --force-recreate Recreate containers even if their configuration
  922. and image haven't changed.
  923. --always-recreate-deps Recreate dependent containers.
  924. Incompatible with --no-recreate.
  925. --no-recreate If containers already exist, don't recreate
  926. them. Incompatible with --force-recreate and -V.
  927. --no-build Don't build an image, even if it's missing.
  928. --no-start Don't start the services after creating them.
  929. --build Build images before starting containers.
  930. --abort-on-container-exit Stops all containers if any container was
  931. stopped. Incompatible with -d.
  932. --attach-dependencies Attach to dependent containers.
  933. -t, --timeout TIMEOUT Use this timeout in seconds for container
  934. shutdown when attached or when containers are
  935. already running. (default: 10)
  936. -V, --renew-anon-volumes Recreate anonymous volumes instead of retrieving
  937. data from the previous containers.
  938. --remove-orphans Remove containers for services not defined
  939. in the Compose file.
  940. --exit-code-from SERVICE Return the exit code of the selected service
  941. container. Implies --abort-on-container-exit.
  942. --scale SERVICE=NUM Scale SERVICE to NUM instances. Overrides the
  943. `scale` setting in the Compose file if present.
  944. --no-log-prefix Don't print prefix in logs.
  945. """
  946. start_deps = not options['--no-deps']
  947. always_recreate_deps = options['--always-recreate-deps']
  948. exit_value_from = exitval_from_opts(options, self.project)
  949. cascade_stop = options['--abort-on-container-exit']
  950. service_names = options['SERVICE']
  951. timeout = timeout_from_opts(options)
  952. remove_orphans = options['--remove-orphans']
  953. detached = options.get('--detach')
  954. no_start = options.get('--no-start')
  955. attach_dependencies = options.get('--attach-dependencies')
  956. keep_prefix = not options['--no-log-prefix']
  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. containers,
  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. )