main.py 35 KB

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