main.py 36 KB

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