main.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 inspect import getdoc
  8. from .. import __version__
  9. from ..project import NoSuchService, ConfigurationError
  10. from ..service import BuildError, CannotBeScaledError
  11. from .command import Command
  12. from .formatter import Formatter
  13. from .log_printer import LogPrinter
  14. from .utils import yesno
  15. from ..packages.docker.errors import APIError
  16. from .errors import UserError
  17. from .docopt_command import NoSuchCommand
  18. from .socketclient import SocketClient
  19. log = logging.getLogger(__name__)
  20. def main():
  21. console_handler = logging.StreamHandler(stream=sys.stderr)
  22. console_handler.setFormatter(logging.Formatter())
  23. console_handler.setLevel(logging.INFO)
  24. root_logger = logging.getLogger()
  25. root_logger.addHandler(console_handler)
  26. root_logger.setLevel(logging.DEBUG)
  27. # Disable requests logging
  28. logging.getLogger("requests").propagate = False
  29. try:
  30. command = TopLevelCommand()
  31. command.sys_dispatch()
  32. except KeyboardInterrupt:
  33. log.error("\nAborting.")
  34. sys.exit(1)
  35. except (UserError, NoSuchService, ConfigurationError) as e:
  36. log.error(e.msg)
  37. sys.exit(1)
  38. except NoSuchCommand as e:
  39. log.error("No such command: %s", e.command)
  40. log.error("")
  41. log.error("\n".join(parse_doc_section("commands:", getdoc(e.supercommand))))
  42. sys.exit(1)
  43. except APIError as e:
  44. log.error(e.explanation)
  45. sys.exit(1)
  46. except BuildError as e:
  47. log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
  48. sys.exit(1)
  49. # stolen from docopt master
  50. def parse_doc_section(name, source):
  51. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  52. re.IGNORECASE | re.MULTILINE)
  53. return [s.strip() for s in pattern.findall(source)]
  54. class TopLevelCommand(Command):
  55. """Punctual, lightweight development environments using Docker.
  56. Usage:
  57. fig [options] [COMMAND] [ARGS...]
  58. fig -h|--help
  59. Options:
  60. --verbose Show more output
  61. --version Print version and exit
  62. -f, --file FILE Specify an alternate fig file (default: fig.yml)
  63. -p, --project-name NAME Specify an alternate project name (default: directory name)
  64. Commands:
  65. build Build or rebuild services
  66. help Get help on a command
  67. kill Kill containers
  68. logs View output from containers
  69. ps List containers
  70. rm Remove stopped containers
  71. run Run a one-off command
  72. scale Set number of containers for a service
  73. start Start services
  74. stop Stop services
  75. up Create and start containers
  76. """
  77. def docopt_options(self):
  78. options = super(TopLevelCommand, self).docopt_options()
  79. options['version'] = "fig %s" % __version__
  80. return options
  81. def build(self, options):
  82. """
  83. Build or rebuild services.
  84. Services are built once and then tagged as `project_service`,
  85. e.g. `figtest_db`. If you change a service's `Dockerfile` or the
  86. contents of its build directory, you can run `fig build` to rebuild it.
  87. Usage: build [SERVICE...]
  88. """
  89. self.project.build(service_names=options['SERVICE'])
  90. def help(self, options):
  91. """
  92. Get help on a command.
  93. Usage: help COMMAND
  94. """
  95. command = options['COMMAND']
  96. if not hasattr(self, command):
  97. raise NoSuchCommand(command, self)
  98. raise SystemExit(getdoc(getattr(self, command)))
  99. def kill(self, options):
  100. """
  101. Force stop service containers.
  102. Usage: kill [SERVICE...]
  103. """
  104. self.project.kill(service_names=options['SERVICE'])
  105. def logs(self, options):
  106. """
  107. View output from containers.
  108. Usage: logs [SERVICE...]
  109. """
  110. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  111. print("Attaching to", list_containers(containers))
  112. LogPrinter(containers, attach_params={'logs': True}).run()
  113. def ps(self, options):
  114. """
  115. List containers.
  116. Usage: ps [options] [SERVICE...]
  117. Options:
  118. -q Only display IDs
  119. """
  120. containers = self.project.containers(service_names=options['SERVICE'], stopped=True) + self.project.containers(service_names=options['SERVICE'], one_off=True)
  121. if options['-q']:
  122. for container in containers:
  123. print(container.id)
  124. else:
  125. headers = [
  126. 'Name',
  127. 'Command',
  128. 'State',
  129. 'Ports',
  130. ]
  131. rows = []
  132. for container in containers:
  133. command = container.human_readable_command
  134. if len(command) > 30:
  135. command = '%s ...' % command[:26]
  136. rows.append([
  137. container.name,
  138. command,
  139. container.human_readable_state,
  140. container.human_readable_ports,
  141. ])
  142. print(Formatter().table(headers, rows))
  143. def rm(self, options):
  144. """
  145. Remove stopped service containers.
  146. Usage: rm [options] [SERVICE...]
  147. Options:
  148. --force Don't ask to confirm removal
  149. -v Remove volumes associated with containers
  150. """
  151. all_containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  152. stopped_containers = [c for c in all_containers if not c.is_running]
  153. if len(stopped_containers) > 0:
  154. print("Going to remove", list_containers(stopped_containers))
  155. if options.get('--force') \
  156. or yesno("Are you sure? [yN] ", default=False):
  157. self.project.remove_stopped(
  158. service_names=options['SERVICE'],
  159. v=options.get('-v', False)
  160. )
  161. else:
  162. print("No stopped containers")
  163. def run(self, options):
  164. """
  165. Run a one-off command on a service.
  166. For example:
  167. $ fig run web python manage.py shell
  168. By default, linked services will be started, unless they are already
  169. running. If you do not want to start linked services, use
  170. `fig run --no-links SERVICE COMMAND [ARGS...]`.
  171. Usage: run [options] SERVICE COMMAND [ARGS...]
  172. Options:
  173. -d Detached mode: Run container in the background, print
  174. new container name.
  175. -T Disable pseudo-tty allocation. By default `fig run`
  176. allocates a TTY.
  177. --rm Remove container after run. Ignored in detached mode.
  178. --no-links Don't start linked services.
  179. """
  180. service = self.project.get_service(options['SERVICE'])
  181. if not options['--no-links']:
  182. self.project.up(
  183. service_names=service.get_linked_names(),
  184. start_links=True,
  185. recreate=False
  186. )
  187. tty = True
  188. if options['-d'] or options['-T'] or not sys.stdin.isatty():
  189. tty = False
  190. container_options = {
  191. 'command': [options['COMMAND']] + options['ARGS'],
  192. 'tty': tty,
  193. 'stdin_open': not options['-d'],
  194. }
  195. container = service.create_container(one_off=True, **container_options)
  196. if options['-d']:
  197. service.start_container(container, ports=None, one_off=True)
  198. print(container.name)
  199. else:
  200. with self._attach_to_container(container.id, raw=tty) as c:
  201. service.start_container(container, ports=None, one_off=True)
  202. c.run()
  203. exit_code = container.wait()
  204. if options['--rm']:
  205. log.info("Removing %s..." % container.name)
  206. self.client.remove_container(container.id)
  207. sys.exit(exit_code)
  208. def scale(self, options):
  209. """
  210. Set number of containers to run for a service.
  211. Numbers are specified in the form `service=num` as arguments.
  212. For example:
  213. $ fig scale web=2 worker=3
  214. Usage: scale [SERVICE=NUM...]
  215. """
  216. for s in options['SERVICE=NUM']:
  217. if '=' not in s:
  218. raise UserError('Arguments to scale should be in the form service=num')
  219. service_name, num = s.split('=', 1)
  220. try:
  221. num = int(num)
  222. except ValueError:
  223. raise UserError('Number of containers for service "%s" is not a number' % service)
  224. try:
  225. self.project.get_service(service_name).scale(num)
  226. except CannotBeScaledError:
  227. raise UserError('Service "%s" cannot be scaled because it specifies a port on the host. If multiple containers for this service were created, the port would clash.\n\nRemove the ":" from the port definition in fig.yml so Docker can choose a random port for each container.' % service_name)
  228. def start(self, options):
  229. """
  230. Start existing containers.
  231. Usage: start [SERVICE...]
  232. """
  233. self.project.start(service_names=options['SERVICE'])
  234. def stop(self, options):
  235. """
  236. Stop running containers without removing them.
  237. They can be started again with `fig start`.
  238. Usage: stop [SERVICE...]
  239. """
  240. self.project.stop(service_names=options['SERVICE'])
  241. def up(self, options):
  242. """
  243. Build, (re)create, start and attach to containers for a service.
  244. By default, `fig up` will aggregate the output of each container, and
  245. when it exits, all containers will be stopped. If you run `fig up -d`,
  246. it'll start the containers in the background and leave them running.
  247. If there are existing containers for a service, `fig up` will stop
  248. and recreate them (preserving mounted volumes with volumes-from),
  249. so that changes in `fig.yml` are picked up. If you do not want existing
  250. containers to be recreated, `fig up --no-recreate` will re-use existing
  251. containers.
  252. Usage: up [options] [SERVICE...]
  253. Options:
  254. -d Detached mode: Run containers in the background,
  255. print new container names.
  256. --no-links Don't start linked services.
  257. --no-recreate If containers already exist, don't recreate them.
  258. """
  259. detached = options['-d']
  260. start_links = not options['--no-links']
  261. recreate = not options['--no-recreate']
  262. service_names = options['SERVICE']
  263. to_attach = self.project.up(
  264. service_names=service_names,
  265. start_links=start_links,
  266. recreate=recreate
  267. )
  268. if not detached:
  269. print("Attaching to", list_containers(to_attach))
  270. log_printer = LogPrinter(to_attach, attach_params={"logs": True})
  271. try:
  272. log_printer.run()
  273. finally:
  274. def handler(signal, frame):
  275. self.project.kill(service_names=service_names)
  276. sys.exit(0)
  277. signal.signal(signal.SIGINT, handler)
  278. print("Gracefully stopping... (press Ctrl+C again to force)")
  279. self.project.stop(service_names=service_names)
  280. def _attach_to_container(self, container_id, raw=False):
  281. socket_in = self.client.attach_socket(container_id, params={'stdin': 1, 'stream': 1})
  282. socket_out = self.client.attach_socket(container_id, params={'stdout': 1, 'logs': 1, 'stream': 1})
  283. socket_err = self.client.attach_socket(container_id, params={'stderr': 1, 'logs': 1, 'stream': 1})
  284. return SocketClient(
  285. socket_in=socket_in,
  286. socket_out=socket_out,
  287. socket_err=socket_err,
  288. raw=raw,
  289. )
  290. def list_containers(containers):
  291. return ", ".join(c.name for c in containers)