registry.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. Registry for the applications
  19. """
  20. import errno
  21. import glob
  22. import logging
  23. import os
  24. import simplejson
  25. import common
  26. LOG = logging.getLogger(__name__)
  27. class AppRegistry(object):
  28. """
  29. Represents a registry.
  30. """
  31. def __init__(self):
  32. """Open the existing registry"""
  33. self._reg_path = os.path.join(common.INSTALL_ROOT, 'app.reg')
  34. self._initialized = False
  35. self._apps = { } # Map of name -> HueApp
  36. self._open()
  37. def _open(self):
  38. """Open the registry file. May raise OSError"""
  39. if os.path.exists(self._reg_path):
  40. reg_file = file(self._reg_path)
  41. app_list = simplejson.load(reg_file)
  42. reg_file.close()
  43. for app_json in app_list:
  44. app_json.setdefault('author', 'Unknown') # Added after 0.9
  45. app = HueApp.create(app_json)
  46. self._apps[app.name] = app
  47. self._initialized = True
  48. def _write(self, path):
  49. """Write out the registry to the given path"""
  50. outfile = file(path, 'w')
  51. simplejson.dump(self._apps.values(), outfile, cls=AppJsonEncoder, indent=2)
  52. outfile.close()
  53. def contains(self, app):
  54. """Returns whether the app (of the same version) is in the registry"""
  55. try:
  56. existing = self._apps[app.name]
  57. return existing.version == app.version
  58. except KeyError:
  59. return False
  60. def register(self, app):
  61. """register(app) -> True/False"""
  62. assert self._initialized, "Registry not yet initialized"
  63. try:
  64. existing = self._apps[app.name]
  65. version_diff = common.cmp_version(existing.version, app.version)
  66. if version_diff == 0:
  67. LOG.warn('%s is already registered' % (app,))
  68. return False
  69. elif version_diff < 0:
  70. LOG.info('Upgrading %s from version %s' % (app, existing.version))
  71. elif version_diff > 0:
  72. LOG.error('A newer version of %s is already installed' % (app,))
  73. return False
  74. except KeyError:
  75. pass
  76. LOG.info('Updating registry with %s' % (app,))
  77. self._apps[app.name] = app
  78. return True
  79. def unregister(self, app_name):
  80. """unregister(app_Name) -> HueApp. May raise KeyError"""
  81. assert self._initialized, "Registry not yet initialized"
  82. app = self._apps[app_name]
  83. del self._apps[app_name]
  84. return app
  85. def get_all_apps(self):
  86. """get_all_apps() -> List of HueApp"""
  87. return self._apps.values()
  88. def save(self):
  89. """Save and write out the registry"""
  90. assert self._initialized, "Registry not yet initialized"
  91. tmp_path = self._reg_path + '.new'
  92. self._write(tmp_path)
  93. os.rename(tmp_path, self._reg_path)
  94. LOG.info('=== Saved registry at %s' % (self._reg_path,))
  95. class HueApp(object):
  96. """
  97. Represents an app.
  98. """
  99. @staticmethod
  100. def create(json):
  101. return HueApp(json['name'], json['version'], json['path'], json['desc'], json['author'])
  102. def __init__(self, name, version, path, desc, author):
  103. self.name = name
  104. self.version = version
  105. self.path = path
  106. self.desc = desc
  107. self.author = author
  108. def __str__(self):
  109. return "%s (version %s)" % (self.name, self.version)
  110. def __cmp__(self, other):
  111. if not isinstance(other, HueApp):
  112. raise TypeError
  113. return cmp((self.name, self.version), (other.name, other.version))
  114. def jsonable(self):
  115. return dict(name=self.name, version=self.version, path=self.path,
  116. desc=self.desc, author=self.author)
  117. def find_ext_pys(self):
  118. """find_ext_pys() -> A list of paths for all ext-py packages"""
  119. return glob.glob(os.path.join(self.path, 'ext-py', '*'))
  120. def get_conffiles(self):
  121. """get_conffiles() -> A list of config (.ini) files"""
  122. ini_files = glob.glob(os.path.join(self.path, 'conf', '*.ini'))
  123. return [ os.path.abspath(ini) for ini in ini_files ]
  124. def install_conf(self):
  125. """
  126. install_conf() -> True/False
  127. Symlink the app's conf/*.ini files into the conf directory.
  128. """
  129. installed = [ ]
  130. for target in self.get_conffiles():
  131. link_name = os.path.join(common.HUE_CONF_DIR, os.path.basename(target))
  132. try:
  133. os.symlink(target, link_name)
  134. LOG.info('Symlink config %s -> %s' % (link_name, target))
  135. installed.append(link_name)
  136. except OSError, ex:
  137. # Does the link already exists?
  138. if ex.errno == errno.EEXIST and os.path.islink(link_name):
  139. try:
  140. cur = os.readlink(link_name)
  141. if cur == target:
  142. LOG.warn("Symlink for configuration already exists: %s" % (link_name,))
  143. continue
  144. except:
  145. pass
  146. # Nope. True error. Cleanup.
  147. LOG.error("Failed to symlink %s to %s: %s" % (target, link_name, ex))
  148. for lnk in installed:
  149. try:
  150. os.unlink(lnk)
  151. except:
  152. LOG.error("Failed to cleanup link %s" % (link_name,))
  153. return False
  154. return True
  155. def uninstall_conf(self):
  156. """uninstall_conf() -> True/False"""
  157. app_conf_dir = os.path.join(self.path, 'conf')
  158. # Check all symlink in the conf dir and remove any that point to this app
  159. for name in os.listdir(common.HUE_CONF_DIR):
  160. path = os.path.join(common.HUE_CONF_DIR, name)
  161. if not os.path.islink(path):
  162. continue
  163. target = os.readlink(path)
  164. if os.path.samefile(os.path.dirname(target), app_conf_dir):
  165. try:
  166. os.unlink(path)
  167. LOG.info('Remove config symlink %s -> %s' % (path, target))
  168. except OSError, ex:
  169. LOG.error("Failed to remove configuration link %s: %s" % (path, ex))
  170. return False
  171. return True
  172. class AppJsonEncoder(simplejson.JSONEncoder):
  173. def __init__(self, **kwargs):
  174. simplejson.JSONEncoder.__init__(self, **kwargs)
  175. def default(self, obj):
  176. if isinstance(obj, HueApp):
  177. return obj.jsonable()
  178. return simplejson.JSONEncoder.default(self, obj)