main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. from __future__ import print_function
  2. from __future__ import unicode_literals
  3. import logging
  4. import sys
  5. import re
  6. import signal
  7. from operator import attrgetter
  8. from inspect import getdoc
  9. import dockerpty
  10. from .. import __version__
  11. from ..project import NoSuchService, ConfigurationError
  12. from ..service import BuildError, CannotBeScaledError
  13. from .command import Command
  14. from .formatter import Formatter
  15. from .log_printer import LogPrinter
  16. from .utils import yesno
  17. from docker.errors import APIError
  18. from .errors import UserError
  19. from .docopt_command import NoSuchCommand
  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. fig [options] [COMMAND] [ARGS...]
  61. fig -h|--help
  62. Options:
  63. --verbose Show more output
  64. --version Print version and exit
  65. -f, --file FILE Specify an alternate fig file (default: fig.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'] = "fig %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. `figtest_db`. If you change a service's `Dockerfile` or the
  92. contents of its build directory, you can run `fig 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. --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. $ fig 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. `fig 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. --no-deps Don't start linked services.
  229. --rm Remove container after run. Ignored in detached mode.
  230. --service-ports Run command with the service's ports enabled and mapped
  231. to the host.
  232. -T Disable pseudo-tty allocation. By default `fig run`
  233. allocates a TTY.
  234. """
  235. service = project.get_service(options['SERVICE'])
  236. insecure_registry = options['--allow-insecure-ssl']
  237. if not options['--no-deps']:
  238. deps = service.get_linked_names()
  239. if len(deps) > 0:
  240. project.up(
  241. service_names=deps,
  242. start_links=True,
  243. recreate=False,
  244. insecure_registry=insecure_registry,
  245. detach=options['-d']
  246. )
  247. tty = True
  248. if options['-d'] or options['-T'] or not sys.stdin.isatty():
  249. tty = False
  250. if options['COMMAND']:
  251. command = [options['COMMAND']] + options['ARGS']
  252. else:
  253. command = service.options.get('command')
  254. container_options = {
  255. 'command': command,
  256. 'tty': tty,
  257. 'stdin_open': not options['-d'],
  258. 'detach': options['-d'],
  259. }
  260. if options['-e']:
  261. for option in options['-e']:
  262. if 'environment' not in service.options:
  263. service.options['environment'] = {}
  264. k, v = option.split('=', 1)
  265. service.options['environment'][k] = v
  266. if options['--entrypoint']:
  267. container_options['entrypoint'] = options.get('--entrypoint')
  268. container = service.create_container(
  269. one_off=True,
  270. insecure_registry=insecure_registry,
  271. **container_options
  272. )
  273. service_ports = None
  274. if options['--service-ports']:
  275. service_ports = service.options['ports']
  276. if options['-d']:
  277. service.start_container(container, ports=service_ports, one_off=True)
  278. print(container.name)
  279. else:
  280. service.start_container(container, ports=service_ports, one_off=True)
  281. dockerpty.start(project.client, container.id, interactive=not options['-T'])
  282. exit_code = container.wait()
  283. if options['--rm']:
  284. log.info("Removing %s..." % container.name)
  285. project.client.remove_container(container.id)
  286. sys.exit(exit_code)
  287. def scale(self, project, options):
  288. """
  289. Set number of containers to run for a service.
  290. Numbers are specified in the form `service=num` as arguments.
  291. For example:
  292. $ fig scale web=2 worker=3
  293. Usage: scale [SERVICE=NUM...]
  294. """
  295. for s in options['SERVICE=NUM']:
  296. if '=' not in s:
  297. raise UserError('Arguments to scale should be in the form service=num')
  298. service_name, num = s.split('=', 1)
  299. try:
  300. num = int(num)
  301. except ValueError:
  302. raise UserError('Number of containers for service "%s" is not a '
  303. 'number' % service_name)
  304. try:
  305. project.get_service(service_name).scale(num)
  306. except CannotBeScaledError:
  307. raise UserError(
  308. 'Service "%s" cannot be scaled because it specifies a port '
  309. 'on the host. If multiple containers for this service were '
  310. 'created, the port would clash.\n\nRemove the ":" from the '
  311. 'port definition in fig.yml so Docker can choose a random '
  312. 'port for each container.' % service_name)
  313. def start(self, project, options):
  314. """
  315. Start existing containers.
  316. Usage: start [SERVICE...]
  317. """
  318. project.start(service_names=options['SERVICE'])
  319. def stop(self, project, options):
  320. """
  321. Stop running containers without removing them.
  322. They can be started again with `fig start`.
  323. Usage: stop [SERVICE...]
  324. """
  325. project.stop(service_names=options['SERVICE'])
  326. def restart(self, project, options):
  327. """
  328. Restart running containers.
  329. Usage: restart [SERVICE...]
  330. """
  331. project.restart(service_names=options['SERVICE'])
  332. def up(self, project, options):
  333. """
  334. Build, (re)create, start and attach to containers for a service.
  335. By default, `fig up` will aggregate the output of each container, and
  336. when it exits, all containers will be stopped. If you run `fig up -d`,
  337. it'll start the containers in the background and leave them running.
  338. If there are existing containers for a service, `fig up` will stop
  339. and recreate them (preserving mounted volumes with volumes-from),
  340. so that changes in `fig.yml` are picked up. If you do not want existing
  341. containers to be recreated, `fig up --no-recreate` will re-use existing
  342. containers.
  343. Usage: up [options] [SERVICE...]
  344. Options:
  345. --allow-insecure-ssl Allow insecure connections to the docker
  346. registry
  347. -d Detached mode: Run containers in the background,
  348. print new container names.
  349. --no-color Produce monochrome output.
  350. --no-deps Don't start linked services.
  351. --no-recreate If containers already exist, don't recreate them.
  352. """
  353. insecure_registry = options['--allow-insecure-ssl']
  354. detached = options['-d']
  355. monochrome = options['--no-color']
  356. start_links = not options['--no-deps']
  357. recreate = not options['--no-recreate']
  358. service_names = options['SERVICE']
  359. project.up(
  360. service_names=service_names,
  361. start_links=start_links,
  362. recreate=recreate,
  363. insecure_registry=insecure_registry,
  364. detach=options['-d']
  365. )
  366. to_attach = [c for s in project.get_services(service_names) for c in s.containers()]
  367. if not detached:
  368. print("Attaching to", list_containers(to_attach))
  369. log_printer = LogPrinter(to_attach, attach_params={"logs": True}, monochrome=monochrome)
  370. try:
  371. log_printer.run()
  372. finally:
  373. def handler(signal, frame):
  374. project.kill(service_names=service_names)
  375. sys.exit(0)
  376. signal.signal(signal.SIGINT, handler)
  377. print("Gracefully stopping... (press Ctrl+C again to force)")
  378. project.stop(service_names=service_names)
  379. def list_containers(containers):
  380. return ", ".join(c.name for c in containers)