main.py 21 KB

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