main.py 34 KB

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