main.py 16 KB

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