main.py 11 KB

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