main.py 21 KB

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