main.py 58 KB

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