1
0

main.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. from docker.errors import APIError
  10. from requests.exceptions import ReadTimeout
  11. from .. import __version__
  12. from .. import legacy
  13. from ..config import ConfigurationError
  14. from ..config import parse_environment
  15. from ..const import DEFAULT_TIMEOUT
  16. from ..const import HTTP_TIMEOUT
  17. from ..const import IS_WINDOWS_PLATFORM
  18. from ..progress_stream import StreamOutputError
  19. from ..project import NoSuchService
  20. from ..service import BuildError
  21. from ..service import ConvergenceStrategy
  22. from ..service import NeedsBuildError
  23. from .command import friendly_error_message
  24. from .command import project_from_options
  25. from .docopt_command import DocoptCommand
  26. from .docopt_command import NoSuchCommand
  27. from .errors import UserError
  28. from .formatter import ConsoleWarningFormatter
  29. from .formatter import Formatter
  30. from .log_printer import LogPrinter
  31. from .utils import get_version_info
  32. from .utils import yesno
  33. if not IS_WINDOWS_PLATFORM:
  34. import dockerpty
  35. log = logging.getLogger(__name__)
  36. console_handler = logging.StreamHandler(sys.stderr)
  37. INSECURE_SSL_WARNING = """
  38. --allow-insecure-ssl is deprecated and has no effect.
  39. It will be removed in a future version of Compose.
  40. """
  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, legacy.LegacyError) 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. --x-networking (EXPERIMENTAL) Use new Docker networking functionality.
  106. Requires Docker 1.9 or later.
  107. --x-network-driver DRIVER (EXPERIMENTAL) Specify a network driver (default: "bridge").
  108. Requires Docker 1.9 or later.
  109. --verbose Show more output
  110. -v, --version Print version and exit
  111. Commands:
  112. build Build or rebuild 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. migrate-to-labels Recreate containers to add labels
  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. project = project_from_options(self.base_dir, options)
  143. with friendly_error_message():
  144. handler(project, command_options)
  145. def build(self, project, options):
  146. """
  147. Build or rebuild services.
  148. Services are built once and then tagged as `project_service`,
  149. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  150. contents of its build directory, you can run `docker-compose build` to rebuild it.
  151. Usage: build [options] [SERVICE...]
  152. Options:
  153. --force-rm Always remove intermediate containers.
  154. --no-cache Do not use cache when building the image.
  155. --pull Always attempt to pull a newer version of the image.
  156. """
  157. project.build(
  158. service_names=options['SERVICE'],
  159. no_cache=bool(options.get('--no-cache', False)),
  160. pull=bool(options.get('--pull', False)),
  161. force_rm=bool(options.get('--force-rm', False)))
  162. def help(self, project, options):
  163. """
  164. Get help on a command.
  165. Usage: help COMMAND
  166. """
  167. handler = self.get_handler(options['COMMAND'])
  168. raise SystemExit(getdoc(handler))
  169. def kill(self, project, options):
  170. """
  171. Force stop service containers.
  172. Usage: kill [options] [SERVICE...]
  173. Options:
  174. -s SIGNAL SIGNAL to send to the container.
  175. Default signal is SIGKILL.
  176. """
  177. signal = options.get('-s', 'SIGKILL')
  178. project.kill(service_names=options['SERVICE'], signal=signal)
  179. def logs(self, project, options):
  180. """
  181. View output from containers.
  182. Usage: logs [options] [SERVICE...]
  183. Options:
  184. --no-color Produce monochrome output.
  185. """
  186. containers = project.containers(service_names=options['SERVICE'], stopped=True)
  187. monochrome = options['--no-color']
  188. print("Attaching to", list_containers(containers))
  189. LogPrinter(containers, monochrome=monochrome).run()
  190. def pause(self, project, options):
  191. """
  192. Pause services.
  193. Usage: pause [SERVICE...]
  194. """
  195. project.pause(service_names=options['SERVICE'])
  196. def port(self, project, options):
  197. """
  198. Print the public port for a port binding.
  199. Usage: port [options] SERVICE PRIVATE_PORT
  200. Options:
  201. --protocol=proto tcp or udp [default: tcp]
  202. --index=index index of the container if there are multiple
  203. instances of a service [default: 1]
  204. """
  205. index = int(options.get('--index'))
  206. service = project.get_service(options['SERVICE'])
  207. try:
  208. container = service.get_container(number=index)
  209. except ValueError as e:
  210. raise UserError(str(e))
  211. print(container.get_local_port(
  212. options['PRIVATE_PORT'],
  213. protocol=options.get('--protocol') or 'tcp') or '')
  214. def ps(self, project, options):
  215. """
  216. List containers.
  217. Usage: ps [options] [SERVICE...]
  218. Options:
  219. -q Only display IDs
  220. """
  221. containers = sorted(
  222. project.containers(service_names=options['SERVICE'], stopped=True) +
  223. project.containers(service_names=options['SERVICE'], one_off=True),
  224. key=attrgetter('name'))
  225. if options['-q']:
  226. for container in containers:
  227. print(container.id)
  228. else:
  229. headers = [
  230. 'Name',
  231. 'Command',
  232. 'State',
  233. 'Ports',
  234. ]
  235. rows = []
  236. for container in containers:
  237. command = container.human_readable_command
  238. if len(command) > 30:
  239. command = '%s ...' % command[:26]
  240. rows.append([
  241. container.name,
  242. command,
  243. container.human_readable_state,
  244. container.human_readable_ports,
  245. ])
  246. print(Formatter().table(headers, rows))
  247. def pull(self, project, options):
  248. """
  249. Pulls images for services.
  250. Usage: pull [options] [SERVICE...]
  251. Options:
  252. --ignore-pull-failures Pull what it can and ignores images with pull failures.
  253. --allow-insecure-ssl Deprecated - no effect.
  254. """
  255. if options['--allow-insecure-ssl']:
  256. log.warn(INSECURE_SSL_WARNING)
  257. project.pull(
  258. service_names=options['SERVICE'],
  259. ignore_pull_failures=options.get('--ignore-pull-failures')
  260. )
  261. def rm(self, project, options):
  262. """
  263. Remove stopped service containers.
  264. Usage: rm [options] [SERVICE...]
  265. Options:
  266. -f, --force Don't ask to confirm removal
  267. -v Remove volumes associated with containers
  268. """
  269. all_containers = project.containers(service_names=options['SERVICE'], stopped=True)
  270. stopped_containers = [c for c in all_containers if not c.is_running]
  271. if len(stopped_containers) > 0:
  272. print("Going to remove", list_containers(stopped_containers))
  273. if options.get('--force') \
  274. or yesno("Are you sure? [yN] ", default=False):
  275. project.remove_stopped(
  276. service_names=options['SERVICE'],
  277. v=options.get('-v', False)
  278. )
  279. else:
  280. print("No stopped containers")
  281. def run(self, project, options):
  282. """
  283. Run a one-off command on a service.
  284. For example:
  285. $ docker-compose run web python manage.py shell
  286. By default, linked services will be started, unless they are already
  287. running. If you do not want to start linked services, use
  288. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  289. Usage: run [options] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  290. Options:
  291. --allow-insecure-ssl Deprecated - no effect.
  292. -d Detached mode: Run container in the background, print
  293. new container name.
  294. --name NAME Assign a name to the container
  295. --entrypoint CMD Override the entrypoint of the image.
  296. -e KEY=VAL Set an environment variable (can be used multiple times)
  297. -u, --user="" Run as specified username or uid
  298. --no-deps Don't start linked services.
  299. --rm Remove container after run. Ignored in detached mode.
  300. -p, --publish=[] Publish a container's port(s) to the host
  301. --service-ports Run command with the service's ports enabled and mapped
  302. to the host.
  303. -T Disable pseudo-tty allocation. By default `docker-compose run`
  304. allocates a TTY.
  305. """
  306. service = project.get_service(options['SERVICE'])
  307. detach = options['-d']
  308. if IS_WINDOWS_PLATFORM and not detach:
  309. raise UserError(
  310. "Interactive mode is not yet supported on Windows.\n"
  311. "Please pass the -d flag when using `docker-compose run`."
  312. )
  313. if options['--allow-insecure-ssl']:
  314. log.warn(INSECURE_SSL_WARNING)
  315. if options['COMMAND']:
  316. command = [options['COMMAND']] + options['ARGS']
  317. else:
  318. command = service.options.get('command')
  319. container_options = {
  320. 'command': command,
  321. 'tty': not (detach or options['-T'] or not sys.stdin.isatty()),
  322. 'stdin_open': not detach,
  323. 'detach': detach,
  324. }
  325. if options['-e']:
  326. container_options['environment'] = parse_environment(options['-e'])
  327. if options['--entrypoint']:
  328. container_options['entrypoint'] = options.get('--entrypoint')
  329. if options['--rm']:
  330. container_options['restart'] = None
  331. if options['--user']:
  332. container_options['user'] = options.get('--user')
  333. if not options['--service-ports']:
  334. container_options['ports'] = []
  335. if options['--publish']:
  336. container_options['ports'] = options.get('--publish')
  337. if options['--publish'] and options['--service-ports']:
  338. raise UserError(
  339. 'Service port mapping and manual port mapping '
  340. 'can not be used togather'
  341. )
  342. if options['--name']:
  343. container_options['name'] = options['--name']
  344. run_one_off_container(container_options, project, service, options)
  345. def scale(self, project, options):
  346. """
  347. Set number of containers to run for a service.
  348. Numbers are specified in the form `service=num` as arguments.
  349. For example:
  350. $ docker-compose scale web=2 worker=3
  351. Usage: scale [options] [SERVICE=NUM...]
  352. Options:
  353. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  354. (default: 10)
  355. """
  356. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  357. for s in options['SERVICE=NUM']:
  358. if '=' not in s:
  359. raise UserError('Arguments to scale should be in the form service=num')
  360. service_name, num = s.split('=', 1)
  361. try:
  362. num = int(num)
  363. except ValueError:
  364. raise UserError('Number of containers for service "%s" is not a '
  365. 'number' % service_name)
  366. project.get_service(service_name).scale(num, timeout=timeout)
  367. def start(self, project, options):
  368. """
  369. Start existing containers.
  370. Usage: start [SERVICE...]
  371. """
  372. project.start(service_names=options['SERVICE'])
  373. def stop(self, project, options):
  374. """
  375. Stop running containers without removing them.
  376. They can be started again with `docker-compose start`.
  377. Usage: stop [options] [SERVICE...]
  378. Options:
  379. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  380. (default: 10)
  381. """
  382. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  383. project.stop(service_names=options['SERVICE'], timeout=timeout)
  384. def restart(self, project, options):
  385. """
  386. Restart running containers.
  387. Usage: restart [options] [SERVICE...]
  388. Options:
  389. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  390. (default: 10)
  391. """
  392. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  393. project.restart(service_names=options['SERVICE'], timeout=timeout)
  394. def unpause(self, project, options):
  395. """
  396. Unpause services.
  397. Usage: unpause [SERVICE...]
  398. """
  399. project.unpause(service_names=options['SERVICE'])
  400. def up(self, project, options):
  401. """
  402. Builds, (re)creates, starts, and attaches to containers for a service.
  403. Unless they are already running, this command also starts any linked services.
  404. The `docker-compose up` command aggregates the output of each container. When
  405. the command exits, all containers are stopped. Running `docker-compose up -d`
  406. starts the containers in the background and leaves them running.
  407. If there are existing containers for a service, and the service's configuration
  408. or image was changed after the container's creation, `docker-compose up` picks
  409. up the changes by stopping and recreating the containers (preserving mounted
  410. volumes). To prevent Compose from picking up changes, use the `--no-recreate`
  411. flag.
  412. If you want to force Compose to stop and recreate all containers, use the
  413. `--force-recreate` flag.
  414. Usage: up [options] [SERVICE...]
  415. Options:
  416. --allow-insecure-ssl Deprecated - no effect.
  417. -d Detached mode: Run containers in the background,
  418. print new container names.
  419. --no-color Produce monochrome output.
  420. --no-deps Don't start linked services.
  421. --force-recreate Recreate containers even if their configuration and
  422. image haven't changed. Incompatible with --no-recreate.
  423. --no-recreate If containers already exist, don't recreate them.
  424. Incompatible with --force-recreate.
  425. --no-build Don't build an image, even if it's missing
  426. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  427. when attached or when containers are already
  428. running. (default: 10)
  429. """
  430. if options['--allow-insecure-ssl']:
  431. log.warn(INSECURE_SSL_WARNING)
  432. monochrome = options['--no-color']
  433. start_deps = not options['--no-deps']
  434. service_names = options['SERVICE']
  435. timeout = int(options.get('--timeout') or DEFAULT_TIMEOUT)
  436. detached = options.get('-d')
  437. to_attach = project.up(
  438. service_names=service_names,
  439. start_deps=start_deps,
  440. strategy=convergence_strategy_from_opts(options),
  441. do_build=not options['--no-build'],
  442. timeout=timeout,
  443. detached=detached
  444. )
  445. if not detached:
  446. log_printer = build_log_printer(to_attach, service_names, monochrome)
  447. attach_to_logs(project, log_printer, service_names, timeout)
  448. def migrate_to_labels(self, project, _options):
  449. """
  450. Recreate containers to add labels
  451. If you're coming from Compose 1.2 or earlier, you'll need to remove or
  452. migrate your existing containers after upgrading Compose. This is
  453. because, as of version 1.3, Compose uses Docker labels to keep track
  454. of containers, and so they need to be recreated with labels added.
  455. If Compose detects containers that were created without labels, it
  456. will refuse to run so that you don't end up with two sets of them. If
  457. you want to keep using your existing containers (for example, because
  458. they have data volumes you want to preserve) you can migrate them with
  459. the following command:
  460. docker-compose migrate-to-labels
  461. Alternatively, if you're not worried about keeping them, you can
  462. remove them - Compose will just create new ones.
  463. docker rm -f myapp_web_1 myapp_db_1 ...
  464. Usage: migrate-to-labels
  465. """
  466. legacy.migrate_project_to_labels(project)
  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. try:
  499. container = service.create_container(
  500. quiet=True,
  501. one_off=True,
  502. **container_options)
  503. except APIError:
  504. legacy.check_for_legacy_containers(
  505. project.client,
  506. project.name,
  507. [service.name],
  508. allow_one_off=False)
  509. raise
  510. if options['-d']:
  511. container.start()
  512. print(container.name)
  513. return
  514. def remove_container(force=False):
  515. if options['--rm']:
  516. project.client.remove_container(container.id, force=True)
  517. def force_shutdown(signal, frame):
  518. project.client.kill(container.id)
  519. remove_container(force=True)
  520. sys.exit(2)
  521. def shutdown(signal, frame):
  522. set_signal_handler(force_shutdown)
  523. project.client.stop(container.id)
  524. remove_container()
  525. sys.exit(1)
  526. set_signal_handler(shutdown)
  527. dockerpty.start(project.client, container.id, interactive=not options['-T'])
  528. exit_code = container.wait()
  529. remove_container()
  530. sys.exit(exit_code)
  531. def build_log_printer(containers, service_names, monochrome):
  532. if service_names:
  533. containers = [
  534. container
  535. for container in containers if container.service in service_names
  536. ]
  537. return LogPrinter(containers, monochrome=monochrome)
  538. def attach_to_logs(project, log_printer, service_names, timeout):
  539. def force_shutdown(signal, frame):
  540. project.kill(service_names=service_names)
  541. sys.exit(2)
  542. def shutdown(signal, frame):
  543. set_signal_handler(force_shutdown)
  544. print("Gracefully stopping... (press Ctrl+C again to force)")
  545. project.stop(service_names=service_names, timeout=timeout)
  546. print("Attaching to", list_containers(log_printer.containers))
  547. set_signal_handler(shutdown)
  548. log_printer.run()
  549. def set_signal_handler(handler):
  550. signal.signal(signal.SIGINT, handler)
  551. signal.signal(signal.SIGTERM, handler)
  552. def list_containers(containers):
  553. return ", ".join(c.name for c in containers)