loader.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. from configparser 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 = sorted(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()
  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 list(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. required_plugins.sort(); # sort the plugin list to get similar results independant of the os
  104. # upgrade the list of required plugins
  105. required_and_dependant_plugins = []
  106. for name in required_plugins:
  107. for each in list_dependants_recursively(inicontainer, name):
  108. if each not in required_and_dependant_plugins:
  109. required_and_dependant_plugins.append(each)
  110. if name not in required_and_dependant_plugins:
  111. required_and_dependant_plugins.append(name)
  112. # load
  113. for plugin_name in required_and_dependant_plugins:
  114. item = inicontainer.hash[plugin_name]
  115. plugin = __import__(item['package'], globals(), locals(), [str(item['module'])])
  116. module_attr = plugin.__getattribute__(item['module'])
  117. class_attr = module_attr.__getattribute__(item['class'])
  118. item['instance'] = class_attr.__new__(class_attr)
  119. item['instance'].__init__()
  120. item['instance'].set_name(item['package'] + "." + item['module'])
  121. item['instance'].set_version(item['version'])
  122. item['instance']._set_plugin_loader(self)
  123. self.plugins.append(item)
  124. self.hash[plugin_name] = item
  125. optparser = MultiOptionParser(
  126. usage = "Usage: python %prog --help\n" +
  127. " python %prog <action> --help\n" +
  128. " python %prog <action> [options] -- [path 1] ... [path N]\n" +
  129. "\n" +
  130. "Actions: \n " + "\n ".join(sorted(inicontainer.actions)))
  131. if command in ['--help', '--h', '-h']:
  132. optparser.print_help()
  133. exit(0)
  134. if command.strip() == "":
  135. optparser.error("Mandatory action argument required")
  136. if command not in inicontainer.actions:
  137. optparser.error("action {action}: Unknown command".format(action=command))
  138. self.action = command
  139. optparser = MultiOptionParser(
  140. usage="Usage: python %prog --help\n"
  141. " python %prog {command} --help\n"
  142. " python %prog {command} [options] -- [path 1] ... [path N]".format(command=command))
  143. for item in self.iterate_plugins():
  144. if (isinstance(item, mpp.api.IConfigurable)):
  145. item.declare_configuration(optparser)
  146. (options, args) = optparser.parse_args(args)
  147. for item in self.iterate_plugins():
  148. if (isinstance(item, mpp.api.IConfigurable)):
  149. item.configure(options)
  150. for item in self.iterate_plugins():
  151. item.initialize()
  152. return args
  153. def unload(self):
  154. for item in self.iterate_plugins(is_reversed = True):
  155. item.terminate()
  156. def run(self, args):
  157. exit_code = 0
  158. for item in self.iterate_plugins():
  159. if (isinstance(item, mpp.api.IRunable)):
  160. exit_code += item.run(args)
  161. return exit_code
  162. def __repr__(self):
  163. result = object.__repr__(self) + ' with loaded:'
  164. for item in self.iterate_plugins():
  165. result += '\n\t' + item.__repr__()
  166. if isinstance(item, mpp.api.Parent):
  167. result += ' with subscribed:'
  168. for child in item.iterate_children():
  169. result += '\n\t\t' + child.__repr__()
  170. return result