1
0

main.py 44 KB

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