main.py 51 KB

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