main.py 24 KB

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