loader.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #
  2. # Metrix++, Copyright 2009-2013, Metrix++ Project
  3. # Link: http://metrixplusplus.sourceforge.net
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. # Metrix++ is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 3 of the License.
  10. #
  11. # Metrix++ is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Metrix++. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import mpp.api
  20. import os
  21. import sys
  22. import ConfigParser
  23. import re
  24. import optparse
  25. class MultiOptionParser(optparse.OptionParser):
  26. class MultipleOption(optparse.Option):
  27. ACTIONS = optparse.Option.ACTIONS + ("multiopt",)
  28. STORE_ACTIONS = optparse.Option.STORE_ACTIONS + ("multiopt",)
  29. TYPED_ACTIONS = optparse.Option.TYPED_ACTIONS + ("multiopt",)
  30. ALWAYS_TYPED_ACTIONS = optparse.Option.ALWAYS_TYPED_ACTIONS + ("multiopt",)
  31. def take_action(self, action, dest, opt, value, values, parser):
  32. if action == "multiopt":
  33. values.ensure_value(dest, []).append(value)
  34. else:
  35. optparse.Option.take_action(self, action, dest, opt, value, values, parser)
  36. def __init__(self, *args, **kwargs):
  37. optparse.OptionParser.__init__(self, *args, option_class=self.MultipleOption, **kwargs)
  38. class Loader(object):
  39. def __init__(self):
  40. self.plugins = []
  41. self.hash = {}
  42. self.action = None
  43. def get_action(self):
  44. return self.action
  45. def get_plugin(self, name):
  46. return self.hash[name]['instance']
  47. def iterate_plugins(self, is_reversed = False):
  48. if is_reversed == False:
  49. for item in self.plugins:
  50. yield item['instance']
  51. else:
  52. for item in reversed(self.plugins):
  53. yield item['instance']
  54. def load(self, command, directories, args):
  55. class IniContainer(object):
  56. def __init__(self):
  57. self.plugins = []
  58. self.actions = []
  59. self.hash = {}
  60. def load_recursively(inicontainer, directory):
  61. active_plugins = []
  62. pattern = re.compile(r'.*[.]ini$', flags=re.IGNORECASE)
  63. dirList = os.listdir(directory)
  64. for fname in dirList:
  65. fname = os.path.join(directory, fname)
  66. if os.path.isdir(fname):
  67. active_plugins += load_recursively(inicontainer, fname)
  68. elif re.match(pattern, fname):
  69. config = ConfigParser.ConfigParser()
  70. config.read(fname)
  71. item = {'package': config.get('Plugin', 'package'),
  72. 'module': config.get('Plugin', 'module'),
  73. 'class': config.get('Plugin', 'class'),
  74. 'version': config.get('Plugin', 'version'),
  75. 'depends': config.get('Plugin', 'depends'),
  76. 'actions': config.get('Plugin', 'actions'),
  77. 'enabled': config.getboolean('Plugin', 'enabled'),
  78. 'instance': None}
  79. if item['enabled']:
  80. item['actions'] = item['actions'].split(',')
  81. for (ind, action) in enumerate(item['actions']):
  82. action = action.strip()
  83. item['actions'][ind] = action
  84. if action not in inicontainer.actions + ['*', 'None', 'none', 'False', 'false']:
  85. inicontainer.actions.append(action)
  86. if action == '*' or action == command:
  87. active_plugins.append(item['package'] + '.' + item['module'])
  88. inicontainer.plugins.append(item)
  89. inicontainer.hash[item['package'] + '.' + item['module']] = item
  90. return active_plugins
  91. def list_dependants_recursively(inicontainer, required_plugin_name):
  92. assert required_plugin_name in inicontainer.hash.keys(), \
  93. "depends section requires unknown plugin: " + required_plugin_name
  94. item = inicontainer.hash[required_plugin_name]
  95. if item['depends'] in ('None', 'none', 'False', 'false'):
  96. return []
  97. result = []
  98. for child in item['depends'].split(','):
  99. child = child.strip()
  100. result += list_dependants_recursively(inicontainer, child)
  101. result.append(child)
  102. return result
  103. # configure python path for loading
  104. std_ext_dir = os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], 'ext')
  105. std_ext_priority_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  106. for each in [std_ext_dir] + directories:
  107. sys.path.append(each)
  108. inicontainer = IniContainer()
  109. # load available plugin ini files
  110. required_plugins = []
  111. for each in ([std_ext_priority_dir, std_ext_dir] + directories):
  112. required_plugins += load_recursively(inicontainer, each)
  113. # upgrade the list of required plugins
  114. required_and_dependant_plugins = []
  115. for name in required_plugins:
  116. for each in list_dependants_recursively(inicontainer, name):
  117. if each not in required_and_dependant_plugins:
  118. required_and_dependant_plugins.append(each)
  119. required_and_dependant_plugins.append(name)
  120. # load
  121. for plugin_name in required_and_dependant_plugins:
  122. item = inicontainer.hash[plugin_name]
  123. plugin = __import__(item['package'], globals(), locals(), [item['module']], -1)
  124. module_attr = plugin.__getattribute__(item['module'])
  125. class_attr = module_attr.__getattribute__(item['class'])
  126. item['instance'] = class_attr.__new__(class_attr)
  127. item['instance'].__init__()
  128. item['instance'].set_name(item['package'] + "." + item['module'])
  129. item['instance'].set_version(item['version'])
  130. item['instance'].set_plugin_loader(self)
  131. self.plugins.append(item)
  132. self.hash[plugin_name] = item
  133. optparser = MultiOptionParser(
  134. usage = "Usage: python %prog --help\n" +
  135. " python %prog <action> --help\n" +
  136. " python %prog <action> [options] -- [path 1] ... [path N]\n" +
  137. "\n" +
  138. "Actions: \n " + "\n ".join(inicontainer.actions))
  139. if command in ['--help', '--h', '-h']:
  140. optparser.print_help()
  141. exit(0)
  142. if command.strip() == "":
  143. optparser.error("Mandatory action argument required")
  144. if command not in inicontainer.actions:
  145. optparser.error("Unknown action: {action}".format(action=command))
  146. self.action = command
  147. optparser = MultiOptionParser(
  148. usage="Usage: python %prog --help\n"
  149. " python %prog {command} --help\n"
  150. " python %prog {command} [options] -- [path 1] ... [path N]".format(command=command))
  151. for item in self.iterate_plugins():
  152. if (isinstance(item, mpp.api.IConfigurable)):
  153. item.declare_configuration(optparser)
  154. (options, args) = optparser.parse_args(args)
  155. for item in self.iterate_plugins():
  156. if (isinstance(item, mpp.api.IConfigurable)):
  157. item.configure(options)
  158. for item in self.iterate_plugins():
  159. item.initialize()
  160. return args
  161. def unload(self):
  162. for item in self.iterate_plugins(is_reversed = True):
  163. item.terminate()
  164. def run(self, args):
  165. exit_code = 0
  166. for item in self.iterate_plugins():
  167. if (isinstance(item, mpp.api.IRunable)):
  168. exit_code += item.run(args)
  169. return exit_code
  170. def __repr__(self):
  171. result = object.__repr__(self) + ' with loaded:'
  172. for item in self.iterate_plugins():
  173. result += '\n\t' + item.__repr__()
  174. if isinstance(item, mpp.api.Parent):
  175. result += ' with subscribed:'
  176. for child in item.iterate_children():
  177. result += '\n\t\t' + child.__repr__()
  178. return result