main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 (defaults to tcp)
  143. --index=index index of the container if there are multiple
  144. instances of a service (defaults to 1)
  145. """
  146. service = project.get_service(options['SERVICE'])
  147. try:
  148. container = service.get_container(number=options.get('--index') or 1)
  149. except ValueError as e:
  150. raise UserError(str(e))
  151. print(container.get_local_port(
  152. options['PRIVATE_PORT'],
  153. protocol=options.get('--protocol') or 'tcp') or '')
  154. def ps(self, project, options):
  155. """
  156. List containers.
  157. Usage: ps [options] [SERVICE...]
  158. Options:
  159. -q Only display IDs
  160. """
  161. containers = sorted(
  162. project.containers(service_names=options['SERVICE'], stopped=True) +
  163. project.containers(service_names=options['SERVICE'], one_off=True),
  164. key=attrgetter('name'))
  165. if options['-q']:
  166. for container in containers:
  167. print(container.id)
  168. else:
  169. headers = [
  170. 'Name',
  171. 'Command',
  172. 'State',
  173. 'Ports',
  174. ]
  175. rows = []
  176. for container in containers:
  177. command = container.human_readable_command
  178. if len(command) > 30:
  179. command = '%s ...' % command[:26]
  180. rows.append([
  181. container.name,
  182. command,
  183. container.human_readable_state,
  184. container.human_readable_ports,
  185. ])
  186. print(Formatter().table(headers, rows))
  187. def pull(self, project, options):
  188. """
  189. Pulls images for services.
  190. Usage: pull [options] [SERVICE...]
  191. Options:
  192. --allow-insecure-ssl Allow insecure connections to the docker
  193. registry
  194. """
  195. insecure_registry = options['--allow-insecure-ssl']
  196. project.pull(
  197. service_names=options['SERVICE'],
  198. insecure_registry=insecure_registry
  199. )
  200. def rm(self, project, options):
  201. """
  202. Remove stopped service containers.
  203. Usage: rm [options] [SERVICE...]
  204. Options:
  205. -f, --force Don't ask to confirm removal
  206. -v Remove volumes associated with containers
  207. """
  208. all_containers = project.containers(service_names=options['SERVICE'], stopped=True)
  209. stopped_containers = [c for c in all_containers if not c.is_running]
  210. if len(stopped_containers) > 0:
  211. print("Going to remove", list_containers(stopped_containers))
  212. if options.get('--force') \
  213. or yesno("Are you sure? [yN] ", default=False):
  214. project.remove_stopped(
  215. service_names=options['SERVICE'],
  216. v=options.get('-v', False)
  217. )
  218. else:
  219. print("No stopped containers")
  220. def run(self, project, options):
  221. """
  222. Run a one-off command on a service.
  223. For example:
  224. $ docker-compose run web python manage.py shell
  225. By default, linked services will be started, unless they are already
  226. running. If you do not want to start linked services, use
  227. `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
  228. Usage: run [options] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
  229. Options:
  230. --allow-insecure-ssl Allow insecure connections to the docker
  231. registry
  232. -d Detached mode: Run container in the background, print
  233. new container name.
  234. --entrypoint CMD Override the entrypoint of the image.
  235. -e KEY=VAL Set an environment variable (can be used multiple times)
  236. -u, --user="" Run as specified username or uid
  237. --no-deps Don't start linked services.
  238. --rm Remove container after run. Ignored in detached mode.
  239. --service-ports Run command with the service's ports enabled and mapped
  240. to the host.
  241. -T Disable pseudo-tty allocation. By default `docker-compose run`
  242. allocates a TTY.
  243. """
  244. service = project.get_service(options['SERVICE'])
  245. insecure_registry = options['--allow-insecure-ssl']
  246. if not options['--no-deps']:
  247. deps = service.get_linked_names()
  248. if len(deps) > 0:
  249. project.up(
  250. service_names=deps,
  251. start_deps=True,
  252. allow_recreate=False,
  253. insecure_registry=insecure_registry,
  254. )
  255. tty = True
  256. if options['-d'] or options['-T'] or not sys.stdin.isatty():
  257. tty = False
  258. if options['COMMAND']:
  259. command = [options['COMMAND']] + options['ARGS']
  260. else:
  261. command = service.options.get('command')
  262. container_options = {
  263. 'command': command,
  264. 'tty': tty,
  265. 'stdin_open': not options['-d'],
  266. 'detach': options['-d'],
  267. }
  268. if options['-e']:
  269. container_options['environment'] = parse_environment(options['-e'])
  270. if options['--entrypoint']:
  271. container_options['entrypoint'] = options.get('--entrypoint')
  272. if options['--rm']:
  273. container_options['restart'] = None
  274. if options['--user']:
  275. container_options['user'] = options.get('--user')
  276. if not options['--service-ports']:
  277. container_options['ports'] = []
  278. container = service.create_container(
  279. quiet=True,
  280. one_off=True,
  281. insecure_registry=insecure_registry,
  282. **container_options
  283. )
  284. if options['-d']:
  285. service.start_container(container)
  286. print(container.name)
  287. else:
  288. dockerpty.start(project.client, container.id, interactive=not options['-T'])
  289. exit_code = container.wait()
  290. if options['--rm']:
  291. project.client.remove_container(container.id)
  292. sys.exit(exit_code)
  293. def scale(self, project, options):
  294. """
  295. Set number of containers to run for a service.
  296. Numbers are specified in the form `service=num` as arguments.
  297. For example:
  298. $ docker-compose scale web=2 worker=3
  299. Usage: scale [SERVICE=NUM...]
  300. """
  301. for s in options['SERVICE=NUM']:
  302. if '=' not in s:
  303. raise UserError('Arguments to scale should be in the form service=num')
  304. service_name, num = s.split('=', 1)
  305. try:
  306. num = int(num)
  307. except ValueError:
  308. raise UserError('Number of containers for service "%s" is not a '
  309. 'number' % service_name)
  310. project.get_service(service_name).scale(num)
  311. def start(self, project, options):
  312. """
  313. Start existing containers.
  314. Usage: start [SERVICE...]
  315. """
  316. project.start(service_names=options['SERVICE'])
  317. def stop(self, project, options):
  318. """
  319. Stop running containers without removing them.
  320. They can be started again with `docker-compose start`.
  321. Usage: stop [options] [SERVICE...]
  322. Options:
  323. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  324. (default: 10)
  325. """
  326. timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT)
  327. project.stop(service_names=options['SERVICE'], timeout=timeout)
  328. def restart(self, project, options):
  329. """
  330. Restart running containers.
  331. Usage: restart [options] [SERVICE...]
  332. Options:
  333. -t, --timeout TIMEOUT Specify a shutdown timeout in seconds.
  334. (default: 10)
  335. """
  336. timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT)
  337. project.restart(service_names=options['SERVICE'], timeout=timeout)
  338. def up(self, project, options):
  339. """
  340. Build, (re)create, start and attach to containers for a service.
  341. By default, `docker-compose up` will aggregate the output of each container, and
  342. when it exits, all containers will be stopped. If you run `docker-compose up -d`,
  343. it'll start the containers in the background and leave them running.
  344. If there are existing containers for a service, `docker-compose up` will stop
  345. and recreate them (preserving mounted volumes with volumes-from),
  346. so that changes in `docker-compose.yml` are picked up. If you do not want existing
  347. containers to be recreated, `docker-compose up --no-recreate` will re-use existing
  348. containers.
  349. Usage: up [options] [SERVICE...]
  350. Options:
  351. --allow-insecure-ssl Allow insecure connections to the docker
  352. registry
  353. -d Detached mode: Run containers in the background,
  354. print new container names.
  355. --no-color Produce monochrome output.
  356. --no-deps Don't start linked services.
  357. --x-smart-recreate Only recreate containers whose configuration or
  358. image needs to be updated. (EXPERIMENTAL)
  359. --no-recreate If containers already exist, don't recreate them.
  360. --no-build Don't build an image, even if it's missing
  361. -t, --timeout TIMEOUT Use this timeout in seconds for container shutdown
  362. when attached or when containers are already
  363. running. (default: 10)
  364. """
  365. insecure_registry = options['--allow-insecure-ssl']
  366. detached = options['-d']
  367. monochrome = options['--no-color']
  368. start_deps = not options['--no-deps']
  369. allow_recreate = not options['--no-recreate']
  370. smart_recreate = options['--x-smart-recreate']
  371. service_names = options['SERVICE']
  372. timeout = float(options.get('--timeout') or DEFAULT_TIMEOUT)
  373. project.up(
  374. service_names=service_names,
  375. start_deps=start_deps,
  376. allow_recreate=allow_recreate,
  377. smart_recreate=smart_recreate,
  378. insecure_registry=insecure_registry,
  379. do_build=not options['--no-build'],
  380. timeout=timeout
  381. )
  382. to_attach = [c for s in project.get_services(service_names) for c in s.containers()]
  383. if not detached:
  384. print("Attaching to", list_containers(to_attach))
  385. log_printer = LogPrinter(to_attach, attach_params={"logs": True}, monochrome=monochrome)
  386. try:
  387. log_printer.run()
  388. finally:
  389. def handler(signal, frame):
  390. project.kill(service_names=service_names)
  391. sys.exit(0)
  392. signal.signal(signal.SIGINT, handler)
  393. print("Gracefully stopping... (press Ctrl+C again to force)")
  394. project.stop(service_names=service_names, timeout=timeout)
  395. def migrate_to_labels(self, project, _options):
  396. """
  397. Recreate containers to add labels
  398. Usage: migrate-to-labels
  399. """
  400. legacy.migrate_project_to_labels(project)
  401. def version(self, project, options):
  402. """
  403. Show version informations
  404. Usage: version [--short]
  405. Options:
  406. --short Shows only Compose's version number.
  407. """
  408. if options['--short']:
  409. print(__version__)
  410. else:
  411. print(get_version_info('full'))
  412. def list_containers(containers):
  413. return ", ".join(c.name for c in containers)