1
0

main.py 16 KB

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