main.py 23 KB

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