loader.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. if os.path.exists(directory) == False or os.path.isdir(directory) == False:
  63. return active_plugins
  64. pattern = re.compile(r'.*[.]ini$', flags=re.IGNORECASE)
  65. dirList = os.listdir(directory)
  66. for fname in dirList:
  67. fname = os.path.join(directory, fname)
  68. if os.path.isdir(fname):
  69. active_plugins += load_recursively(inicontainer, fname)
  70. elif re.match(pattern, fname):
  71. config = ConfigParser.ConfigParser()
  72. config.read(fname)
  73. item = {'package': config.get('Plugin', 'package'),
  74. 'module': config.get('Plugin', 'module'),
  75. 'class': config.get('Plugin', 'class'),
  76. 'version': config.get('Plugin', 'version'),
  77. 'depends': config.get('Plugin', 'depends'),
  78. 'actions': config.get('Plugin', 'actions'),
  79. 'enabled': config.getboolean('Plugin', 'enabled'),
  80. 'instance': None}
  81. if item['enabled']:
  82. item['actions'] = item['actions'].split(',')
  83. for (ind, action) in enumerate(item['actions']):
  84. action = action.strip()
  85. item['actions'][ind] = action
  86. if action not in inicontainer.actions + ['*', 'None', 'none', 'False', 'false']:
  87. inicontainer.actions.append(action)
  88. if action == '*' or action == command:
  89. active_plugins.append(item['package'] + '.' + item['module'])
  90. inicontainer.plugins.append(item)
  91. inicontainer.hash[item['package'] + '.' + item['module']] = item
  92. return active_plugins
  93. def list_dependants_recursively(inicontainer, required_plugin_name):
  94. assert required_plugin_name in inicontainer.hash.keys(), \
  95. "depends section requires unknown plugin: " + required_plugin_name
  96. item = inicontainer.hash[required_plugin_name]
  97. if item['depends'] in ('None', 'none', 'False', 'false'):
  98. return []
  99. result = []
  100. for child in item['depends'].split(','):
  101. child = child.strip()
  102. result += list_dependants_recursively(inicontainer, child)
  103. result.append(child)
  104. return result
  105. # configure python path for loading
  106. std_ext_dir = os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], 'ext')
  107. std_ext_priority_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  108. for each in [std_ext_dir] + directories:
  109. sys.path.append(each)
  110. inicontainer = IniContainer()
  111. # load available plugin ini files
  112. required_plugins = []
  113. for each in ([std_ext_priority_dir, std_ext_dir] + directories):
  114. required_plugins += load_recursively(inicontainer, each)
  115. # upgrade the list of required plugins
  116. required_and_dependant_plugins = []
  117. for name in required_plugins:
  118. for each in list_dependants_recursively(inicontainer, name):
  119. if each not in required_and_dependant_plugins:
  120. required_and_dependant_plugins.append(each)
  121. required_and_dependant_plugins.append(name)
  122. # load
  123. for plugin_name in required_and_dependant_plugins:
  124. item = inicontainer.hash[plugin_name]
  125. plugin = __import__(item['package'], globals(), locals(), [item['module']], -1)
  126. module_attr = plugin.__getattribute__(item['module'])
  127. class_attr = module_attr.__getattribute__(item['class'])
  128. item['instance'] = class_attr.__new__(class_attr)
  129. item['instance'].__init__()
  130. item['instance'].set_name(item['package'] + "." + item['module'])
  131. item['instance'].set_version(item['version'])
  132. item['instance']._set_plugin_loader(self)
  133. self.plugins.append(item)
  134. self.hash[plugin_name] = item
  135. optparser = MultiOptionParser(
  136. usage = "Usage: python %prog --help\n" +
  137. " python %prog <action> --help\n" +
  138. " python %prog <action> [options] -- [path 1] ... [path N]\n" +
  139. "\n" +
  140. "Actions: \n " + "\n ".join(inicontainer.actions))
  141. if command in ['--help', '--h', '-h']:
  142. optparser.print_help()
  143. exit(0)
  144. if command.strip() == "":
  145. optparser.error("Mandatory action argument required")
  146. if command not in inicontainer.actions:
  147. optparser.error("action {action}: Unknown command".format(action=command))
  148. self.action = command
  149. optparser = MultiOptionParser(
  150. usage="Usage: python %prog --help\n"
  151. " python %prog {command} --help\n"
  152. " python %prog {command} [options] -- [path 1] ... [path N]".format(command=command))
  153. for item in self.iterate_plugins():
  154. if (isinstance(item, mpp.api.IConfigurable)):
  155. item.declare_configuration(optparser)
  156. (options, args) = optparser.parse_args(args)
  157. for item in self.iterate_plugins():
  158. if (isinstance(item, mpp.api.IConfigurable)):
  159. item.configure(options)
  160. for item in self.iterate_plugins():
  161. item.initialize()
  162. return args
  163. def unload(self):
  164. for item in self.iterate_plugins(is_reversed = True):
  165. item.terminate()
  166. def run(self, args):
  167. exit_code = 0
  168. for item in self.iterate_plugins():
  169. if (isinstance(item, mpp.api.IRunable)):
  170. exit_code += item.run(args)
  171. return exit_code
  172. def __repr__(self):
  173. result = object.__repr__(self) + ' with loaded:'
  174. for item in self.iterate_plugins():
  175. result += '\n\t' + item.__repr__()
  176. if isinstance(item, mpp.api.Parent):
  177. result += ' with subscribed:'
  178. for child in item.iterate_children():
  179. result += '\n\t\t' + child.__repr__()
  180. return result