1
0

main.py 33 KB

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