main.py 37 KB

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