main.py 58 KB

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