main.py 44 KB

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