main.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. from __future__ import print_function
  2. from __future__ import unicode_literals
  3. from inspect import getdoc
  4. from operator import attrgetter
  5. import logging
  6. import re
  7. import signal
  8. import sys
  9. from docker.errors import APIError
  10. import dockerpty
  11. from .. import __version__
  12. from .. import legacy
  13. from ..const import DEFAULT_TIMEOUT
  14. from ..project import NoSuchService, ConfigurationError
  15. from ..service import BuildError, NeedsBuildError
  16. from ..config import parse_environment
  17. from .command import Command
  18. from .docopt_command import NoSuchCommand
  19. from .errors import UserError
  20. from .formatter import Formatter
  21. from .log_printer import LogPrinter
  22. from .utils import yesno, get_version_info
  23. log = logging.getLogger(__name__)
  24. def main():
  25. setup_logging()
  26. try:
  27. command = TopLevelCommand()
  28. command.sys_dispatch()
  29. except KeyboardInterrupt:
  30. log.error("\nAborting.")
  31. sys.exit(1)
  32. except (UserError, NoSuchService, ConfigurationError, legacy.LegacyContainersError) as e:
  33. log.error(e.msg)
  34. sys.exit(1)
  35. except NoSuchCommand as e:
  36. log.error("No such command: %s", e.command)
  37. log.error("")
  38. log.error("\n".join(parse_doc_section("commands:", getdoc(e.supercommand))))
  39. sys.exit(1)
  40. except APIError as e:
  41. log.error(e.explanation)
  42. sys.exit(1)
  43. except BuildError as e:
  44. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  45. sys.exit(1)
  46. except NeedsBuildError as e:
  47. log.error("Service '%s' needs to be built, but --no-build was passed." % e.service.name)
  48. sys.exit(1)
  49. def setup_logging():
  50. console_handler = logging.StreamHandler(sys.stderr)
  51. console_handler.setFormatter(logging.Formatter())
  52. console_handler.setLevel(logging.INFO)
  53. root_logger = logging.getLogger()
  54. root_logger.addHandler(console_handler)
  55. root_logger.setLevel(logging.DEBUG)
  56. # Disable requests logging
  57. logging.getLogger("requests").propagate = False
  58. # stolen from docopt master
  59. def parse_doc_section(name, source):
  60. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  61. re.IGNORECASE | re.MULTILINE)
  62. return [s.strip() for s in pattern.findall(source)]
  63. class TopLevelCommand(Command):
  64. """Define and run multi-container applications with Docker.
  65. Usage:
  66. docker-compose [options] [COMMAND] [ARGS...]
  67. docker-compose -h|--help
  68. Options:
  69. -f, --file FILE Specify an alternate compose file (default: docker-compose.yml)
  70. -p, --project-name NAME Specify an alternate project name (default: directory name)
  71. --verbose Show more output
  72. -v, --version Print version and exit
  73. Commands:
  74. build Build or rebuild services
  75. help Get help on a command
  76. kill Kill containers
  77. logs View output from containers
  78. port Print the public port for a port binding
  79. ps List containers
  80. pull Pulls service images
  81. restart Restart services
  82. rm Remove stopped containers
  83. run Run a one-off command
  84. scale Set number of containers for a service
  85. start Start services
  86. stop Stop services
  87. up Create and start containers
  88. migrate-to-labels Recreate containers to add labels
  89. version Show the Docker-Compose version information
  90. """
  91. def docopt_options(self):
  92. options = super(TopLevelCommand, self).docopt_options()
  93. options['version'] = get_version_info('compose')
  94. return options
  95. def build(self, project, options):
  96. """
  97. Build or rebuild services.
  98. Services are built once and then tagged as `project_service`,
  99. e.g. `composetest_db`. If you change a service's `Dockerfile` or the
  100. contents of its build directory, you can run `docker-compose build` to rebuild it.
  101. Usage: build [options] [SERVICE...]
  102. Options:
  103. --no-cache Do not use cache when building the image.
  104. """
  105. no_cache = bool(options.get('--no-cache', False))
  106. project.build(service_names=options['SERVICE'], no_cache=no_cache)
  107. def help(self, project, options):
  108. """
  109. Get help on a command.
  110. Usage: help COMMAND
  111. """
  112. command = options['COMMAND']
  113. if not hasattr(self, command):
  114. raise NoSuchCommand(command, self)
  115. raise SystemExit(getdoc(getattr(self, command)))
  116. def kill(self, project, options):
  117. """
  118. Force stop service containers.
  119. Usage: kill [options] [SERVICE...]
  120. Options:
  121. -s SIGNAL SIGNAL to send to the container.
  122. Default signal is SIGKILL.
  123. """
  124. signal = options.get('-s', 'SIGKILL')
  125. project.kill(service_names=options['SERVICE'], signal=signal)
  126. def logs(self, project, options):
  127. """
  128. View output from containers.
  129. Usage: logs [options] [SERVICE...]
  130. Options:
  131. --no-color Produce monochrome output.
  132. """
  133. containers = project.containers(service_names=options['SERVICE'], stopped=True)
  134. monochrome = options['--no-color']
  135. print("Attaching to", list_containers(containers))
  136. LogPrinter(containers, attach_params={'logs': True}, monochrome=monochrome).run()
  137. def port(self, project, options):
  138. """
  139. Print the public port for a port binding.
  140. Usage: port [options] SERVICE PRIVATE_PORT
  141. Options:
  142. --protocol=proto tcp or udp [default: tcp]
  143. --index=index index of the container if there are multiple
  144. instances of a service [default: 1]
  145. """
  146. index = int(options.get('--index'))
  147. service = project.get_service(options['SERVICE'])
  148. try:
  149. container = service.get_container(number=index)
  150. except ValueError as e:
  151. raise UserError(str(e))
  152. print(container.get_local_port(
  153. options['PRIVATE_PORT'],
  154. protocol=options.get('--protocol') or 'tcp') or '')
  155. def ps(self, project, options):
  156. """
  157. List containers.
  158. Usage: ps [options] [SERVICE...]
  159. Options:
  160. -q Only display IDs
  161. """
  162. containers = sorted(
  163. project.containers(service_names=options['SERVICE'], stopped=True) +
  164. project.containers(service_names=options['SERVICE'], one_off=True),
  165. key=attrgetter('name'))
  166. if options['-q']:
  167. for container in containers:
  168. print(container.id)
  169. else:
  170. headers = [
  171. 'Name',
  172. 'Command',
  173. 'State',
  174. 'Ports',
  175. ]
  176. rows = []
  177. for container in containers:
  178. command = container.human_readable_command
  179. if len(command) > 30:
  180. command = '%s ...' % command[:26]
  181. rows.append([
  182. container.name,
  183. command,
  184. container.human_readable_state,
  185. container.human_readable_ports,
  186. ])
  187. print(Formatter().table(headers, rows))
  188. def pull(self, project, options):
  189. """
  190. Pulls images for services.
  191. Usage: pull [options] [SERVICE...]
  192. Options:
  193. --allow-insecure-ssl Allow insecure connections to the docker
  194. registry
  195. """
  196. insecure_registry = options['--allow-insecure-ssl']
  197. project.pull(
  198. service_names=options['SERVICE'],
  199. insecure_registry=insecure_registry
  200. )
  201. def rm(self, project, options):
  202. """
  203. Remove stopped service containers.
  204. Usage: rm [options] [SERVICE...]
  205. Options:
  206. -f, --force Don't ask to confirm removal
  207. -v Remove volumes associated with containers
  208. """
  209. all_containers = project.containers(service_names=options['SERVICE'], stopped=True)
  210. stopped_containers = [c for c in all_containers if not c.is_running]
  211. if len(stopped_containers) > 0:
  212. print("Going to remove", list_containers(stopped_containers))
  213. if options.get('--force') \
  214. or yesno("Are you sure? [yN] ", default=False):
  215. project.remove_stopped(
  216. service_names=options['SERVICE'],
  217. v=options.get('-v', False)
  218. )
  219. else:
  220. print("No stopped containers")
  221. def run(self, project, options):
  222. """
  223. Run a one-off command on a service.
  224. For example:
  225. $ docker-compose run web python manage.py shell
  226. By default, linked services will be started, unless they are already
  227. running. If you do not want to start linked services, use
  228. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  229. Usage: run [options] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  230. Options:
  231. --allow-insecure-ssl Allow insecure connections to the docker
  232. registry
  233. -d Detached mode: Run container in the background, print
  234. new container name.
  235. --entrypoint CMD Override the entrypoint of the image.
  236. -e KEY=VAL Set an environment variable (can be used multiple times)
  237. -u, --user="" Run as specified username or uid
  238. --no-deps Don't start linked services.
  239. --rm Remove container after run. Ignored in detached mode.
  240. --service-ports Run command with the service's ports enabled and mapped
  241. to the host.
  242. -T Disable pseudo-tty allocation. By default `docker-compose run`
  243. allocates a TTY.
  244. """
  245. service = project.get_service(options['SERVICE'])
  246. insecure_registry = options['--allow-insecure-ssl']
  247. if not options['--no-deps']:
  248. deps = service.get_linked_names()
  249. if len(deps) > 0:
  250. project.up(
  251. service_names=deps,
  252. start_deps=True,
  253. allow_recreate=False,
  254. insecure_registry=insecure_registry,
  255. )
  256. tty = True
  257. if options['-d'] or options['-T'] or not sys.stdin.isatty():
  258. tty = False
  259. if options['COMMAND']:
  260. command = [options['COMMAND']] + options['ARGS']
  261. else:
  262. command = service.options.get('command')
  263. container_options = {
  264. 'command': command,
  265. 'tty': tty,
  266. 'stdin_open': not options['-d'],
  267. 'detach': options['-d'],
  268. }
  269. if options['-e']:
  270. container_options['environment'] = parse_environment(options['-e'])
  271. if options['--entrypoint']:
  272. container_options['entrypoint'] = options.get('--entrypoint')
  273. if options['--rm']:
  274. container_options['restart'] = None
  275. if options['--user']:
  276. container_options['user'] = options.get('--user')
  277. if not options['--service-ports']:
  278. container_options['ports'] = []
  279. container = service.create_container(
  280. quiet=True,
  281. one_off=True,
  282. insecure_registry=insecure_registry,
  283. **container_options
  284. )
  285. if options['-d']:
  286. service.start_container(container)
  287. print(container.name)
  288. else:
  289. dockerpty.start(project.client, container.id, interactive=not options['-T'])
  290. exit_code = container.wait()
  291. if options['--rm']:
  292. project.client.remove_container(container.id)
  293. sys.exit(exit_code)
  294. def scale(self, project, options):
  295. """
  296. Set number of containers to run for a service.
  297. Numbers are specified in the form `service=num` as arguments.
  298. For example:
  299. $ docker-compose scale web=2 worker=3
  300. Usage: scale [SERVICE=NUM...]
  301. """
  302. for s in options['SERVICE=NUM']:
  303. if '=' not in s:
  304. raise UserError('Arguments to scale should be in the form service=num')
  305. service_name, num = s.split('=', 1)
  306. try:
  307. num = int(num)
  308. except ValueError:
  309. raise UserError('Number of containers for service "%s" is not a '
  310. 'number' % service_name)
  311. project.get_service(service_name).scale(num)
  312. def start(self, project, options):
  313. """
  314. Start existing containers.
  315. Usage: start [SERVICE...]
  316. """
  317. project.start(service_names=options['SERVICE'])
  318. def stop(self, project, options):
  319. """
  320. Stop running containers without removing them.
  321. They can be started again with `docker-compose start`.
  322. Usage: stop [options] [SERVICE...]
  323. Options:
  324. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  325. (default: 10)
  326. """
  327. timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT)
  328. project.stop(service_names=options['SERVICE'], timeout=timeout)
  329. def restart(self, project, options):
  330. """
  331. Restart running containers.
  332. Usage: restart [options] [SERVICE...]
  333. Options:
  334. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  335. (default: 10)
  336. """
  337. timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT)
  338. project.restart(service_names=options['SERVICE'], timeout=timeout)
  339. def up(self, project, options):
  340. """
  341. Build, (re)create, start and attach to containers for a service.
  342. By default, `docker-compose up` will aggregate the output of each container, and
  343. when it exits, all containers will be stopped. If you run `docker-compose up -d`,
  344. it'll start the containers in the background and leave them running.
  345. If there are existing containers for a service, `docker-compose up` will stop
  346. and recreate them (preserving mounted volumes with volumes-from),
  347. so that changes in `docker-compose.yml` are picked up. If you do not want existing
  348. containers to be recreated, `docker-compose up --no-recreate` will re-use existing
  349. containers.
  350. Usage: up [options] [SERVICE...]
  351. Options:
  352. --allow-insecure-ssl Allow insecure connections to the docker
  353. registry
  354. -d Detached mode: Run containers in the background,
  355. print new container names.
  356. --no-color Produce monochrome output.
  357. --no-deps Don't start linked services.
  358. --x-smart-recreate Only recreate containers whose configuration or
  359. image needs to be updated. (EXPERIMENTAL)
  360. --no-recreate If containers already exist, don't recreate them.
  361. --no-build Don't build an image, even if it's missing
  362. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  363. when attached or when containers are already
  364. running. (default: 10)
  365. """
  366. insecure_registry = options['--allow-insecure-ssl']
  367. detached = options['-d']
  368. monochrome = options['--no-color']
  369. start_deps = not options['--no-deps']
  370. allow_recreate = not options['--no-recreate']
  371. smart_recreate = options['--x-smart-recreate']
  372. service_names = options['SERVICE']
  373. timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT)
  374. project.up(
  375. service_names=service_names,
  376. start_deps=start_deps,
  377. allow_recreate=allow_recreate,
  378. smart_recreate=smart_recreate,
  379. insecure_registry=insecure_registry,
  380. do_build=not options['--no-build'],
  381. timeout=timeout
  382. )
  383. to_attach = [c for s in project.get_services(service_names) for c in s.containers()]
  384. if not detached:
  385. print("Attaching to", list_containers(to_attach))
  386. log_printer = LogPrinter(to_attach, attach_params={"logs": True}, monochrome=monochrome)
  387. try:
  388. log_printer.run()
  389. finally:
  390. def handler(signal, frame):
  391. project.kill(service_names=service_names)
  392. sys.exit(0)
  393. signal.signal(signal.SIGINT, handler)
  394. print("Gracefully stopping... (press Ctrl+C again to force)")
  395. project.stop(service_names=service_names, timeout=timeout)
  396. def migrate_to_labels(self, project, _options):
  397. """
  398. Recreate containers to add labels
  399. Usage: migrate-to-labels
  400. """
  401. legacy.migrate_project_to_labels(project)
  402. def version(self, project, options):
  403. """
  404. Show version informations
  405. Usage: version [--short]
  406. Options:
  407. --short Shows only Compose's version number.
  408. """
  409. if options['--short']:
  410. print(__version__)
  411. else:
  412. print(get_version_info('full'))
  413. def list_containers(containers):
  414. return ", ".join(c.name for c in containers)