loader.py 8.5 KB

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