main.py 46 KB

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