main.py 36 KB

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