main.py 58 KB

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