main.py 44 KB

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