main.py 24 KB

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