1
0

main.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. from __future__ import absolute_import
  2. from __future__ import print_function
  3. from __future__ import unicode_literals
  4. import json
  5. import logging
  6. import re
  7. import sys
  8. from inspect import getdoc
  9. from operator import attrgetter
  10. import yaml
  11. from docker.errors import APIError
  12. from requests.exceptions import ReadTimeout
  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 ..const import DEFAULT_TIMEOUT
  19. from ..const import HTTP_TIMEOUT
  20. from ..const import IS_WINDOWS_PLATFORM
  21. from ..progress_stream import StreamOutputError
  22. from ..project import NoSuchService
  23. from ..service import BuildError
  24. from ..service import ConvergenceStrategy
  25. from ..service import NeedsBuildError
  26. from .command import friendly_error_message
  27. from .command import get_config_path_from_options
  28. from .command import project_from_options
  29. from .docopt_command import DocoptCommand
  30. from .docopt_command import NoSuchCommand
  31. from .errors import UserError
  32. from .formatter import ConsoleWarningFormatter
  33. from .formatter import Formatter
  34. from .log_printer import LogPrinter
  35. from .utils import get_version_info
  36. from .utils import yesno
  37. if not IS_WINDOWS_PLATFORM:
  38. import dockerpty
  39. log = logging.getLogger(__name__)
  40. console_handler = logging.StreamHandler(sys.stderr)
  41. def main():
  42. setup_logging()
  43. try:
  44. command = TopLevelCommand()
  45. command.sys_dispatch()
  46. except KeyboardInterrupt:
  47. log.error("\nAborting.")
  48. sys.exit(1)
  49. except (UserError, NoSuchService, ConfigurationError) as e:
  50. log.error(e.msg)
  51. sys.exit(1)
  52. except NoSuchCommand as e:
  53. commands = "\n".join(parse_doc_section("commands:", getdoc(e.supercommand)))
  54. log.error("No such command: %s\n\n%s", e.command, commands)
  55. sys.exit(1)
  56. except APIError as e:
  57. log.error(e.explanation)
  58. sys.exit(1)
  59. except BuildError as e:
  60. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  61. sys.exit(1)
  62. except StreamOutputError as e:
  63. log.error(e)
  64. sys.exit(1)
  65. except NeedsBuildError as e:
  66. log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name)
  67. sys.exit(1)
  68. except ReadTimeout as e:
  69. log.error(
  70. "An HTTP request took too long to complete. Retry with --verbose to obtain debug information.\n"
  71. "If you encounter this issue regularly because of slow network conditions, consider setting "
  72. "COMPOSE_HTTP_TIMEOUT to a higher value (current value: %s)." % HTTP_TIMEOUT
  73. )
  74. sys.exit(1)
  75. def setup_logging():
  76. root_logger = logging.getLogger()
  77. root_logger.addHandler(console_handler)
  78. root_logger.setLevel(logging.DEBUG)
  79. # Disable requests logging
  80. logging.getLogger("requests").propagate = False
  81. def setup_console_handler(handler, verbose):
  82. if handler.stream.isatty():
  83. format_class = ConsoleWarningFormatter
  84. else:
  85. format_class = logging.Formatter
  86. if verbose:
  87. handler.setFormatter(format_class('%(name)s.%(funcName)s: %(message)s'))
  88. handler.setLevel(logging.DEBUG)
  89. else:
  90. handler.setFormatter(format_class())
  91. handler.setLevel(logging.INFO)
  92. # stolen from docopt master
  93. def parse_doc_section(name, source):
  94. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  95. re.IGNORECASE | re.MULTILINE)
  96. return [s.strip() for s in pattern.findall(source)]
  97. class TopLevelCommand(DocoptCommand):
  98. """Define and run multi-container applications with Docker.
  99. Usage:
  100. docker-compose [-f=<arg>...] [options] [COMMAND] [ARGS...]
  101. docker-compose -h|--help
  102. Options:
  103. -f, --file FILE Specify an alternate compose file (default: docker-compose.yml)
  104. -p, --project-name NAME Specify an alternate project name (default: directory name)
  105. --verbose Show more output
  106. -v, --version Print version and exit
  107. Commands:
  108. build Build or rebuild services
  109. config Validate and view the compose file
  110. create Create services
  111. events Receive real time events from containers
  112. help Get help on a command
  113. kill Kill containers
  114. logs View output from containers
  115. pause Pause services
  116. port Print the public port for a port binding
  117. ps List containers
  118. pull Pulls service images
  119. restart Restart services
  120. rm Remove stopped containers
  121. run Run a one-off command
  122. scale Set number of containers for a service
  123. start Start services
  124. stop Stop services
  125. unpause Unpause services
  126. up Create and start containers
  127. version Show the Docker-Compose version information
  128. """
  129. base_dir = '.'
  130. def docopt_options(self):
  131. options = super(TopLevelCommand, self).docopt_options()
  132. options['version'] = get_version_info('compose')
  133. return options
  134. def perform_command(self, options, handler, command_options):
  135. setup_console_handler(console_handler, options.get('--verbose'))
  136. if options['COMMAND'] in ('help', 'version'):
  137. # Skip looking up the compose file.
  138. handler(None, command_options)
  139. return
  140. if options['COMMAND'] == 'config':
  141. handler(options, command_options)
  142. return
  143. project = project_from_options(self.base_dir, options)
  144. with friendly_error_message():
  145. handler(project, command_options)
  146. def build(self, project, options):
  147. """
  148. Build or rebuild services.
  149. Services are built once and then tagged as `project_service`,
  150. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  151. contents of its build directory, you can run `docker-compose build` to rebuild it.
  152. Usage: build [options] [SERVICE...]
  153. Options:
  154. --force-rm Always remove intermediate containers.
  155. --no-cache Do not use cache when building the image.
  156. --pull Always attempt to pull a newer version of the image.
  157. """
  158. project.build(
  159. service_names=options['SERVICE'],
  160. no_cache=bool(options.get('--no-cache', False)),
  161. pull=bool(options.get('--pull', False)),
  162. force_rm=bool(options.get('--force-rm', False)))
  163. def config(self, config_options, options):
  164. """
  165. Validate and view the compose file.
  166. Usage: config [options]
  167. Options:
  168. -q, --quiet Only validate the configuration, don't print
  169. anything.
  170. --services Print the service names, one per line.
  171. """
  172. config_path = get_config_path_from_options(config_options)
  173. compose_config = config.load(config.find(self.base_dir, config_path))
  174. if options['--quiet']:
  175. return
  176. if options['--services']:
  177. print('\n'.join(service['name'] for service in compose_config.services))
  178. return
  179. compose_config = dict(
  180. (service.pop('name'), service) for service in compose_config.services)
  181. print(yaml.dump(
  182. compose_config,
  183. default_flow_style=False,
  184. indent=2,
  185. width=80))
  186. def create(self, project, options):
  187. """
  188. Creates containers for a service.
  189. Usage: create [options] [SERVICE...]
  190. Options:
  191. --force-recreate Recreate containers even if their configuration and
  192. image haven't changed. Incompatible with --no-recreate.
  193. --no-recreate If containers already exist, don't recreate them.
  194. Incompatible with --force-recreate.
  195. --no-build Don't build an image, even if it's missing
  196. """
  197. service_names = options['SERVICE']
  198. project.create(
  199. service_names=service_names,
  200. strategy=convergence_strategy_from_opts(options),
  201. do_build=not options['--no-build']
  202. )
  203. def events(self, project, options):
  204. """
  205. Receive real time events from containers.
  206. Usage: events [options] [SERVICE...]
  207. Options:
  208. --json Output events as a stream of json objects
  209. """
  210. def format_event(event):
  211. attributes = ["%s=%s" % item for item in event['attributes'].items()]
  212. return ("{time} {type} {action} {id} ({attrs})").format(
  213. attrs=", ".join(sorted(attributes)),
  214. **event)
  215. def json_format_event(event):
  216. event['time'] = event['time'].isoformat()
  217. return json.dumps(event)
  218. for event in project.events():
  219. formatter = json_format_event if options['--json'] else format_event
  220. print(formatter(event))
  221. sys.stdout.flush()
  222. def help(self, project, options):
  223. """
  224. Get help on a command.
  225. Usage: help COMMAND
  226. """
  227. handler = self.get_handler(options['COMMAND'])
  228. raise SystemExit(getdoc(handler))
  229. def kill(self, project, options):
  230. """
  231. Force stop service containers.
  232. Usage: kill [options] [SERVICE...]
  233. Options:
  234. -s SIGNAL SIGNAL to send to the container.
  235. Default signal is SIGKILL.
  236. """
  237. signal = options.get('-s', 'SIGKILL')
  238. project.kill(service_names=options['SERVICE'], signal=signal)
  239. def logs(self, project, options):
  240. """
  241. View output from containers.
  242. Usage: logs [options] [SERVICE...]
  243. Options:
  244. --no-color Produce monochrome output.
  245. """
  246. containers = project.containers(service_names=options['SERVICE'], stopped=True)
  247. monochrome = options['--no-color']
  248. print("Attaching to", list_containers(containers))
  249. LogPrinter(containers, monochrome=monochrome).run()
  250. def pause(self, project, options):
  251. """
  252. Pause services.
  253. Usage: pause [SERVICE...]
  254. """
  255. containers = project.pause(service_names=options['SERVICE'])
  256. exit_if(not containers, 'No containers to pause', 1)
  257. def port(self, project, options):
  258. """
  259. Print the public port for a port binding.
  260. Usage: port [options] SERVICE PRIVATE_PORT
  261. Options:
  262. --protocol=proto tcp or udp [default: tcp]
  263. --index=index index of the container if there are multiple
  264. instances of a service [default: 1]
  265. """
  266. index = int(options.get('--index'))
  267. service = project.get_service(options['SERVICE'])
  268. try:
  269. container = service.get_container(number=index)
  270. except ValueError as e:
  271. raise UserError(str(e))
  272. print(container.get_local_port(
  273. options['PRIVATE_PORT'],
  274. protocol=options.get('--protocol') or 'tcp') or '')
  275. def ps(self, project, options):
  276. """
  277. List containers.
  278. Usage: ps [options] [SERVICE...]
  279. Options:
  280. -q Only display IDs
  281. """
  282. containers = sorted(
  283. project.containers(service_names=options['SERVICE'], stopped=True) +
  284. project.containers(service_names=options['SERVICE'], one_off=True),
  285. key=attrgetter('name'))
  286. if options['-q']:
  287. for container in containers:
  288. print(container.id)
  289. else:
  290. headers = [
  291. 'Name',
  292. 'Command',
  293. 'State',
  294. 'Ports',
  295. ]
  296. rows = []
  297. for container in containers:
  298. command = container.human_readable_command
  299. if len(command) > 30:
  300. command = '%s ...' % command[:26]
  301. rows.append([
  302. container.name,
  303. command,
  304. container.human_readable_state,
  305. container.human_readable_ports,
  306. ])
  307. print(Formatter().table(headers, rows))
  308. def pull(self, project, options):
  309. """
  310. Pulls images for services.
  311. Usage: pull [options] [SERVICE...]
  312. Options:
  313. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  314. """
  315. project.pull(
  316. service_names=options['SERVICE'],
  317. ignore_pull_failures=options.get('--ignore-pull-failures')
  318. )
  319. def rm(self, project, options):
  320. """
  321. Remove stopped service containers.
  322. By default, volumes attached to containers will not be removed. You can see all
  323. volumes with `docker volume ls`.
  324. Any data which is not in a volume will be lost.
  325. Usage: rm [options] [SERVICE...]
  326. Options:
  327. -f, --force Don't ask to confirm removal
  328. -v Remove volumes associated with containers
  329. """
  330. all_containers = project.containers(service_names=options['SERVICE'], stopped=True)
  331. stopped_containers = [c for c in all_containers if not c.is_running]
  332. if len(stopped_containers) > 0:
  333. print("Going to remove", list_containers(stopped_containers))
  334. if options.get('--force') \
  335. or yesno("Are you sure? [yN] ", default=False):
  336. project.remove_stopped(
  337. service_names=options['SERVICE'],
  338. v=options.get('-v', False)
  339. )
  340. else:
  341. print("No stopped containers")
  342. def run(self, project, options):
  343. """
  344. Run a one-off command on a service.
  345. For example:
  346. $ docker-compose run web python manage.py shell
  347. By default, linked services will be started, unless they are already
  348. running. If you do not want to start linked services, use
  349. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  350. Usage: run [options] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  351. Options:
  352. -d Detached mode: Run container in the background, print
  353. new container name.
  354. --name NAME Assign a name to the container
  355. --entrypoint CMD Override the entrypoint of the image.
  356. -e KEY=VAL Set an environment variable (can be used multiple times)
  357. -u, --user="" Run as specified username or uid
  358. --no-deps Don't start linked services.
  359. --rm Remove container after run. Ignored in detached mode.
  360. -p, --publish=[] Publish a container's port(s) to the host
  361. --service-ports Run command with the service's ports enabled and mapped
  362. to the host.
  363. -T Disable pseudo-tty allocation. By default `docker-compose run`
  364. allocates a TTY.
  365. """
  366. service = project.get_service(options['SERVICE'])
  367. detach = options['-d']
  368. if IS_WINDOWS_PLATFORM and not detach:
  369. raise UserError(
  370. "Interactive mode is not yet supported on Windows.\n"
  371. "Please pass the -d flag when using `docker-compose run`."
  372. )
  373. if options['COMMAND']:
  374. command = [options['COMMAND']] + options['ARGS']
  375. else:
  376. command = service.options.get('command')
  377. container_options = {
  378. 'command': command,
  379. 'tty': not (detach or options['-T'] or not sys.stdin.isatty()),
  380. 'stdin_open': not detach,
  381. 'detach': detach,
  382. }
  383. if options['-e']:
  384. container_options['environment'] = parse_environment(options['-e'])
  385. if options['--entrypoint']:
  386. container_options['entrypoint'] = options.get('--entrypoint')
  387. if options['--rm']:
  388. container_options['restart'] = None
  389. if options['--user']:
  390. container_options['user'] = options.get('--user')
  391. if not options['--service-ports']:
  392. container_options['ports'] = []
  393. if options['--publish']:
  394. container_options['ports'] = options.get('--publish')
  395. if options['--publish'] and options['--service-ports']:
  396. raise UserError(
  397. 'Service port mapping and manual port mapping '
  398. 'can not be used togather'
  399. )
  400. if options['--name']:
  401. container_options['name'] = options['--name']
  402. run_one_off_container(container_options, project, service, options)
  403. def scale(self, project, options):
  404. """
  405. Set number of containers to run for a service.
  406. Numbers are specified in the form `service=num` as arguments.
  407. For example:
  408. $ docker-compose scale web=2 worker=3
  409. Usage: scale [options] [SERVICE=NUM...]
  410. Options:
  411. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  412. (default: 10)
  413. """
  414. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  415. for s in options['SERVICE=NUM']:
  416. if '=' not in s:
  417. raise UserError('Arguments to scale should be in the form service=num')
  418. service_name, num = s.split('=', 1)
  419. try:
  420. num = int(num)
  421. except ValueError:
  422. raise UserError('Number of containers for service "%s" is not a '
  423. 'number' % service_name)
  424. project.get_service(service_name).scale(num, timeout=timeout)
  425. def start(self, project, options):
  426. """
  427. Start existing containers.
  428. Usage: start [SERVICE...]
  429. """
  430. containers = project.start(service_names=options['SERVICE'])
  431. exit_if(not containers, 'No containers to start', 1)
  432. def stop(self, project, options):
  433. """
  434. Stop running containers without removing them.
  435. They can be started again with `docker-compose start`.
  436. Usage: stop [options] [SERVICE...]
  437. Options:
  438. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  439. (default: 10)
  440. """
  441. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  442. project.stop(service_names=options['SERVICE'], timeout=timeout)
  443. def restart(self, project, options):
  444. """
  445. Restart running containers.
  446. Usage: restart [options] [SERVICE...]
  447. Options:
  448. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  449. (default: 10)
  450. """
  451. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  452. containers = project.restart(service_names=options['SERVICE'], timeout=timeout)
  453. exit_if(not containers, 'No containers to restart', 1)
  454. def unpause(self, project, options):
  455. """
  456. Unpause services.
  457. Usage: unpause [SERVICE...]
  458. """
  459. containers = project.unpause(service_names=options['SERVICE'])
  460. exit_if(not containers, 'No containers to unpause', 1)
  461. def up(self, project, options):
  462. """
  463. Builds, (re)creates, starts, and attaches to containers for a service.
  464. Unless they are already running, this command also starts any linked services.
  465. The `docker-compose up` command aggregates the output of each container. When
  466. the command exits, all containers are stopped. Running `docker-compose up -d`
  467. starts the containers in the background and leaves them running.
  468. If there are existing containers for a service, and the service's configuration
  469. or image was changed after the container's creation, `docker-compose up` picks
  470. up the changes by stopping and recreating the containers (preserving mounted
  471. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  472. flag.
  473. If you want to force Compose to stop and recreate all containers, use the
  474. `--force-recreate` flag.
  475. Usage: up [options] [SERVICE...]
  476. Options:
  477. -d Detached mode: Run containers in the background,
  478. print new container names.
  479. --no-color Produce monochrome output.
  480. --no-deps Don't start linked services.
  481. --force-recreate Recreate containers even if their configuration and
  482. image haven't changed. Incompatible with --no-recreate.
  483. --no-recreate If containers already exist, don't recreate them.
  484. Incompatible with --force-recreate.
  485. --no-build Don't build an image, even if it's missing
  486. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  487. when attached or when containers are already
  488. running. (default: 10)
  489. """
  490. monochrome = options['--no-color']
  491. start_deps = not options['--no-deps']
  492. service_names = options['SERVICE']
  493. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  494. detached = options.get('-d')
  495. to_attach = project.up(
  496. service_names=service_names,
  497. start_deps=start_deps,
  498. strategy=convergence_strategy_from_opts(options),
  499. do_build=not options['--no-build'],
  500. timeout=timeout,
  501. detached=detached
  502. )
  503. if not detached:
  504. log_printer = build_log_printer(to_attach, service_names, monochrome)
  505. attach_to_logs(project, log_printer, service_names, timeout)
  506. def version(self, project, options):
  507. """
  508. Show version informations
  509. Usage: version [--short]
  510. Options:
  511. --short Shows only Compose's version number.
  512. """
  513. if options['--short']:
  514. print(__version__)
  515. else:
  516. print(get_version_info('full'))
  517. def convergence_strategy_from_opts(options):
  518. no_recreate = options['--no-recreate']
  519. force_recreate = options['--force-recreate']
  520. if force_recreate and no_recreate:
  521. raise UserError("--force-recreate and --no-recreate cannot be combined.")
  522. if force_recreate:
  523. return ConvergenceStrategy.always
  524. if no_recreate:
  525. return ConvergenceStrategy.never
  526. return ConvergenceStrategy.changed
  527. def run_one_off_container(container_options, project, service, options):
  528. if not options['--no-deps']:
  529. deps = service.get_linked_service_names()
  530. if deps:
  531. project.up(
  532. service_names=deps,
  533. start_deps=True,
  534. strategy=ConvergenceStrategy.never)
  535. if project.use_networking:
  536. project.ensure_network_exists()
  537. container = service.create_container(
  538. quiet=True,
  539. one_off=True,
  540. **container_options)
  541. if options['-d']:
  542. container.start()
  543. print(container.name)
  544. return
  545. def remove_container(force=False):
  546. if options['--rm']:
  547. project.client.remove_container(container.id, force=True)
  548. signals.set_signal_handler_to_shutdown()
  549. try:
  550. try:
  551. dockerpty.start(project.client, container.id, interactive=not options['-T'])
  552. exit_code = container.wait()
  553. except signals.ShutdownException:
  554. project.client.stop(container.id)
  555. exit_code = 1
  556. except signals.ShutdownException:
  557. project.client.kill(container.id)
  558. remove_container(force=True)
  559. sys.exit(2)
  560. remove_container()
  561. sys.exit(exit_code)
  562. def build_log_printer(containers, service_names, monochrome):
  563. if service_names:
  564. containers = [
  565. container
  566. for container in containers if container.service in service_names
  567. ]
  568. return LogPrinter(containers, monochrome=monochrome)
  569. def attach_to_logs(project, log_printer, service_names, timeout):
  570. print("Attaching to", list_containers(log_printer.containers))
  571. signals.set_signal_handler_to_shutdown()
  572. try:
  573. try:
  574. log_printer.run()
  575. except signals.ShutdownException:
  576. print("Gracefully stopping... (press Ctrl+C again to force)")
  577. project.stop(service_names=service_names, timeout=timeout)
  578. except signals.ShutdownException:
  579. project.kill(service_names=service_names)
  580. sys.exit(2)
  581. def list_containers(containers):
  582. return ", ".join(c.name for c in containers)
  583. def exit_if(condition, message, exit_code):
  584. if condition:
  585. log.error(message)
  586. raise SystemExit(exit_code)