main.py 38 KB

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