main.py 53 KB

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