main.py 36 KB

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