main.py 43 KB

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