main.py 38 KB

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