main.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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 bulid 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 custom tag
  303. set by the `image` field.
  304. -v, --volumes Remove named volumes declared in the `volumes` section
  305. 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. """
  310. image_type = image_type_from_opt('--rmi', options['--rmi'])
  311. self.project.down(image_type, options['--volumes'], options['--remove-orphans'])
  312. def events(self, options):
  313. """
  314. Receive real time events from containers.
  315. Usage: events [options] [SERVICE...]
  316. Options:
  317. --json Output events as a stream of json objects
  318. """
  319. def format_event(event):
  320. attributes = ["%s=%s" % item for item in event['attributes'].items()]
  321. return ("{time} {type} {action} {id} ({attrs})").format(
  322. attrs=", ".join(sorted(attributes)),
  323. **event)
  324. def json_format_event(event):
  325. event['time'] = event['time'].isoformat()
  326. event.pop('container')
  327. return json.dumps(event)
  328. for event in self.project.events():
  329. formatter = json_format_event if options['--json'] else format_event
  330. print(formatter(event))
  331. sys.stdout.flush()
  332. def exec_command(self, options):
  333. """
  334. Execute a command in a running container
  335. Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]
  336. Options:
  337. -d Detached mode: Run command in the background.
  338. --privileged Give extended privileges to the process.
  339. -u, --user USER Run the command as this user.
  340. -T Disable pseudo-tty allocation. By default `docker-compose exec`
  341. allocates a TTY.
  342. --index=index index of the container if there are multiple
  343. instances of a service [default: 1]
  344. -e, --env KEY=VAL Set environment variables (can be used multiple times,
  345. not supported in API < 1.25)
  346. """
  347. index = int(options.get('--index'))
  348. service = self.project.get_service(options['SERVICE'])
  349. detach = options['-d']
  350. if options['--env'] and docker.utils.version_lt(self.project.client.api_version, '1.25'):
  351. raise UserError("Setting environment for exec is not supported in API < 1.25'")
  352. try:
  353. container = service.get_container(number=index)
  354. except ValueError as e:
  355. raise UserError(str(e))
  356. command = [options['COMMAND']] + options['ARGS']
  357. tty = not options["-T"]
  358. if IS_WINDOWS_PLATFORM and not detach:
  359. sys.exit(call_docker(build_exec_command(options, container.id, command)))
  360. create_exec_options = {
  361. "privileged": options["--privileged"],
  362. "user": options["--user"],
  363. "tty": tty,
  364. "stdin": tty,
  365. }
  366. if docker.utils.version_gte(self.project.client.api_version, '1.25'):
  367. create_exec_options["environment"] = options["--env"]
  368. exec_id = container.create_exec(command, **create_exec_options)
  369. if detach:
  370. container.start_exec(exec_id, tty=tty, stream=True)
  371. return
  372. signals.set_signal_handler_to_shutdown()
  373. try:
  374. operation = ExecOperation(
  375. self.project.client,
  376. exec_id,
  377. interactive=tty,
  378. )
  379. pty = PseudoTerminal(self.project.client, operation)
  380. pty.start()
  381. except signals.ShutdownException:
  382. log.info("received shutdown exception: closing")
  383. exit_code = self.project.client.exec_inspect(exec_id).get("ExitCode")
  384. sys.exit(exit_code)
  385. @classmethod
  386. def help(cls, options):
  387. """
  388. Get help on a command.
  389. Usage: help [COMMAND]
  390. """
  391. if options['COMMAND']:
  392. subject = get_handler(cls, options['COMMAND'])
  393. else:
  394. subject = cls
  395. print(getdoc(subject))
  396. def images(self, options):
  397. """
  398. List images used by the created containers.
  399. Usage: images [options] [SERVICE...]
  400. Options:
  401. -q Only display IDs
  402. """
  403. containers = sorted(
  404. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  405. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  406. key=attrgetter('name'))
  407. if options['-q']:
  408. for image in set(c.image for c in containers):
  409. print(image.split(':')[1])
  410. else:
  411. headers = [
  412. 'Container',
  413. 'Repository',
  414. 'Tag',
  415. 'Image Id',
  416. 'Size'
  417. ]
  418. rows = []
  419. for container in containers:
  420. image_config = container.image_config
  421. repo_tags = image_config['RepoTags'][0].rsplit(':', 1)
  422. image_id = image_config['Id'].split(':')[1][:12]
  423. size = human_readable_file_size(image_config['Size'])
  424. rows.append([
  425. container.name,
  426. repo_tags[0],
  427. repo_tags[1],
  428. image_id,
  429. size
  430. ])
  431. print(Formatter().table(headers, rows))
  432. def kill(self, options):
  433. """
  434. Force stop service containers.
  435. Usage: kill [options] [SERVICE...]
  436. Options:
  437. -s SIGNAL SIGNAL to send to the container.
  438. Default signal is SIGKILL.
  439. """
  440. signal = options.get('-s', 'SIGKILL')
  441. self.project.kill(service_names=options['SERVICE'], signal=signal)
  442. def logs(self, options):
  443. """
  444. View output from containers.
  445. Usage: logs [options] [SERVICE...]
  446. Options:
  447. --no-color Produce monochrome output.
  448. -f, --follow Follow log output.
  449. -t, --timestamps Show timestamps.
  450. --tail="all" Number of lines to show from the end of the logs
  451. for each container.
  452. """
  453. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  454. tail = options['--tail']
  455. if tail is not None:
  456. if tail.isdigit():
  457. tail = int(tail)
  458. elif tail != 'all':
  459. raise UserError("tail flag must be all or a number")
  460. log_args = {
  461. 'follow': options['--follow'],
  462. 'tail': tail,
  463. 'timestamps': options['--timestamps']
  464. }
  465. print("Attaching to", list_containers(containers))
  466. log_printer_from_project(
  467. self.project,
  468. containers,
  469. options['--no-color'],
  470. log_args,
  471. event_stream=self.project.events(service_names=options['SERVICE'])).run()
  472. def pause(self, options):
  473. """
  474. Pause services.
  475. Usage: pause [SERVICE...]
  476. """
  477. containers = self.project.pause(service_names=options['SERVICE'])
  478. exit_if(not containers, 'No containers to pause', 1)
  479. def port(self, options):
  480. """
  481. Print the public port for a port binding.
  482. Usage: port [options] SERVICE PRIVATE_PORT
  483. Options:
  484. --protocol=proto tcp or udp [default: tcp]
  485. --index=index index of the container if there are multiple
  486. instances of a service [default: 1]
  487. """
  488. index = int(options.get('--index'))
  489. service = self.project.get_service(options['SERVICE'])
  490. try:
  491. container = service.get_container(number=index)
  492. except ValueError as e:
  493. raise UserError(str(e))
  494. print(container.get_local_port(
  495. options['PRIVATE_PORT'],
  496. protocol=options.get('--protocol') or 'tcp') or '')
  497. def ps(self, options):
  498. """
  499. List containers.
  500. Usage: ps [options] [SERVICE...]
  501. Options:
  502. -q Only display IDs
  503. """
  504. containers = sorted(
  505. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  506. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  507. key=attrgetter('name'))
  508. if options['-q']:
  509. for container in containers:
  510. print(container.id)
  511. else:
  512. headers = [
  513. 'Name',
  514. 'Command',
  515. 'State',
  516. 'Ports',
  517. ]
  518. rows = []
  519. for container in containers:
  520. command = container.human_readable_command
  521. if len(command) > 30:
  522. command = '%s ...' % command[:26]
  523. rows.append([
  524. container.name,
  525. command,
  526. container.human_readable_state,
  527. container.human_readable_ports,
  528. ])
  529. print(Formatter().table(headers, rows))
  530. def pull(self, options):
  531. """
  532. Pulls images for services defined in a Compose file, but does not start the containers.
  533. Usage: pull [options] [SERVICE...]
  534. Options:
  535. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  536. --parallel Pull multiple images in parallel.
  537. --quiet Pull without printing progress information
  538. """
  539. self.project.pull(
  540. service_names=options['SERVICE'],
  541. ignore_pull_failures=options.get('--ignore-pull-failures'),
  542. parallel_pull=options.get('--parallel'),
  543. silent=options.get('--quiet'),
  544. )
  545. def push(self, options):
  546. """
  547. Pushes images for services.
  548. Usage: push [options] [SERVICE...]
  549. Options:
  550. --ignore-push-failures Push what it can and ignores images with push failures.
  551. """
  552. self.project.push(
  553. service_names=options['SERVICE'],
  554. ignore_push_failures=options.get('--ignore-push-failures')
  555. )
  556. def rm(self, options):
  557. """
  558. Removes stopped service containers.
  559. By default, anonymous volumes attached to containers will not be removed. You
  560. can override this with `-v`. To list all volumes, use `docker volume ls`.
  561. Any data which is not in a volume will be lost.
  562. Usage: rm [options] [SERVICE...]
  563. Options:
  564. -f, --force Don't ask to confirm removal
  565. -s, --stop Stop the containers, if required, before removing
  566. -v Remove any anonymous volumes attached to containers
  567. -a, --all Deprecated - no effect.
  568. """
  569. if options.get('--all'):
  570. log.warn(
  571. '--all flag is obsolete. This is now the default behavior '
  572. 'of `docker-compose rm`'
  573. )
  574. one_off = OneOffFilter.include
  575. if options.get('--stop'):
  576. self.project.stop(service_names=options['SERVICE'], one_off=one_off)
  577. all_containers = self.project.containers(
  578. service_names=options['SERVICE'], stopped=True, one_off=one_off
  579. )
  580. stopped_containers = [c for c in all_containers if not c.is_running]
  581. if len(stopped_containers) > 0:
  582. print("Going to remove", list_containers(stopped_containers))
  583. if options.get('--force') \
  584. or yesno("Are you sure? [yN] ", default=False):
  585. self.project.remove_stopped(
  586. service_names=options['SERVICE'],
  587. v=options.get('-v', False),
  588. one_off=one_off
  589. )
  590. else:
  591. print("No stopped containers")
  592. def run(self, options):
  593. """
  594. Run a one-off command on a service.
  595. For example:
  596. $ docker-compose run web python manage.py shell
  597. By default, linked services will be started, unless they are already
  598. running. If you do not want to start linked services, use
  599. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  600. Usage:
  601. run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...]
  602. SERVICE [COMMAND] [ARGS...]
  603. Options:
  604. -d Detached mode: Run container in the background, print
  605. new container name.
  606. --name NAME Assign a name to the container
  607. --entrypoint CMD Override the entrypoint of the image.
  608. -e KEY=VAL Set an environment variable (can be used multiple times)
  609. -l, --label KEY=VAL Add or override a label (can be used multiple times)
  610. -u, --user="" Run as specified username or uid
  611. --no-deps Don't start linked services.
  612. --rm Remove container after run. Ignored in detached mode.
  613. -p, --publish=[] Publish a container's port(s) to the host
  614. --service-ports Run command with the service's ports enabled and mapped
  615. to the host.
  616. -v, --volume=[] Bind mount a volume (default [])
  617. -T Disable pseudo-tty allocation. By default `docker-compose run`
  618. allocates a TTY.
  619. -w, --workdir="" Working directory inside the container
  620. """
  621. service = self.project.get_service(options['SERVICE'])
  622. detach = options['-d']
  623. if options['--publish'] and options['--service-ports']:
  624. raise UserError(
  625. 'Service port mapping and manual port mapping '
  626. 'can not be used together'
  627. )
  628. if options['COMMAND'] is not None:
  629. command = [options['COMMAND']] + options['ARGS']
  630. elif options['--entrypoint'] is not None:
  631. command = []
  632. else:
  633. command = service.options.get('command')
  634. container_options = build_container_options(options, detach, command)
  635. run_one_off_container(container_options, self.project, service, options)
  636. def scale(self, options):
  637. """
  638. Set number of containers to run for a service.
  639. Numbers are specified in the form `service=num` as arguments.
  640. For example:
  641. $ docker-compose scale web=2 worker=3
  642. This command is deprecated. Use the up command with the `--scale` flag
  643. instead.
  644. Usage: scale [options] [SERVICE=NUM...]
  645. Options:
  646. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  647. (default: 10)
  648. """
  649. timeout = timeout_from_opts(options)
  650. if self.project.config_version == V2_2:
  651. raise UserError(
  652. 'The scale command is incompatible with the v2.2 format. '
  653. 'Use the up command with the --scale flag instead.'
  654. )
  655. else:
  656. log.warn(
  657. 'The scale command is deprecated. '
  658. 'Use the up command with the --scale flag instead.'
  659. )
  660. for service_name, num in parse_scale_args(options['SERVICE=NUM']).items():
  661. self.project.get_service(service_name).scale(num, timeout=timeout)
  662. def start(self, options):
  663. """
  664. Start existing containers.
  665. Usage: start [SERVICE...]
  666. """
  667. containers = self.project.start(service_names=options['SERVICE'])
  668. exit_if(not containers, 'No containers to start', 1)
  669. def stop(self, options):
  670. """
  671. Stop running containers without removing them.
  672. They can be started again with `docker-compose start`.
  673. Usage: stop [options] [SERVICE...]
  674. Options:
  675. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  676. (default: 10)
  677. """
  678. timeout = timeout_from_opts(options)
  679. self.project.stop(service_names=options['SERVICE'], timeout=timeout)
  680. def restart(self, options):
  681. """
  682. Restart running containers.
  683. Usage: restart [options] [SERVICE...]
  684. Options:
  685. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  686. (default: 10)
  687. """
  688. timeout = timeout_from_opts(options)
  689. containers = self.project.restart(service_names=options['SERVICE'], timeout=timeout)
  690. exit_if(not containers, 'No containers to restart', 1)
  691. def top(self, options):
  692. """
  693. Display the running processes
  694. Usage: top [SERVICE...]
  695. """
  696. containers = sorted(
  697. self.project.containers(service_names=options['SERVICE'], stopped=False) +
  698. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  699. key=attrgetter('name')
  700. )
  701. for idx, container in enumerate(containers):
  702. if idx > 0:
  703. print()
  704. top_data = self.project.client.top(container.name)
  705. headers = top_data.get("Titles")
  706. rows = []
  707. for process in top_data.get("Processes", []):
  708. rows.append(process)
  709. print(container.name)
  710. print(Formatter().table(headers, rows))
  711. def unpause(self, options):
  712. """
  713. Unpause services.
  714. Usage: unpause [SERVICE...]
  715. """
  716. containers = self.project.unpause(service_names=options['SERVICE'])
  717. exit_if(not containers, 'No containers to unpause', 1)
  718. def up(self, options):
  719. """
  720. Builds, (re)creates, starts, and attaches to containers for a service.
  721. Unless they are already running, this command also starts any linked services.
  722. The `docker-compose up` command aggregates the output of each container. When
  723. the command exits, all containers are stopped. Running `docker-compose up -d`
  724. starts the containers in the background and leaves them running.
  725. If there are existing containers for a service, and the service's configuration
  726. or image was changed after the container's creation, `docker-compose up` picks
  727. up the changes by stopping and recreating the containers (preserving mounted
  728. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  729. flag.
  730. If you want to force Compose to stop and recreate all containers, use the
  731. `--force-recreate` flag.
  732. Usage: up [options] [--scale SERVICE=NUM...] [SERVICE...]
  733. Options:
  734. -d Detached mode: Run containers in the background,
  735. print new container names. Incompatible with
  736. --abort-on-container-exit and --timeout.
  737. --no-color Produce monochrome output.
  738. --no-deps Don't start linked services.
  739. --force-recreate Recreate containers even if their configuration
  740. and image haven't changed.
  741. Incompatible with --no-recreate.
  742. --no-recreate If containers already exist, don't recreate them.
  743. Incompatible with --force-recreate.
  744. --no-build Don't build an image, even if it's missing.
  745. --no-start Don't start the services after creating them.
  746. --build Build images before starting containers.
  747. --abort-on-container-exit Stops all containers if any container was stopped.
  748. Incompatible with -d.
  749. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  750. when attached or when containers are already.
  751. Incompatible with -d.
  752. running. (default: 10)
  753. --remove-orphans Remove containers for services not
  754. defined in the Compose file
  755. --exit-code-from SERVICE Return the exit code of the selected service container.
  756. Implies --abort-on-container-exit.
  757. --scale SERVICE=NUM Scale SERVICE to NUM instances. Overrides the `scale`
  758. setting in the Compose file if present.
  759. """
  760. start_deps = not options['--no-deps']
  761. exit_value_from = exitval_from_opts(options, self.project)
  762. cascade_stop = options['--abort-on-container-exit']
  763. service_names = options['SERVICE']
  764. timeout = timeout_from_opts(options)
  765. remove_orphans = options['--remove-orphans']
  766. detached = options.get('-d')
  767. no_start = options.get('--no-start')
  768. if detached and (cascade_stop or exit_value_from):
  769. raise UserError("--abort-on-container-exit and -d cannot be combined.")
  770. if detached and timeout:
  771. raise UserError("-d and --timeout cannot be combined.")
  772. if no_start:
  773. for excluded in ['-d', '--abort-on-container-exit', '--exit-code-from']:
  774. if options.get(excluded):
  775. raise UserError('--no-start and {} cannot be combined.'.format(excluded))
  776. with up_shutdown_context(self.project, service_names, timeout, detached):
  777. to_attach = self.project.up(
  778. service_names=service_names,
  779. start_deps=start_deps,
  780. strategy=convergence_strategy_from_opts(options),
  781. do_build=build_action_from_opts(options),
  782. timeout=timeout,
  783. detached=detached,
  784. remove_orphans=remove_orphans,
  785. scale_override=parse_scale_args(options['--scale']),
  786. start=not no_start
  787. )
  788. if detached or no_start:
  789. return
  790. attached_containers = filter_containers_to_service_names(to_attach, service_names)
  791. log_printer = log_printer_from_project(
  792. self.project,
  793. attached_containers,
  794. options['--no-color'],
  795. {'follow': True},
  796. cascade_stop,
  797. event_stream=self.project.events(service_names=service_names))
  798. print("Attaching to", list_containers(log_printer.containers))
  799. cascade_starter = log_printer.run()
  800. if cascade_stop:
  801. print("Aborting on container exit...")
  802. all_containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  803. exit_code = compute_exit_code(
  804. exit_value_from, attached_containers, cascade_starter, all_containers
  805. )
  806. self.project.stop(service_names=service_names, timeout=timeout)
  807. sys.exit(exit_code)
  808. @classmethod
  809. def version(cls, options):
  810. """
  811. Show version informations
  812. Usage: version [--short]
  813. Options:
  814. --short Shows only Compose's version number.
  815. """
  816. if options['--short']:
  817. print(__version__)
  818. else:
  819. print(get_version_info('full'))
  820. def compute_exit_code(exit_value_from, attached_containers, cascade_starter, all_containers):
  821. exit_code = 0
  822. if exit_value_from:
  823. candidates = list(filter(
  824. lambda c: c.service == exit_value_from,
  825. attached_containers))
  826. if not candidates:
  827. log.error(
  828. 'No containers matching the spec "{0}" '
  829. 'were run.'.format(exit_value_from)
  830. )
  831. exit_code = 2
  832. elif len(candidates) > 1:
  833. exit_values = filter(
  834. lambda e: e != 0,
  835. [c.inspect()['State']['ExitCode'] for c in candidates]
  836. )
  837. exit_code = exit_values[0]
  838. else:
  839. exit_code = candidates[0].inspect()['State']['ExitCode']
  840. else:
  841. for e in all_containers:
  842. if (not e.is_running and cascade_starter == e.name):
  843. if not e.exit_code == 0:
  844. exit_code = e.exit_code
  845. break
  846. return exit_code
  847. def convergence_strategy_from_opts(options):
  848. no_recreate = options['--no-recreate']
  849. force_recreate = options['--force-recreate']
  850. if force_recreate and no_recreate:
  851. raise UserError("--force-recreate and --no-recreate cannot be combined.")
  852. if force_recreate:
  853. return ConvergenceStrategy.always
  854. if no_recreate:
  855. return ConvergenceStrategy.never
  856. return ConvergenceStrategy.changed
  857. def timeout_from_opts(options):
  858. timeout = options.get('--timeout')
  859. return None if timeout is None else int(timeout)
  860. def image_digests_for_project(project, allow_push=False):
  861. with errors.handle_connection_errors(project.client):
  862. try:
  863. return get_image_digests(
  864. project,
  865. allow_push=allow_push
  866. )
  867. except MissingDigests as e:
  868. def list_images(images):
  869. return "\n".join(" {}".format(name) for name in sorted(images))
  870. paras = ["Some images are missing digests."]
  871. if e.needs_push:
  872. command_hint = (
  873. "Use `docker-compose push {}` to push them. "
  874. .format(" ".join(sorted(e.needs_push)))
  875. )
  876. paras += [
  877. "The following images can be pushed:",
  878. list_images(e.needs_push),
  879. command_hint,
  880. ]
  881. if e.needs_pull:
  882. command_hint = (
  883. "Use `docker-compose pull {}` to pull them. "
  884. .format(" ".join(sorted(e.needs_pull)))
  885. )
  886. paras += [
  887. "The following images need to be pulled:",
  888. list_images(e.needs_pull),
  889. command_hint,
  890. ]
  891. raise UserError("\n\n".join(paras))
  892. def exitval_from_opts(options, project):
  893. exit_value_from = options.get('--exit-code-from')
  894. if exit_value_from:
  895. if not options.get('--abort-on-container-exit'):
  896. log.warn('using --exit-code-from implies --abort-on-container-exit')
  897. options['--abort-on-container-exit'] = True
  898. if exit_value_from not in [s.name for s in project.get_services()]:
  899. log.error('No service named "%s" was found in your compose file.',
  900. exit_value_from)
  901. sys.exit(2)
  902. return exit_value_from
  903. def image_type_from_opt(flag, value):
  904. if not value:
  905. return ImageType.none
  906. try:
  907. return ImageType[value]
  908. except KeyError:
  909. raise UserError("%s flag must be one of: all, local" % flag)
  910. def build_action_from_opts(options):
  911. if options['--build'] and options['--no-build']:
  912. raise UserError("--build and --no-build can not be combined.")
  913. if options['--build']:
  914. return BuildAction.force
  915. if options['--no-build']:
  916. return BuildAction.skip
  917. return BuildAction.none
  918. def build_container_options(options, detach, command):
  919. container_options = {
  920. 'command': command,
  921. 'tty': not (detach or options['-T'] or not sys.stdin.isatty()),
  922. 'stdin_open': not detach,
  923. 'detach': detach,
  924. }
  925. if options['-e']:
  926. container_options['environment'] = Environment.from_command_line(
  927. parse_environment(options['-e'])
  928. )
  929. if options['--label']:
  930. container_options['labels'] = parse_labels(options['--label'])
  931. if options['--entrypoint']:
  932. container_options['entrypoint'] = options.get('--entrypoint')
  933. if options['--rm']:
  934. container_options['restart'] = None
  935. if options['--user']:
  936. container_options['user'] = options.get('--user')
  937. if not options['--service-ports']:
  938. container_options['ports'] = []
  939. if options['--publish']:
  940. container_options['ports'] = options.get('--publish')
  941. if options['--name']:
  942. container_options['name'] = options['--name']
  943. if options['--workdir']:
  944. container_options['working_dir'] = options['--workdir']
  945. if options['--volume']:
  946. volumes = [VolumeSpec.parse(i) for i in options['--volume']]
  947. container_options['volumes'] = volumes
  948. return container_options
  949. def run_one_off_container(container_options, project, service, options):
  950. if not options['--no-deps']:
  951. deps = service.get_dependency_names()
  952. if deps:
  953. project.up(
  954. service_names=deps,
  955. start_deps=True,
  956. strategy=ConvergenceStrategy.never,
  957. rescale=False
  958. )
  959. project.initialize()
  960. container = service.create_container(
  961. quiet=True,
  962. one_off=True,
  963. **container_options)
  964. if options['-d']:
  965. service.start_container(container)
  966. print(container.name)
  967. return
  968. def remove_container(force=False):
  969. if options['--rm']:
  970. project.client.remove_container(container.id, force=True, v=True)
  971. signals.set_signal_handler_to_shutdown()
  972. try:
  973. try:
  974. if IS_WINDOWS_PLATFORM:
  975. service.connect_container_to_networks(container)
  976. exit_code = call_docker(["start", "--attach", "--interactive", container.id])
  977. else:
  978. operation = RunOperation(
  979. project.client,
  980. container.id,
  981. interactive=not options['-T'],
  982. logs=False,
  983. )
  984. pty = PseudoTerminal(project.client, operation)
  985. sockets = pty.sockets()
  986. service.start_container(container)
  987. pty.start(sockets)
  988. exit_code = container.wait()
  989. except signals.ShutdownException:
  990. project.client.stop(container.id)
  991. exit_code = 1
  992. except signals.ShutdownException:
  993. project.client.kill(container.id)
  994. remove_container(force=True)
  995. sys.exit(2)
  996. remove_container()
  997. sys.exit(exit_code)
  998. def log_printer_from_project(
  999. project,
  1000. containers,
  1001. monochrome,
  1002. log_args,
  1003. cascade_stop=False,
  1004. event_stream=None,
  1005. ):
  1006. return LogPrinter(
  1007. containers,
  1008. build_log_presenters(project.service_names, monochrome),
  1009. event_stream or project.events(),
  1010. cascade_stop=cascade_stop,
  1011. log_args=log_args)
  1012. def filter_containers_to_service_names(containers, service_names):
  1013. if not service_names:
  1014. return containers
  1015. return [
  1016. container
  1017. for container in containers if container.service in service_names
  1018. ]
  1019. @contextlib.contextmanager
  1020. def up_shutdown_context(project, service_names, timeout, detached):
  1021. if detached:
  1022. yield
  1023. return
  1024. signals.set_signal_handler_to_shutdown()
  1025. try:
  1026. try:
  1027. yield
  1028. except signals.ShutdownException:
  1029. print("Gracefully stopping... (press Ctrl+C again to force)")
  1030. project.stop(service_names=service_names, timeout=timeout)
  1031. except signals.ShutdownException:
  1032. project.kill(service_names=service_names)
  1033. sys.exit(2)
  1034. def list_containers(containers):
  1035. return ", ".join(c.name for c in containers)
  1036. def exit_if(condition, message, exit_code):
  1037. if condition:
  1038. log.error(message)
  1039. raise SystemExit(exit_code)
  1040. def call_docker(args):
  1041. executable_path = find_executable('docker')
  1042. if not executable_path:
  1043. raise UserError(errors.docker_not_found_msg("Couldn't find `docker` binary."))
  1044. args = [executable_path] + args
  1045. log.debug(" ".join(map(pipes.quote, args)))
  1046. return subprocess.call(args)
  1047. def parse_scale_args(options):
  1048. res = {}
  1049. for s in options:
  1050. if '=' not in s:
  1051. raise UserError('Arguments to scale should be in the form service=num')
  1052. service_name, num = s.split('=', 1)
  1053. try:
  1054. num = int(num)
  1055. except ValueError:
  1056. raise UserError(
  1057. 'Number of containers for service "%s" is not a number' % service_name
  1058. )
  1059. res[service_name] = num
  1060. return res
  1061. def build_exec_command(options, container_id, command):
  1062. args = ["exec"]
  1063. if options["-d"]:
  1064. args += ["--detach"]
  1065. else:
  1066. args += ["--interactive"]
  1067. if not options["-T"]:
  1068. args += ["--tty"]
  1069. if options["--privileged"]:
  1070. args += ["--privileged"]
  1071. if options["--user"]:
  1072. args += ["--user", options["--user"]]
  1073. if options["--env"]:
  1074. for env_variable in options["--env"]:
  1075. args += ["--env", env_variable]
  1076. args += [container_id]
  1077. args += command
  1078. return args