main.py 17 KB

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