main.py 55 KB

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