main.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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.environment import Environment
  24. from ..config.serialize import serialize_config
  25. from ..const import IS_WINDOWS_PLATFORM
  26. from ..errors import StreamParseError
  27. from ..progress_stream import StreamOutputError
  28. from ..project import NoSuchService
  29. from ..project import OneOffFilter
  30. from ..project import ProjectError
  31. from ..service import BuildAction
  32. from ..service import BuildError
  33. from ..service import ConvergenceStrategy
  34. from ..service import ImageType
  35. from ..service import NeedsBuildError
  36. from ..service import OperationFailedError
  37. from .command import get_config_from_options
  38. from .command import project_from_options
  39. from .docopt_command import DocoptDispatcher
  40. from .docopt_command import get_handler
  41. from .docopt_command import NoSuchCommand
  42. from .errors import UserError
  43. from .formatter import ConsoleWarningFormatter
  44. from .formatter import Formatter
  45. from .log_printer import build_log_presenters
  46. from .log_printer import LogPrinter
  47. from .utils import get_version_info
  48. from .utils import yesno
  49. if not IS_WINDOWS_PLATFORM:
  50. from dockerpty.pty import PseudoTerminal, RunOperation, ExecOperation
  51. log = logging.getLogger(__name__)
  52. console_handler = logging.StreamHandler(sys.stderr)
  53. def main():
  54. command = dispatch()
  55. try:
  56. command()
  57. except (KeyboardInterrupt, signals.ShutdownException):
  58. log.error("Aborting.")
  59. sys.exit(1)
  60. except (UserError, NoSuchService, ConfigurationError,
  61. ProjectError, OperationFailedError) as e:
  62. log.error(e.msg)
  63. sys.exit(1)
  64. except BuildError as e:
  65. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  66. sys.exit(1)
  67. except StreamOutputError as e:
  68. log.error(e)
  69. sys.exit(1)
  70. except NeedsBuildError as e:
  71. log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name)
  72. sys.exit(1)
  73. except (errors.ConnectionError, StreamParseError):
  74. sys.exit(1)
  75. def dispatch():
  76. setup_logging()
  77. dispatcher = DocoptDispatcher(
  78. TopLevelCommand,
  79. {'options_first': True, 'version': get_version_info('compose')})
  80. try:
  81. options, handler, command_options = dispatcher.parse(sys.argv[1:])
  82. except NoSuchCommand as e:
  83. commands = "\n".join(parse_doc_section("commands:", getdoc(e.supercommand)))
  84. log.error("No such command: %s\n\n%s", e.command, commands)
  85. sys.exit(1)
  86. setup_console_handler(console_handler, options.get('--verbose'))
  87. return functools.partial(perform_command, options, handler, command_options)
  88. def perform_command(options, handler, command_options):
  89. if options['COMMAND'] in ('help', 'version'):
  90. # Skip looking up the compose file.
  91. handler(command_options)
  92. return
  93. if options['COMMAND'] in ('config', 'bundle'):
  94. command = TopLevelCommand(None)
  95. handler(command, options, command_options)
  96. return
  97. project = project_from_options('.', options)
  98. command = TopLevelCommand(project)
  99. with errors.handle_connection_errors(project.client):
  100. handler(command, command_options)
  101. def setup_logging():
  102. root_logger = logging.getLogger()
  103. root_logger.addHandler(console_handler)
  104. root_logger.setLevel(logging.DEBUG)
  105. # Disable requests logging
  106. logging.getLogger("requests").propagate = False
  107. def setup_console_handler(handler, verbose):
  108. if handler.stream.isatty():
  109. format_class = ConsoleWarningFormatter
  110. else:
  111. format_class = logging.Formatter
  112. if verbose:
  113. handler.setFormatter(format_class('%(name)s.%(funcName)s: %(message)s'))
  114. handler.setLevel(logging.DEBUG)
  115. else:
  116. handler.setFormatter(format_class())
  117. handler.setLevel(logging.INFO)
  118. # stolen from docopt master
  119. def parse_doc_section(name, source):
  120. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  121. re.IGNORECASE | re.MULTILINE)
  122. return [s.strip() for s in pattern.findall(source)]
  123. class TopLevelCommand(object):
  124. """Define and run multi-container applications with Docker.
  125. Usage:
  126. docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  127. docker-compose -h|--help
  128. Options:
  129. -f, --file FILE Specify an alternate compose file (default: docker-compose.yml)
  130. -p, --project-name NAME Specify an alternate project name (default: directory name)
  131. --verbose Show more output
  132. -v, --version Print version and exit
  133. -H, --host HOST Daemon socket to connect to
  134. --tls Use TLS; implied by --tlsverify
  135. --tlscacert CA_PATH Trust certs signed only by this CA
  136. --tlscert CLIENT_CERT_PATH Path to TLS certificate file
  137. --tlskey TLS_KEY_PATH Path to TLS key file
  138. --tlsverify Use TLS and verify the remote
  139. --skip-hostname-check Don't check the daemon's hostname against the name specified
  140. in the client certificate (for example if your docker host
  141. is an IP address)
  142. Commands:
  143. build Build or rebuild services
  144. bundle Generate a Docker bundle from the Compose file
  145. config Validate and view the compose file
  146. create Create services
  147. down Stop and remove containers, networks, images, and volumes
  148. events Receive real time events from containers
  149. exec Execute a command in a running container
  150. help Get help on a command
  151. kill Kill containers
  152. logs View output from containers
  153. pause Pause services
  154. port Print the public port for a port binding
  155. ps List containers
  156. pull Pull service images
  157. push Push service images
  158. restart Restart services
  159. rm Remove stopped containers
  160. run Run a one-off command
  161. scale Set number of containers for a service
  162. start Start services
  163. stop Stop services
  164. top Display the running processes
  165. unpause Unpause services
  166. up Create and start containers
  167. version Show the Docker-Compose version information
  168. """
  169. def __init__(self, project, project_dir='.'):
  170. self.project = project
  171. self.project_dir = '.'
  172. def build(self, options):
  173. """
  174. Build or rebuild services.
  175. Services are built once and then tagged as `project_service`,
  176. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  177. contents of its build directory, you can run `docker-compose build` to rebuild it.
  178. Usage: build [options] [SERVICE...]
  179. Options:
  180. --force-rm Always remove intermediate containers.
  181. --no-cache Do not use cache when building the image.
  182. --pull Always attempt to pull a newer version of the image.
  183. """
  184. self.project.build(
  185. service_names=options['SERVICE'],
  186. no_cache=bool(options.get('--no-cache', False)),
  187. pull=bool(options.get('--pull', False)),
  188. force_rm=bool(options.get('--force-rm', False)))
  189. def bundle(self, config_options, options):
  190. """
  191. Generate a Distributed Application Bundle (DAB) from the Compose file.
  192. Images must have digests stored, which requires interaction with a
  193. Docker registry. If digests aren't stored for all images, you can fetch
  194. them with `docker-compose pull` or `docker-compose push`. To push images
  195. automatically when bundling, pass `--push-images`. Only services with
  196. a `build` option specified will have their images pushed.
  197. Usage: bundle [options]
  198. Options:
  199. --push-images Automatically push images for any services
  200. which have a `build` option specified.
  201. -o, --output PATH Path to write the bundle file to.
  202. Defaults to "<project name>.dab".
  203. """
  204. self.project = project_from_options('.', config_options)
  205. compose_config = get_config_from_options(self.project_dir, config_options)
  206. output = options["--output"]
  207. if not output:
  208. output = "{}.dab".format(self.project.name)
  209. with errors.handle_connection_errors(self.project.client):
  210. try:
  211. image_digests = get_image_digests(
  212. self.project,
  213. allow_push=options['--push-images'],
  214. )
  215. except MissingDigests as e:
  216. def list_images(images):
  217. return "\n".join(" {}".format(name) for name in sorted(images))
  218. paras = ["Some images are missing digests."]
  219. if e.needs_push:
  220. command_hint = (
  221. "Use `docker-compose push {}` to push them. "
  222. "You can do this automatically with `docker-compose bundle --push-images`."
  223. .format(" ".join(sorted(e.needs_push)))
  224. )
  225. paras += [
  226. "The following images can be pushed:",
  227. list_images(e.needs_push),
  228. command_hint,
  229. ]
  230. if e.needs_pull:
  231. command_hint = (
  232. "Use `docker-compose pull {}` to pull them. "
  233. .format(" ".join(sorted(e.needs_pull)))
  234. )
  235. paras += [
  236. "The following images need to be pulled:",
  237. list_images(e.needs_pull),
  238. command_hint,
  239. ]
  240. raise UserError("\n\n".join(paras))
  241. with open(output, 'w') as f:
  242. f.write(serialize_bundle(compose_config, image_digests))
  243. log.info("Wrote bundle to {}".format(output))
  244. def config(self, config_options, options):
  245. """
  246. Validate and view the compose file.
  247. Usage: config [options]
  248. Options:
  249. -q, --quiet Only validate the configuration, don't print
  250. anything.
  251. --services Print the service names, one per line.
  252. """
  253. compose_config = get_config_from_options(self.project_dir, config_options)
  254. if options['--quiet']:
  255. return
  256. if options['--services']:
  257. print('\n'.join(service['name'] for service in compose_config.services))
  258. return
  259. print(serialize_config(compose_config))
  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. --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)
  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 kill(self, options):
  393. """
  394. Force stop service containers.
  395. Usage: kill [options] [SERVICE...]
  396. Options:
  397. -s SIGNAL SIGNAL to send to the container.
  398. Default signal is SIGKILL.
  399. """
  400. signal = options.get('-s', 'SIGKILL')
  401. self.project.kill(service_names=options['SERVICE'], signal=signal)
  402. def logs(self, options):
  403. """
  404. View output from containers.
  405. Usage: logs [options] [SERVICE...]
  406. Options:
  407. --no-color Produce monochrome output.
  408. -f, --follow Follow log output.
  409. -t, --timestamps Show timestamps.
  410. --tail="all" Number of lines to show from the end of the logs
  411. for each container.
  412. """
  413. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  414. tail = options['--tail']
  415. if tail is not None:
  416. if tail.isdigit():
  417. tail = int(tail)
  418. elif tail != 'all':
  419. raise UserError("tail flag must be all or a number")
  420. log_args = {
  421. 'follow': options['--follow'],
  422. 'tail': tail,
  423. 'timestamps': options['--timestamps']
  424. }
  425. print("Attaching to", list_containers(containers))
  426. log_printer_from_project(
  427. self.project,
  428. containers,
  429. options['--no-color'],
  430. log_args,
  431. event_stream=self.project.events(service_names=options['SERVICE'])).run()
  432. def pause(self, options):
  433. """
  434. Pause services.
  435. Usage: pause [SERVICE...]
  436. """
  437. containers = self.project.pause(service_names=options['SERVICE'])
  438. exit_if(not containers, 'No containers to pause', 1)
  439. def port(self, options):
  440. """
  441. Print the public port for a port binding.
  442. Usage: port [options] SERVICE PRIVATE_PORT
  443. Options:
  444. --protocol=proto tcp or udp [default: tcp]
  445. --index=index index of the container if there are multiple
  446. instances of a service [default: 1]
  447. """
  448. index = int(options.get('--index'))
  449. service = self.project.get_service(options['SERVICE'])
  450. try:
  451. container = service.get_container(number=index)
  452. except ValueError as e:
  453. raise UserError(str(e))
  454. print(container.get_local_port(
  455. options['PRIVATE_PORT'],
  456. protocol=options.get('--protocol') or 'tcp') or '')
  457. def ps(self, options):
  458. """
  459. List containers.
  460. Usage: ps [options] [SERVICE...]
  461. Options:
  462. -q Only display IDs
  463. """
  464. containers = sorted(
  465. self.project.containers(service_names=options['SERVICE'], stopped=True) +
  466. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  467. key=attrgetter('name'))
  468. if options['-q']:
  469. for container in containers:
  470. print(container.id)
  471. else:
  472. headers = [
  473. 'Name',
  474. 'Command',
  475. 'State',
  476. 'Ports',
  477. ]
  478. rows = []
  479. for container in containers:
  480. command = container.human_readable_command
  481. if len(command) > 30:
  482. command = '%s ...' % command[:26]
  483. rows.append([
  484. container.name,
  485. command,
  486. container.human_readable_state,
  487. container.human_readable_ports,
  488. ])
  489. print(Formatter().table(headers, rows))
  490. def pull(self, options):
  491. """
  492. Pulls images for services.
  493. Usage: pull [options] [SERVICE...]
  494. Options:
  495. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  496. --parallel Pull multiple images in parallel.
  497. """
  498. self.project.pull(
  499. service_names=options['SERVICE'],
  500. ignore_pull_failures=options.get('--ignore-pull-failures'),
  501. parallel_pull=options.get('--parallel')
  502. )
  503. def push(self, options):
  504. """
  505. Pushes images for services.
  506. Usage: push [options] [SERVICE...]
  507. Options:
  508. --ignore-push-failures Push what it can and ignores images with push failures.
  509. """
  510. self.project.push(
  511. service_names=options['SERVICE'],
  512. ignore_push_failures=options.get('--ignore-push-failures')
  513. )
  514. def rm(self, options):
  515. """
  516. Removes stopped service containers.
  517. By default, anonymous volumes attached to containers will not be removed. You
  518. can override this with `-v`. To list all volumes, use `docker volume ls`.
  519. Any data which is not in a volume will be lost.
  520. Usage: rm [options] [SERVICE...]
  521. Options:
  522. -f, --force Don't ask to confirm removal
  523. -v Remove any anonymous volumes attached to containers
  524. -a, --all Deprecated - no effect.
  525. """
  526. if options.get('--all'):
  527. log.warn(
  528. '--all flag is obsolete. This is now the default behavior '
  529. 'of `docker-compose rm`'
  530. )
  531. one_off = OneOffFilter.include
  532. all_containers = self.project.containers(
  533. service_names=options['SERVICE'], stopped=True, one_off=one_off
  534. )
  535. stopped_containers = [c for c in all_containers if not c.is_running]
  536. if len(stopped_containers) > 0:
  537. print("Going to remove", list_containers(stopped_containers))
  538. if options.get('--force') \
  539. or yesno("Are you sure? [yN] ", default=False):
  540. self.project.remove_stopped(
  541. service_names=options['SERVICE'],
  542. v=options.get('-v', False),
  543. one_off=one_off
  544. )
  545. else:
  546. print("No stopped containers")
  547. def run(self, options):
  548. """
  549. Run a one-off command on a service.
  550. For example:
  551. $ docker-compose run web python manage.py shell
  552. By default, linked services will be started, unless they are already
  553. running. If you do not want to start linked services, use
  554. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  555. Usage: run [options] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  556. Options:
  557. -d Detached mode: Run container in the background, print
  558. new container name.
  559. --name NAME Assign a name to the container
  560. --entrypoint CMD Override the entrypoint of the image.
  561. -e KEY=VAL Set an environment variable (can be used multiple times)
  562. -u, --user="" Run as specified username or uid
  563. --no-deps Don't start linked services.
  564. --rm Remove container after run. Ignored in detached mode.
  565. -p, --publish=[] Publish a container's port(s) to the host
  566. --service-ports Run command with the service's ports enabled and mapped
  567. to the host.
  568. -T Disable pseudo-tty allocation. By default `docker-compose run`
  569. allocates a TTY.
  570. -w, --workdir="" Working directory inside the container
  571. """
  572. service = self.project.get_service(options['SERVICE'])
  573. detach = options['-d']
  574. if options['--publish'] and options['--service-ports']:
  575. raise UserError(
  576. 'Service port mapping and manual port mapping '
  577. 'can not be used together'
  578. )
  579. if options['COMMAND'] is not None:
  580. command = [options['COMMAND']] + options['ARGS']
  581. elif options['--entrypoint'] is not None:
  582. command = []
  583. else:
  584. command = service.options.get('command')
  585. container_options = build_container_options(options, detach, command)
  586. run_one_off_container(container_options, self.project, service, options)
  587. def scale(self, options):
  588. """
  589. Set number of containers to run for a service.
  590. Numbers are specified in the form `service=num` as arguments.
  591. For example:
  592. $ docker-compose scale web=2 worker=3
  593. Usage: scale [options] [SERVICE=NUM...]
  594. Options:
  595. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  596. (default: 10)
  597. """
  598. timeout = timeout_from_opts(options)
  599. for s in options['SERVICE=NUM']:
  600. if '=' not in s:
  601. raise UserError('Arguments to scale should be in the form service=num')
  602. service_name, num = s.split('=', 1)
  603. try:
  604. num = int(num)
  605. except ValueError:
  606. raise UserError('Number of containers for service "%s" is not a '
  607. 'number' % service_name)
  608. self.project.get_service(service_name).scale(num, timeout=timeout)
  609. def start(self, options):
  610. """
  611. Start existing containers.
  612. Usage: start [SERVICE...]
  613. """
  614. containers = self.project.start(service_names=options['SERVICE'])
  615. exit_if(not containers, 'No containers to start', 1)
  616. def stop(self, options):
  617. """
  618. Stop running containers without removing them.
  619. They can be started again with `docker-compose start`.
  620. Usage: stop [options] [SERVICE...]
  621. Options:
  622. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  623. (default: 10)
  624. """
  625. timeout = timeout_from_opts(options)
  626. self.project.stop(service_names=options['SERVICE'], timeout=timeout)
  627. def restart(self, options):
  628. """
  629. Restart running containers.
  630. Usage: restart [options] [SERVICE...]
  631. Options:
  632. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  633. (default: 10)
  634. """
  635. timeout = timeout_from_opts(options)
  636. containers = self.project.restart(service_names=options['SERVICE'], timeout=timeout)
  637. exit_if(not containers, 'No containers to restart', 1)
  638. def top(self, options):
  639. """
  640. Display the running processes
  641. Usage: top [SERVICE...]
  642. """
  643. containers = sorted(
  644. self.project.containers(service_names=options['SERVICE'], stopped=False) +
  645. self.project.containers(service_names=options['SERVICE'], one_off=OneOffFilter.only),
  646. key=attrgetter('name')
  647. )
  648. for idx, container in enumerate(containers):
  649. if idx > 0:
  650. print()
  651. top_data = self.project.client.top(container.name)
  652. headers = top_data.get("Titles")
  653. rows = []
  654. for process in top_data.get("Processes", []):
  655. rows.append(process)
  656. print(container.name)
  657. print(Formatter().table(headers, rows))
  658. def unpause(self, options):
  659. """
  660. Unpause services.
  661. Usage: unpause [SERVICE...]
  662. """
  663. containers = self.project.unpause(service_names=options['SERVICE'])
  664. exit_if(not containers, 'No containers to unpause', 1)
  665. def up(self, options):
  666. """
  667. Builds, (re)creates, starts, and attaches to containers for a service.
  668. Unless they are already running, this command also starts any linked services.
  669. The `docker-compose up` command aggregates the output of each container. When
  670. the command exits, all containers are stopped. Running `docker-compose up -d`
  671. starts the containers in the background and leaves them running.
  672. If there are existing containers for a service, and the service's configuration
  673. or image was changed after the container's creation, `docker-compose up` picks
  674. up the changes by stopping and recreating the containers (preserving mounted
  675. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  676. flag.
  677. If you want to force Compose to stop and recreate all containers, use the
  678. `--force-recreate` flag.
  679. Usage: up [options] [SERVICE...]
  680. Options:
  681. -d Detached mode: Run containers in the background,
  682. print new container names.
  683. Incompatible with --abort-on-container-exit.
  684. --no-color Produce monochrome output.
  685. --no-deps Don't start linked services.
  686. --force-recreate Recreate containers even if their configuration
  687. and image haven't changed.
  688. Incompatible with --no-recreate.
  689. --no-recreate If containers already exist, don't recreate them.
  690. Incompatible with --force-recreate.
  691. --no-build Don't build an image, even if it's missing.
  692. --build Build images before starting containers.
  693. --abort-on-container-exit Stops all containers if any container was stopped.
  694. Incompatible with -d.
  695. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  696. when attached or when containers are already
  697. running. (default: 10)
  698. --remove-orphans Remove containers for services not
  699. defined in the Compose file
  700. """
  701. start_deps = not options['--no-deps']
  702. cascade_stop = options['--abort-on-container-exit']
  703. service_names = options['SERVICE']
  704. timeout = timeout_from_opts(options)
  705. remove_orphans = options['--remove-orphans']
  706. detached = options.get('-d')
  707. if detached and cascade_stop:
  708. raise UserError("--abort-on-container-exit and -d cannot be combined.")
  709. with up_shutdown_context(self.project, service_names, timeout, detached):
  710. to_attach = self.project.up(
  711. service_names=service_names,
  712. start_deps=start_deps,
  713. strategy=convergence_strategy_from_opts(options),
  714. do_build=build_action_from_opts(options),
  715. timeout=timeout,
  716. detached=detached,
  717. remove_orphans=remove_orphans)
  718. if detached:
  719. return
  720. log_printer = log_printer_from_project(
  721. self.project,
  722. filter_containers_to_service_names(to_attach, service_names),
  723. options['--no-color'],
  724. {'follow': True},
  725. cascade_stop,
  726. event_stream=self.project.events(service_names=service_names))
  727. print("Attaching to", list_containers(log_printer.containers))
  728. log_printer.run()
  729. if cascade_stop:
  730. print("Aborting on container exit...")
  731. self.project.stop(service_names=service_names, timeout=timeout)
  732. @classmethod
  733. def version(cls, options):
  734. """
  735. Show version informations
  736. Usage: version [--short]
  737. Options:
  738. --short Shows only Compose's version number.
  739. """
  740. if options['--short']:
  741. print(__version__)
  742. else:
  743. print(get_version_info('full'))
  744. def convergence_strategy_from_opts(options):
  745. no_recreate = options['--no-recreate']
  746. force_recreate = options['--force-recreate']
  747. if force_recreate and no_recreate:
  748. raise UserError("--force-recreate and --no-recreate cannot be combined.")
  749. if force_recreate:
  750. return ConvergenceStrategy.always
  751. if no_recreate:
  752. return ConvergenceStrategy.never
  753. return ConvergenceStrategy.changed
  754. def timeout_from_opts(options):
  755. timeout = options.get('--timeout')
  756. return None if timeout is None else int(timeout)
  757. def image_type_from_opt(flag, value):
  758. if not value:
  759. return ImageType.none
  760. try:
  761. return ImageType[value]
  762. except KeyError:
  763. raise UserError("%s flag must be one of: all, local" % flag)
  764. def build_action_from_opts(options):
  765. if options['--build'] and options['--no-build']:
  766. raise UserError("--build and --no-build can not be combined.")
  767. if options['--build']:
  768. return BuildAction.force
  769. if options['--no-build']:
  770. return BuildAction.skip
  771. return BuildAction.none
  772. def build_container_options(options, detach, command):
  773. container_options = {
  774. 'command': command,
  775. 'tty': not (detach or options['-T'] or not sys.stdin.isatty()),
  776. 'stdin_open': not detach,
  777. 'detach': detach,
  778. }
  779. if options['-e']:
  780. container_options['environment'] = Environment.from_command_line(
  781. parse_environment(options['-e'])
  782. )
  783. if options['--entrypoint']:
  784. container_options['entrypoint'] = options.get('--entrypoint')
  785. if options['--rm']:
  786. container_options['restart'] = None
  787. if options['--user']:
  788. container_options['user'] = options.get('--user')
  789. if not options['--service-ports']:
  790. container_options['ports'] = []
  791. if options['--publish']:
  792. container_options['ports'] = options.get('--publish')
  793. if options['--name']:
  794. container_options['name'] = options['--name']
  795. if options['--workdir']:
  796. container_options['working_dir'] = options['--workdir']
  797. return container_options
  798. def run_one_off_container(container_options, project, service, options):
  799. if not options['--no-deps']:
  800. deps = service.get_dependency_names()
  801. if deps:
  802. project.up(
  803. service_names=deps,
  804. start_deps=True,
  805. strategy=ConvergenceStrategy.never)
  806. project.initialize()
  807. container = service.create_container(
  808. quiet=True,
  809. one_off=True,
  810. **container_options)
  811. if options['-d']:
  812. service.start_container(container)
  813. print(container.name)
  814. return
  815. def remove_container(force=False):
  816. if options['--rm']:
  817. project.client.remove_container(container.id, force=True)
  818. signals.set_signal_handler_to_shutdown()
  819. try:
  820. try:
  821. if IS_WINDOWS_PLATFORM:
  822. service.connect_container_to_networks(container)
  823. exit_code = call_docker(["start", "--attach", "--interactive", container.id])
  824. else:
  825. operation = RunOperation(
  826. project.client,
  827. container.id,
  828. interactive=not options['-T'],
  829. logs=False,
  830. )
  831. pty = PseudoTerminal(project.client, operation)
  832. sockets = pty.sockets()
  833. service.start_container(container)
  834. pty.start(sockets)
  835. exit_code = container.wait()
  836. except signals.ShutdownException:
  837. project.client.stop(container.id)
  838. exit_code = 1
  839. except signals.ShutdownException:
  840. project.client.kill(container.id)
  841. remove_container(force=True)
  842. sys.exit(2)
  843. remove_container()
  844. sys.exit(exit_code)
  845. def log_printer_from_project(
  846. project,
  847. containers,
  848. monochrome,
  849. log_args,
  850. cascade_stop=False,
  851. event_stream=None,
  852. ):
  853. return LogPrinter(
  854. containers,
  855. build_log_presenters(project.service_names, monochrome),
  856. event_stream or project.events(),
  857. cascade_stop=cascade_stop,
  858. log_args=log_args)
  859. def filter_containers_to_service_names(containers, service_names):
  860. if not service_names:
  861. return containers
  862. return [
  863. container
  864. for container in containers if container.service in service_names
  865. ]
  866. @contextlib.contextmanager
  867. def up_shutdown_context(project, service_names, timeout, detached):
  868. if detached:
  869. yield
  870. return
  871. signals.set_signal_handler_to_shutdown()
  872. try:
  873. try:
  874. yield
  875. except signals.ShutdownException:
  876. print("Gracefully stopping... (press Ctrl+C again to force)")
  877. project.stop(service_names=service_names, timeout=timeout)
  878. except signals.ShutdownException:
  879. project.kill(service_names=service_names)
  880. sys.exit(2)
  881. def list_containers(containers):
  882. return ", ".join(c.name for c in containers)
  883. def exit_if(condition, message, exit_code):
  884. if condition:
  885. log.error(message)
  886. raise SystemExit(exit_code)
  887. def call_docker(args):
  888. executable_path = find_executable('docker')
  889. if not executable_path:
  890. raise UserError(errors.docker_not_found_msg("Couldn't find `docker` binary."))
  891. args = [executable_path] + args
  892. log.debug(" ".join(map(pipes.quote, args)))
  893. return subprocess.call(args)