main.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. import sys
  8. from inspect import getdoc
  9. from .. import __version__
  10. from ..project import NoSuchService
  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.client 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. exit(1)
  35. except UserError as e:
  36. log.error(e.msg)
  37. exit(1)
  38. except NoSuchService as e:
  39. log.error(e.msg)
  40. exit(1)
  41. except NoSuchCommand as e:
  42. log.error("No such command: %s", e.command)
  43. log.error("")
  44. log.error("\n".join(parse_doc_section("commands:", getdoc(e.supercommand))))
  45. exit(1)
  46. except APIError as e:
  47. log.error(e.explanation)
  48. 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. Commands:
  63. build Build or rebuild services
  64. help Get help on a command
  65. kill Kill containers
  66. logs View output from containers
  67. ps List containers
  68. rm Remove stopped containers
  69. run Run a one-off command
  70. start Start services
  71. stop Stop services
  72. up Create and start containers
  73. """
  74. def docopt_options(self):
  75. options = super(TopLevelCommand, self).docopt_options()
  76. options['version'] = "fig %s" % __version__
  77. return options
  78. def build(self, options):
  79. """
  80. Build or rebuild services.
  81. Services are built once and then tagged as `project_service`,
  82. e.g. `figtest_db`. If you change a service's `Dockerfile` or the
  83. contents of its build directory, you can run `fig build` to rebuild it.
  84. Usage: build [SERVICE...]
  85. """
  86. self.project.build(service_names=options['SERVICE'])
  87. def help(self, options):
  88. """
  89. Get help on a command.
  90. Usage: help COMMAND
  91. """
  92. command = options['COMMAND']
  93. if not hasattr(self, command):
  94. raise NoSuchCommand(command, self)
  95. raise SystemExit(getdoc(getattr(self, command)))
  96. def kill(self, options):
  97. """
  98. Force stop service containers.
  99. Usage: kill [SERVICE...]
  100. """
  101. self.project.kill(service_names=options['SERVICE'])
  102. def logs(self, options):
  103. """
  104. View output from containers.
  105. Usage: logs [SERVICE...]
  106. """
  107. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  108. print("Attaching to", list_containers(containers))
  109. LogPrinter(containers, attach_params={'logs': True}).run()
  110. def ps(self, options):
  111. """
  112. List containers.
  113. Usage: ps [options] [SERVICE...]
  114. Options:
  115. -q Only display IDs
  116. """
  117. containers = self.project.containers(service_names=options['SERVICE'], stopped=True) + self.project.containers(service_names=options['SERVICE'], one_off=True)
  118. if options['-q']:
  119. for container in containers:
  120. print(container.id)
  121. else:
  122. headers = [
  123. 'Name',
  124. 'Command',
  125. 'State',
  126. 'Ports',
  127. ]
  128. rows = []
  129. for container in containers:
  130. command = container.human_readable_command
  131. if len(command) > 30:
  132. command = '%s ...' % command[:26]
  133. rows.append([
  134. container.name,
  135. command,
  136. container.human_readable_state,
  137. container.human_readable_ports,
  138. ])
  139. print(Formatter().table(headers, rows))
  140. def rm(self, options):
  141. """
  142. Remove stopped service containers.
  143. Usage: rm [SERVICE...]
  144. """
  145. all_containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  146. stopped_containers = [c for c in all_containers if not c.is_running]
  147. if len(stopped_containers) > 0:
  148. print("Going to remove", list_containers(stopped_containers))
  149. if yesno("Are you sure? [yN] ", default=False):
  150. self.project.remove_stopped(service_names=options['SERVICE'])
  151. else:
  152. print("No stopped containers")
  153. def run(self, options):
  154. """
  155. Run a one-off command on a service.
  156. For example:
  157. $ fig run web python manage.py shell
  158. Note that this will not start any services that the command's service
  159. links to. So if, for example, your one-off command talks to your
  160. database, you will need to run `fig up -d db` first.
  161. Usage: run [options] SERVICE COMMAND [ARGS...]
  162. Options:
  163. -d Detached mode: Run container in the background, print new container name
  164. """
  165. service = self.project.get_service(options['SERVICE'])
  166. container_options = {
  167. 'command': [options['COMMAND']] + options['ARGS'],
  168. 'tty': not options['-d'],
  169. 'stdin_open': not options['-d'],
  170. }
  171. container = service.create_container(one_off=True, **container_options)
  172. if options['-d']:
  173. service.start_container(container, ports=None)
  174. print(container.name)
  175. else:
  176. with self._attach_to_container(
  177. container.id,
  178. interactive=True,
  179. logs=True,
  180. raw=True
  181. ) as c:
  182. service.start_container(container, ports=None)
  183. c.run()
  184. def start(self, options):
  185. """
  186. Start existing containers.
  187. Usage: start [SERVICE...]
  188. """
  189. self.project.start(service_names=options['SERVICE'])
  190. def stop(self, options):
  191. """
  192. Stop running containers without removing them.
  193. They can be started again with `fig start`.
  194. Usage: stop [SERVICE...]
  195. """
  196. self.project.stop(service_names=options['SERVICE'])
  197. def up(self, options):
  198. """
  199. Build, (re)create, start and attach to containers for a service.
  200. By default, `fig up` will aggregate the output of each container, and
  201. when it exits, all containers will be stopped. If you run `fig up -d`,
  202. it'll start the containers in the background and leave them running.
  203. If there are existing containers for a service, `fig up` will stop
  204. and recreate them (preserving mounted volumes with volumes-from),
  205. so that changes in `fig.yml` are picked up.
  206. Usage: up [options] [SERVICE...]
  207. Options:
  208. -d Detached mode: Run containers in the background, print new
  209. container names
  210. """
  211. detached = options['-d']
  212. (old, new) = self.project.recreate_containers(service_names=options['SERVICE'])
  213. if not detached:
  214. to_attach = [c for (s, c) in new]
  215. print("Attaching to", list_containers(to_attach))
  216. log_printer = LogPrinter(to_attach)
  217. for (service, container) in new:
  218. service.start_container(container)
  219. for (service, container) in old:
  220. container.remove()
  221. if not detached:
  222. try:
  223. log_printer.run()
  224. finally:
  225. def handler(signal, frame):
  226. self.project.kill(service_names=options['SERVICE'])
  227. sys.exit(0)
  228. signal.signal(signal.SIGINT, handler)
  229. print("Gracefully stopping... (press Ctrl+C again to force)")
  230. self.project.stop(service_names=options['SERVICE'])
  231. def _attach_to_container(self, container_id, interactive, logs=False, stream=True, raw=False):
  232. stdio = self.client.attach_socket(
  233. container_id,
  234. params={
  235. 'stdin': 1 if interactive else 0,
  236. 'stdout': 1,
  237. 'stderr': 0,
  238. 'logs': 1 if logs else 0,
  239. 'stream': 1 if stream else 0
  240. },
  241. ws=True,
  242. )
  243. stderr = self.client.attach_socket(
  244. container_id,
  245. params={
  246. 'stdin': 0,
  247. 'stdout': 0,
  248. 'stderr': 1,
  249. 'logs': 1 if logs else 0,
  250. 'stream': 1 if stream else 0
  251. },
  252. ws=True,
  253. )
  254. return SocketClient(
  255. socket_in=stdio,
  256. socket_out=stdio,
  257. socket_err=stderr,
  258. raw=raw,
  259. )
  260. def list_containers(containers):
  261. return ", ".join(c.name for c in containers)