main.py 57 KB

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