app_reg.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. #!/usr/bin/env python
  2. # Licensed to Cloudera, Inc. under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. Cloudera, Inc. licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """
  18. A tool to manage Hue applications. This does not stop/restart a
  19. running Desktop instance.
  20. Usage:
  21. %(PROG_NAME)s [flags] --install <path_to_app> [<path_to_app> ...]
  22. To register and install new application(s).
  23. %(PROG_NAME)s [flags] --remove <application_name>
  24. To unregister and remove an installed application.
  25. %(PROG_NAME)s [flags] --list
  26. To list all registered applications.
  27. %(PROG_NAME)s [flags] --sync
  28. Synchronize all registered applications with the Desktop environment.
  29. Useful after a `make clean'.
  30. Optional flags:
  31. --debug Turns on debugging output
  32. """
  33. import getopt
  34. import logging
  35. import os
  36. import sys
  37. import subprocess
  38. import build
  39. import common
  40. import pth
  41. import registry
  42. PROG_NAME = sys.argv[0]
  43. LOG = logging.getLogger()
  44. LOG_LEVEL = logging.INFO
  45. LOG_FORMAT = "%(message)s"
  46. DO_INSTALL = 'do_install'
  47. DO_REMOVE = 'do_remove'
  48. DO_LIST = 'do_list'
  49. DO_SYNC = 'do_sync'
  50. def usage(msg=None):
  51. """Print the usage with an optional message. And exit."""
  52. global __doc__
  53. if msg is not None:
  54. print >>sys.stderr, msg
  55. print >>sys.stderr, __doc__ % dict(PROG_NAME=PROG_NAME)
  56. sys.exit(1)
  57. def get_app_info(app_loc):
  58. """
  59. get_app_info(app_loc) -> (app_name, version, description)
  60. Runs the app's setup.py to get the info. May raise ValueError and OSError.
  61. """
  62. if not os.path.isdir(app_loc):
  63. msg = "Not a directory: %s" % (app_loc,)
  64. LOG.error(msg)
  65. raise ValueError(msg)
  66. save_cwd = os.getcwd()
  67. os.chdir(app_loc)
  68. try:
  69. cmdv = [ common.ENV_PYTHON, 'setup.py',
  70. '--name', '--version', '--description',
  71. '--author' ]
  72. LOG.debug("Running '%s'" % (' '.join(cmdv),))
  73. popen = subprocess.Popen(cmdv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  74. res = popen.wait()
  75. stdout, stderr = popen.communicate()
  76. # Cmd failure?
  77. if res != 0:
  78. LOG.error("Error getting application info from %s:\n%s" % (app_loc, stderr))
  79. raise OSError(stderr)
  80. LOG.debug("Command output:\n<<<\n%s\n>>>" % (stdout,))
  81. return stdout.split('\n')[:4]
  82. finally:
  83. os.chdir(save_cwd)
  84. def _do_install_one(reg, app_loc):
  85. """Install one app, without saving. Returns True/False."""
  86. LOG.info("=== Installing app at %s" % (app_loc,))
  87. try:
  88. app_loc = os.path.realpath(app_loc)
  89. app_name, version, desc, author = get_app_info(app_loc)
  90. except (ValueError, OSError), ex:
  91. LOG.error(ex)
  92. return False
  93. app = registry.DesktopApp(app_name, version, app_loc, desc, author)
  94. if reg.contains(app):
  95. LOG.warn("=== %s is already installed" % (app,))
  96. return True
  97. return reg.register(app) and build.make_app(app)
  98. def do_install(app_loc_list):
  99. """Install the apps. Returns True/False."""
  100. reg = registry.AppRegistry()
  101. for app_loc in app_loc_list:
  102. if not _do_install_one(reg, app_loc):
  103. return False
  104. reg.save()
  105. return do_sync(reg)
  106. def do_list():
  107. """List all apps. Returns True/False."""
  108. reg = registry.AppRegistry()
  109. apps = reg.get_all_apps()
  110. LOG.info("%-18s %-7s %-15s %s" % ('Name', 'Version', 'Author', 'Path'))
  111. LOG.info("%s %s %s %s" % ('-' * 18, '-' * 7, '-' * 15, '-' * 35))
  112. for app in sorted(apps):
  113. LOG.info("%-18s %-7s %-15s %s" % (app.name, app.version, app.author, app.path))
  114. return True
  115. def do_remove(app_name):
  116. """Uninstall the given app. Returns True/False."""
  117. # TODO(bc) Does not detect dependency. The app to be uninstalled could be a
  118. # pre-req for other apps, as defined in various setup.py files.
  119. LOG.info("=== Uninstalling %s" % (app_name,))
  120. reg = registry.AppRegistry()
  121. try:
  122. app = reg.unregister(app_name)
  123. except KeyError:
  124. LOG.error("%s is not installed" % (app_name,))
  125. return False
  126. reg.save()
  127. # Update the pth file
  128. try:
  129. pthfile = pth.PthFile()
  130. pthfile.remove(app)
  131. pthfile.save()
  132. return True
  133. except (OSError, SystemError), ex:
  134. LOG.error("Failed to update the .pth file. Please fix any problem and run "
  135. "`%s --sync'\n%s" % (PROG_NAME, ex))
  136. return False
  137. def do_sync(reg=None):
  138. """Sync apps with virtualenv. Returns True/False."""
  139. if not reg:
  140. reg = registry.AppRegistry()
  141. apps = reg.get_all_apps()
  142. try:
  143. pthfile = pth.PthFile()
  144. pthfile.sync(apps)
  145. pthfile.save()
  146. build.make_syncdb()
  147. return True
  148. except (OSError, SystemError), ex:
  149. LOG.error("Failed to update the .pth file. Please fix any problem and run "
  150. "`%s --sync'\n%s" % (PROG_NAME, ex))
  151. return False
  152. def main():
  153. action = None
  154. app = None
  155. # Option parsing
  156. try:
  157. opts, tail = getopt.getopt(sys.argv[1:],
  158. 'ir:lds',
  159. ('install', 'remove=', 'list', 'debug', 'sync'))
  160. except getopt.GetoptError, ex:
  161. usage(str(ex))
  162. def verify_action(current, new_val):
  163. if current is not None:
  164. usage()
  165. return new_val
  166. for opt, arg in opts:
  167. if opt in ('-i', '--install'):
  168. action = verify_action(action, DO_INSTALL)
  169. elif opt in ('-r', '--remove'):
  170. action = verify_action(action, DO_REMOVE)
  171. app = arg
  172. elif opt in ('-l', '--list'):
  173. action = verify_action(action, DO_LIST)
  174. elif opt in ('-s', '--sync'):
  175. action = verify_action(action, DO_SYNC)
  176. elif opt in ('-d', '--debug'):
  177. global LOG_LEVEL
  178. LOG_LEVEL = logging.DEBUG
  179. if action == DO_INSTALL:
  180. app_loc_list = tail
  181. elif len(tail) != 0:
  182. usage("Unknown trailing arguments: %s" % ' '.join(tail))
  183. if action is None:
  184. usage()
  185. # Setup logging
  186. logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT)
  187. # Dispatch
  188. if action == DO_INSTALL:
  189. ok = do_install(app_loc_list)
  190. elif action == DO_REMOVE:
  191. ok = do_remove(app)
  192. elif action == DO_LIST:
  193. ok = do_list()
  194. elif action == DO_SYNC:
  195. ok = do_sync()
  196. if ok:
  197. return 0
  198. return 2
  199. if __name__ == '__main__':
  200. sys.exit(main())