main.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import logging
  2. import sys
  3. import re
  4. from inspect import getdoc
  5. from .. import __version__
  6. from ..project import NoSuchService
  7. from .command import Command
  8. from .formatter import Formatter
  9. from .log_printer import LogPrinter
  10. from .utils import yesno
  11. from docker.client import APIError
  12. from .errors import UserError
  13. from .docopt_command import NoSuchCommand
  14. from .socketclient import SocketClient
  15. log = logging.getLogger(__name__)
  16. def main():
  17. console_handler = logging.StreamHandler()
  18. console_handler.setFormatter(logging.Formatter())
  19. console_handler.setLevel(logging.INFO)
  20. root_logger = logging.getLogger()
  21. root_logger.addHandler(console_handler)
  22. root_logger.setLevel(logging.DEBUG)
  23. # Disable requests logging
  24. logging.getLogger("requests").propagate = False
  25. try:
  26. command = TopLevelCommand()
  27. command.sys_dispatch()
  28. except KeyboardInterrupt:
  29. log.error("\nAborting.")
  30. exit(1)
  31. except UserError, e:
  32. log.error(e.msg)
  33. exit(1)
  34. except NoSuchService, e:
  35. log.error(e.msg)
  36. exit(1)
  37. except NoSuchCommand, e:
  38. log.error("No such command: %s", e.command)
  39. log.error("")
  40. log.error("\n".join(parse_doc_section("commands:", getdoc(e.supercommand))))
  41. exit(1)
  42. except APIError, e:
  43. log.error(e.explanation)
  44. exit(1)
  45. # stolen from docopt master
  46. def parse_doc_section(name, source):
  47. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  48. re.IGNORECASE | re.MULTILINE)
  49. return [s.strip() for s in pattern.findall(source)]
  50. class TopLevelCommand(Command):
  51. """Punctual, lightweight development environments using Docker.
  52. Usage:
  53. fig [options] [COMMAND] [ARGS...]
  54. fig -h|--help
  55. Options:
  56. --verbose Show more output
  57. --version Print version and exit
  58. Commands:
  59. up Create and start containers
  60. logs View output from containers
  61. ps List containers
  62. run Run a one-off command
  63. start Start services
  64. stop Stop services
  65. kill Kill containers
  66. rm Remove stopped containers
  67. """
  68. def docopt_options(self):
  69. options = super(TopLevelCommand, self).docopt_options()
  70. options['version'] = "fig %s" % __version__
  71. return options
  72. def ps(self, options):
  73. """
  74. List containers.
  75. Usage: ps [options] [SERVICE...]
  76. Options:
  77. -q Only display IDs
  78. """
  79. containers = self.project.containers(service_names=options['SERVICE'], stopped=True) + self.project.containers(service_names=options['SERVICE'], one_off=True)
  80. if options['-q']:
  81. for container in containers:
  82. print container.id
  83. else:
  84. headers = [
  85. 'Name',
  86. 'Command',
  87. 'State',
  88. 'Ports',
  89. ]
  90. rows = []
  91. for container in containers:
  92. rows.append([
  93. container.name,
  94. container.human_readable_command,
  95. container.human_readable_state,
  96. container.human_readable_ports,
  97. ])
  98. print Formatter().table(headers, rows)
  99. def run(self, options):
  100. """
  101. Run a one-off command.
  102. Usage: run [options] SERVICE COMMAND [ARGS...]
  103. Options:
  104. -d Detached mode: Run container in the background, print new container name
  105. """
  106. service = self.project.get_service(options['SERVICE'])
  107. container_options = {
  108. 'command': [options['COMMAND']] + options['ARGS'],
  109. 'tty': not options['-d'],
  110. 'stdin_open': not options['-d'],
  111. }
  112. container = service.create_container(one_off=True, **container_options)
  113. if options['-d']:
  114. service.start_container(container, ports=None)
  115. print container.name
  116. else:
  117. with self._attach_to_container(
  118. container.id,
  119. interactive=True,
  120. logs=True,
  121. raw=True
  122. ) as c:
  123. service.start_container(container, ports=None)
  124. c.run()
  125. def up(self, options):
  126. """
  127. Create and start containers.
  128. Usage: up [options] [SERVICE...]
  129. Options:
  130. -d Detached mode: Run containers in the background, print new container names
  131. """
  132. detached = options['-d']
  133. self.project.create_containers(service_names=options['SERVICE'])
  134. containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  135. if not detached:
  136. print "Attaching to", list_containers(containers)
  137. log_printer = LogPrinter(containers)
  138. self.project.start(service_names=options['SERVICE'])
  139. if not detached:
  140. try:
  141. log_printer.run()
  142. finally:
  143. self.project.kill(service_names=options['SERVICE'])
  144. def start(self, options):
  145. """
  146. Start existing containers.
  147. Usage: start [SERVICE...]
  148. """
  149. self.project.start(service_names=options['SERVICE'])
  150. def stop(self, options):
  151. """
  152. Stop running containers.
  153. Usage: stop [SERVICE...]
  154. """
  155. self.project.stop(service_names=options['SERVICE'])
  156. def kill(self, options):
  157. """
  158. Kill containers.
  159. Usage: kill [SERVICE...]
  160. """
  161. self.project.kill(service_names=options['SERVICE'])
  162. def rm(self, options):
  163. """
  164. Remove stopped containers
  165. Usage: rm [SERVICE...]
  166. """
  167. all_containers = self.project.containers(service_names=options['SERVICE'], stopped=True)
  168. stopped_containers = [c for c in all_containers if not c.is_running]
  169. if len(stopped_containers) > 0:
  170. print "Going to remove", list_containers(stopped_containers)
  171. if yesno("Are you sure? [yN] ", default=False):
  172. self.project.remove_stopped(service_names=options['SERVICE'])
  173. else:
  174. print "No stopped containers"
  175. def logs(self, options):
  176. """
  177. View output from containers.
  178. Usage: logs [SERVICE...]
  179. """
  180. containers = self.project.containers(service_names=options['SERVICE'], stopped=False)
  181. print "Attaching to", list_containers(containers)
  182. LogPrinter(containers, attach_params={'logs': True}).run()
  183. def _attach_to_container(self, container_id, interactive, logs=False, stream=True, raw=False):
  184. stdio = self.client.attach_socket(
  185. container_id,
  186. params={
  187. 'stdin': 1 if interactive else 0,
  188. 'stdout': 1,
  189. 'stderr': 0,
  190. 'logs': 1 if logs else 0,
  191. 'stream': 1 if stream else 0
  192. },
  193. ws=True,
  194. )
  195. stderr = self.client.attach_socket(
  196. container_id,
  197. params={
  198. 'stdin': 0,
  199. 'stdout': 0,
  200. 'stderr': 1,
  201. 'logs': 1 if logs else 0,
  202. 'stream': 1 if stream else 0
  203. },
  204. ws=True,
  205. )
  206. return SocketClient(
  207. socket_in=stdio,
  208. socket_out=stdio,
  209. socket_err=stderr,
  210. raw=raw,
  211. )
  212. def list_containers(containers):
  213. return ", ".join(c.name for c in containers)