main.py 32 KB

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