main.py 43 KB

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