main.py 21 KB

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