main.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import datetime
  2. import logging
  3. import sys
  4. import os
  5. import re
  6. from docopt import docopt
  7. from inspect import getdoc
  8. from .. import __version__
  9. from ..service_collection import ServiceCollection
  10. from .command import Command
  11. from .formatter import Formatter
  12. from .log_printer import LogPrinter
  13. from docker.client import APIError
  14. from .errors import UserError
  15. from .docopt_command import NoSuchCommand
  16. log = logging.getLogger(__name__)
  17. def main():
  18. console_handler = logging.StreamHandler()
  19. console_handler.setFormatter(logging.Formatter())
  20. console_handler.setLevel(logging.INFO)
  21. root_logger = logging.getLogger()
  22. root_logger.addHandler(console_handler)
  23. root_logger.setLevel(logging.DEBUG)
  24. # Disable requests logging
  25. logging.getLogger("requests").propagate = False
  26. try:
  27. command = TopLevelCommand()
  28. command.sys_dispatch()
  29. except KeyboardInterrupt:
  30. log.error("\nAborting.")
  31. exit(1)
  32. except UserError, e:
  33. log.error(e.msg)
  34. exit(1)
  35. except NoSuchCommand, e:
  36. log.error("No such command: %s", e.command)
  37. log.error("")
  38. log.error("\n".join(parse_doc_section("commands:", getdoc(e.supercommand))))
  39. exit(1)
  40. except APIError, e:
  41. log.error(e.explanation)
  42. exit(1)
  43. # stolen from docopt master
  44. def parse_doc_section(name, source):
  45. pattern = re.compile('^([^\n]*' + name + '[^\n]*\n?(?:[ \t].*?(?:\n|$))*)',
  46. re.IGNORECASE | re.MULTILINE)
  47. return [s.strip() for s in pattern.findall(source)]
  48. class TopLevelCommand(Command):
  49. """.
  50. Usage:
  51. plum [options] [COMMAND] [ARGS...]
  52. plum -h|--help
  53. Options:
  54. --verbose Show more output
  55. --version Print version and exit
  56. Commands:
  57. ps List services and containers
  58. run Run a one-off command
  59. start Start services
  60. stop Stop services
  61. """
  62. def ps(self, options):
  63. """
  64. List services and containers.
  65. Usage: ps [options]
  66. Options:
  67. -q Only display IDs
  68. """
  69. if options['-q']:
  70. for container in self.service_collection.containers(all=True):
  71. print container.id
  72. else:
  73. headers = [
  74. 'Name',
  75. 'Command',
  76. 'State',
  77. 'Ports',
  78. ]
  79. rows = []
  80. for container in self.service_collection.containers(all=True):
  81. rows.append([
  82. container.name,
  83. container.human_readable_command,
  84. container.human_readable_state,
  85. container.human_readable_ports,
  86. ])
  87. print Formatter().table(headers, rows)
  88. def run(self, options):
  89. """
  90. Run a one-off command.
  91. Usage: run SERVICE COMMAND [ARGS...]
  92. """
  93. service = self.service_collection.get(options['SERVICE'])
  94. if service is None:
  95. raise UserError("No such service: %s" % options['SERVICE'])
  96. container_options = {
  97. 'command': [options['COMMAND']] + options['ARGS'],
  98. }
  99. container = service.create_container(**container_options)
  100. stream = container.logs(stream=True)
  101. service.start_container(container, ports=None)
  102. for data in stream:
  103. if data is None:
  104. break
  105. print data
  106. def start(self, options):
  107. """
  108. Start all services
  109. Usage: start [-d]
  110. """
  111. if options['-d']:
  112. self.service_collection.start()
  113. return
  114. running = []
  115. unstarted = []
  116. for s in self.service_collection:
  117. if len(s.containers()) == 0:
  118. unstarted.append((s, s.create_container()))
  119. else:
  120. running += s.containers(all=False)
  121. log_printer = LogPrinter(running + [c for (s, c) in unstarted])
  122. for (s, c) in unstarted:
  123. s.start_container(c)
  124. try:
  125. log_printer.run()
  126. finally:
  127. self.service_collection.stop()
  128. def stop(self, options):
  129. """
  130. Stop all services
  131. Usage: stop
  132. """
  133. self.service_collection.stop()
  134. def logs(self, options):
  135. """
  136. View containers' output
  137. Usage: logs
  138. """
  139. containers = self.service_collection.containers(all=False)
  140. print "Attaching to", list_containers(containers)
  141. LogPrinter(containers, attach_params={'logs': True}).run()
  142. def list_containers(containers):
  143. return ", ".join(c.name for c in containers)