main.py 37 KB

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