No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

plugins.py 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. #-*- coding: utf-8 -*-
  2. import sys
  3. import os.path
  4. import importlib
  5. import copy
  6. import json
  7. from importlib.machinery import SourceFileLoader, SourcelessFileLoader
  8. import plugins
  9. from lodel import logger
  10. from lodel.settings.utils import SettingsError
  11. from .exceptions import *
  12. from lodel.exceptions import *
  13. ## @package lodel.plugins Lodel2 plugins management
  14. #
  15. # Lodel2 plugins are stored in directories
  16. # A typicall lodel2 plugin directory structure looks like :
  17. # - {{__init__.py}}} containing informations like full_name, authors, licence etc.
  18. # - main.py containing hooks registration etc
  19. # - confspec.py containing a configuration specification dictionary named CONFSPEC
  20. ##@brief The package in which we will load plugins modules
  21. VIRTUAL_PACKAGE_NAME = 'lodel.plugins'
  22. ##@brief The temporary package to import python sources
  23. VIRTUAL_TEMP_PACKAGE_NAME = 'lodel.plugin_tmp'
  24. ##@brief Plugin init filename
  25. INIT_FILENAME = '__init__.py' # Loaded with settings
  26. PLUGIN_NAME_VARNAME = '__plugin_name__'
  27. PLUGIN_TYPE_VARNAME = '__plugin_type__'
  28. PLUGIN_VERSION_VARNAME = '__version__'
  29. CONFSPEC_FILENAME_VARNAME = '__confspec__'
  30. CONFSPEC_VARNAME = 'CONFSPEC'
  31. LOADER_FILENAME_VARNAME = '__loader__'
  32. PLUGIN_DEPS_VARNAME = '__plugin_deps__'
  33. ACTIVATE_METHOD_NAME = '_activate'
  34. ##@brief Discover stage cache filename
  35. DISCOVER_CACHE_FILENAME = '.plugin_discover_cache.json'
  36. ##@brief Default & failover value for plugins path list
  37. DEFAULT_PLUGINS_PATH_LIST = ['./plugins']
  38. MANDATORY_VARNAMES = [PLUGIN_NAME_VARNAME, LOADER_FILENAME_VARNAME,
  39. PLUGIN_VERSION_VARNAME]
  40. DEFAULT_PLUGIN_TYPE = 'extension' #Value found in lodel/plugin/extensions.py::Extensions._type_conf_name
  41. ##@brief Describe and handle version numbers
  42. class PluginVersion(object):
  43. PROPERTY_LIST = ['major', 'minor', 'revision' ]
  44. ##@brief Version constructor
  45. #@param *args : You can either give a str that will be splitted on . or you
  46. #can give a iterable containing 3 integer or 3 arguments representing
  47. #major, minor and revision version
  48. def __init__(self, *args):
  49. self.__version = [0 for _ in range(3) ]
  50. if len(args) == 1:
  51. arg = args[0]
  52. if isinstance(arg, str):
  53. spl = arg.split('.')
  54. invalid = False
  55. if len(spl) > 3:
  56. raise PluginError("The string '%s' is not a valid plugin \
  57. version number" % arg)
  58. else:
  59. try:
  60. if len(arg) >= 1:
  61. if len(arg) > 3:
  62. raise PluginError("Expected maximum 3 value to \
  63. create a plugin version number but found '%s' as argument" % arg)
  64. for i, v in enumerate(arg):
  65. self.__version[i] = arg[i]
  66. except TypeError:
  67. raise PluginError("Unable to convert argument into plugin \
  68. version number" % arg)
  69. elif len(args) > 3:
  70. raise PluginError("Expected between 1 and 3 positional arguments \
  71. but %d arguments found" % len(args))
  72. else:
  73. for i,v in enumerate(args):
  74. self.__version[i] = v
  75. @property
  76. def major(self):
  77. return self.__version[0]
  78. @property
  79. def minor(self):
  80. return self.__version[1]
  81. @property
  82. def revision(self):
  83. return self.__version[2]
  84. ##@brief Check and prepare comparisoon argument
  85. #@return A PluginVersion instance
  86. #@throw PluginError if invalid argument provided
  87. def __cmp_check(self, other):
  88. if not isinstance(other, PluginVersion):
  89. try:
  90. if len(other) <= 3 and len(other) > 0:
  91. return PluginVersion(other)
  92. except TypeError:
  93. raise PluginError("Cannot compare argument '%s' with \
  94. a PluginVerison instance" % other)
  95. return other
  96. ##@brief Generic comparison function
  97. #@param other PluginVersion or iterable
  98. #@param cmp_fun_name function : interger comparison function
  99. def __generic_cmp(self, other, cmp_fun_name):
  100. other = self.__cmp_check(other)
  101. try:
  102. cmpfun = getattr(int, cmp_fun_name)
  103. except AttributeError:
  104. raise LodelFatalError("Invalid comparison callback given \
  105. to generic PluginVersion comparison function : '%s'" % cmp_fun_name)
  106. for property_name in self.PROPERTY_LIST:
  107. if not cmpfun(getattr(self, pname), getattr(other, pname)):
  108. return False
  109. return True
  110. def __lt__(self, other):
  111. return self.__generic_cmp(other, '__lt__')
  112. def __le__(self, other):
  113. return self.__generic_cmp(other, '__le__')
  114. def __eq__(self, other):
  115. return self.__generic_cmp(other, '__eq__')
  116. def __ne__(self, other):
  117. return self.__generic_cmp(other, '__ne__')
  118. def __gt__(self, other):
  119. return self.__generic_cmp(other, '__gt__')
  120. def __ge__(self, other):
  121. return self.__generic_cmp(other, '__ge__')
  122. def __str__(self):
  123. return '%d.%d.%d' % tuple(self.__version)
  124. def __repr__(self):
  125. return {'major': self.major, 'minor': self.minor,
  126. 'revision': self.revision}
  127. ##@brief Plugin metaclass that allows to "catch" child class
  128. #declaration
  129. #
  130. #Automatic script registration on child class declaration
  131. class MetaPlugType(type):
  132. ##@brief Dict storing all plugin types
  133. #
  134. #key is the _type_conf_name and value is the class
  135. _all_ptypes = dict()
  136. def __init__(self, name, bases, attrs):
  137. #Here we can store all child classes of Plugin
  138. super().__init__(name, bases, attrs)
  139. if len(bases) == 1 and bases[0] == object:
  140. return
  141. #Regitering a new plugin type
  142. MetaPlugType._all_ptypes[self._type_conf_name] = self
  143. @classmethod
  144. def all_types(cls):
  145. return copy.copy(cls._all_ptypes)
  146. @classmethod
  147. def all_ptype_names(cls):
  148. return list(cls._all_ptypes.keys())
  149. @classmethod
  150. def type_from_name(cls, ptype_name):
  151. if ptype_name not in cls._all_ptypes:
  152. raise PluginError("Unknown plugin type '%s'" % ptype_name)
  153. return cls._all_ptypes[ptype_name]
  154. ##@brief Handle plugins
  155. #
  156. # An instance represent a loaded plugin. Class methods allow to load/preload
  157. # plugins.
  158. #
  159. # Typicall Plugins load sequence is :
  160. # 1. Settings call start method to instanciate all plugins found in confs
  161. # 2. Settings fetch all confspecs
  162. # 3. the loader call load_all to register hooks etc
  163. class Plugin(object, metaclass=MetaPlugType):
  164. ##@brief Stores plugin directories paths
  165. _plugin_directories = None
  166. ##@brief Stores Plugin instances indexed by name
  167. _plugin_instances = dict()
  168. ##@brief Attribute used by load_all and load methods to detect circular
  169. #dependencies
  170. _load_called = []
  171. ##@brief Attribute that stores plugins list from discover cache file
  172. _plugin_list = None
  173. ##@brief Store dict representation of discover cache content
  174. _discover_cache = None
  175. #@brief Designed to store, in child classes, the confspec indicating \
  176. #where plugin list is stored
  177. _plist_confspecs = None
  178. ##@brief The name of the plugin type in the confguration
  179. #
  180. #None in abstract classes and implemented by child classes
  181. _type_conf_name = None
  182. ##@brief Plugin class constructor
  183. #
  184. # Called by setting in early stage of lodel2 boot sequence using classmethod
  185. # register
  186. #
  187. # @param plugin_name str : plugin name
  188. # @throw PluginError
  189. def __init__(self, plugin_name):
  190. self.name = plugin_name
  191. self.path = self.plugin_path(plugin_name)
  192. ##@brief Stores the plugin module
  193. self.module = None
  194. ##@breif Stores the plugin loader module
  195. self.__loader_module = None
  196. self.__confspecs = dict()
  197. self.loaded = False
  198. # Importing __init__.py infos in it
  199. plugin_module = '%s.%s' % (VIRTUAL_PACKAGE_NAME,
  200. plugin_name)
  201. init_source = os.path.join(self.path, INIT_FILENAME)
  202. try:
  203. loader = SourceFileLoader(plugin_module, init_source)
  204. self.module = loader.load_module()
  205. except (ImportError,FileNotFoundError) as e:
  206. raise PluginError("Failed to load plugin '%s'. It seems that the plugin name is not valid or the plugin do not exists" % plugin_name)
  207. # loading confspecs
  208. try:
  209. # Loading confspec directly from __init__.py
  210. self.__confspecs = getattr(self.module, CONFSPEC_VARNAME)
  211. except AttributeError:
  212. # Loading file in __confspec__ var in __init__.py
  213. try:
  214. module = self._import_from_init_var(CONFSPEC_FILENAME_VARNAME)
  215. except AttributeError:
  216. msg = "Malformed plugin {plugin} . No {varname} not {filevar} found in __init__.py"
  217. msg = msg.format(
  218. plugin = self.name,
  219. varname = CONFSPEC_VARNAME,
  220. filevar = CONFSPEC_FILENAME_VARNAME)
  221. raise PluginError(msg)
  222. except ImportError as e:
  223. msg = "Broken plugin {plugin} : {expt}"
  224. msg = msg.format(
  225. plugin = self.name,
  226. expt = str(e))
  227. raise PluginError(msg)
  228. try:
  229. # loading confpsecs from file
  230. self.__confspecs = getattr(module, CONFSPEC_VARNAME)
  231. except AttributeError:
  232. msg = "Broken plugin. {varname} not found in '{filename}'"
  233. msg = msg.format(
  234. varname = CONFSPEC_VARNAME,
  235. filename = confspec_filename)
  236. raise PluginError(msg)
  237. # loading plugin version
  238. try:
  239. #this try block should be useless. The existance of
  240. #PLUGIN_VERSION_VARNAME in init file is mandatory
  241. self.__version = getattr(self.module, PLUGIN_VERSION_VARNAME)
  242. except AttributeError:
  243. msg = "Error that should not append while loading plugin '%s': no \
  244. %s found in plugin init file. Malformed plugin"
  245. msg %= (plugin_name, PLUGIN_VERSION_VARNAME)
  246. raise LodelFatalError(msg)
  247. # Load plugin type
  248. try:
  249. self.__type = getattr(self.module, PLUGIN_TYPE_VARNAME)
  250. except AttributeError:
  251. self.__type = DEFAULT_PLUGIN_TYPE
  252. self.__type = str(self.__type).lower()
  253. if self.__type not in MetaPlugType.all_ptype_names():
  254. print("FUCK : ", MetaPlugType.all_ptype_names())
  255. raise PluginError("Unknown plugin type '%s'" % self.__type)
  256. # Load plugin name from init file (just for checking)
  257. try:
  258. #this try block should be useless. The existance of
  259. #PLUGIN_NAME_VARNAME in init file is mandatory
  260. pname = getattr(self.module, PLUGIN_NAME_VARNAME)
  261. except AttributeError:
  262. msg = "Error that should not append : no %s found in plugin \
  263. init file. Malformed plugin"
  264. msg %= PLUGIN_NAME_VARNAME
  265. raise LodelFatalError(msg)
  266. if pname != plugin_name:
  267. msg = "Plugin's discover cache inconsistency detected ! Cached \
  268. name differ from the one found in plugin's init file"
  269. raise PluginError(msg)
  270. ##@brief Try to import a file from a variable in __init__.py
  271. #@param varname str : The variable name
  272. #@return loaded module
  273. #@throw AttributeError if varname not found
  274. #@throw ImportError if the file fails to be imported
  275. #@throw PluginError if the filename was not valid
  276. def _import_from_init_var(self, varname):
  277. # Read varname
  278. try:
  279. filename = getattr(self.module, varname)
  280. except AttributeError:
  281. msg = "Malformed plugin {plugin}. No {varname} found in __init__.py"
  282. msg = msg.format(
  283. plugin = self.name,
  284. varname = LOADER_FILENAME_VARNAME)
  285. raise PluginError(msg)
  286. #Path are not allowed
  287. if filename != os.path.basename(filename):
  288. msg = "Invalid {varname} content : '{fname}' for plugin {name}"
  289. msg = msg.format(
  290. varname = varname,
  291. fname = filename,
  292. name = self.name)
  293. raise PluginError(msg)
  294. # importing the file in varname
  295. module_name = self.module.__name__+"."+varname
  296. filename = os.path.join(self.path, filename)
  297. loader = SourceFileLoader(module_name, filename)
  298. return loader.load_module()
  299. ##@brief Check dependencies of plugin
  300. #@return A list of plugin name to be loaded before
  301. def check_deps(self):
  302. try:
  303. res = getattr(self.module, PLUGIN_DEPS_VARNAME)
  304. except AttributeError:
  305. return list()
  306. result = list()
  307. errors = list()
  308. for plugin_name in res:
  309. try:
  310. result.append(self.get(plugin_name))
  311. except PluginError:
  312. errors.append(plugin_name)
  313. if len(errors) > 0:
  314. raise PluginError( "Bad dependencie for '%s' :"%self.name,
  315. ', '.join(errors))
  316. return result
  317. ##@brief Check if the plugin should be activated
  318. #
  319. #Try to fetch a function called @ref ACTIVATE_METHOD_NAME in __init__.py
  320. #of a plugin. If none found assert that the plugin can be loaded, else
  321. #the method is called. If it returns anything else that True, the plugin
  322. #is noted as not activable
  323. #
  324. # @note Maybe we have to exit everything if a plugin cannot be loaded...
  325. def activable(self):
  326. from lodel import logger
  327. try:
  328. test_fun = getattr(self.module, ACTIVATE_METHOD_NAME)
  329. except AttributeError:
  330. msg = "No %s method found for plugin %s. Assuming plugin is ready to be loaded"
  331. msg %= (ACTIVATE_METHOD_NAME, self.name)
  332. logger.debug(msg)
  333. test_fun = lambda:True
  334. return test_fun()
  335. ##@brief Load a plugin
  336. #
  337. #Loading a plugin means importing a file. The filename is defined in the
  338. #plugin's __init__.py file in a LOADER_FILENAME_VARNAME variable.
  339. #
  340. #The loading process has to take care of other things :
  341. #- loading dependencies (other plugins)
  342. #- check that the plugin can be activated using Plugin.activate() method
  343. #- avoid circular dependencies infinite loop
  344. def _load(self):
  345. if self.loaded:
  346. return
  347. from lodel import logger
  348. #Test that plugin "wants" to be activated
  349. activable = self.activable()
  350. if not(activable is True):
  351. msg = "Plugin %s is not activable : %s"
  352. msg %= (self.name, activable)
  353. raise PluginError(activable)
  354. #Circular dependencie detection
  355. if self.name in self._load_called:
  356. raise PluginError("Circular dependencie in Plugin detected. Abording")
  357. else:
  358. self._load_called.append(self.name)
  359. #Dependencie load
  360. for dependencie in self.check_deps():
  361. activable = dependencie.activable()
  362. if activable is True:
  363. dependencie._load()
  364. else:
  365. msg = "Plugin {plugin_name} not activable because it depends on plugin {dep_name} that is not activable : {reason}"
  366. msg = msg.format(
  367. plugin_name = self.name,
  368. dep_name = dependencie.name,
  369. reason = activable)
  370. #Loading the plugin
  371. try:
  372. self.__loader_module = self._import_from_init_var(LOADER_FILENAME_VARNAME)
  373. except PluginError as e:
  374. raise e
  375. except ImportError as e:
  376. msg = "Broken plugin {plugin} : {expt}"
  377. msg = msg.format(
  378. plugin = self.name,
  379. expt = str(e))
  380. raise PluginError(msg)
  381. logger.debug("Plugin '%s' loaded" % self.name)
  382. self.loaded = True
  383. ##@brief Returns the loader module
  384. #
  385. #Accessor for the __loader__ python module
  386. def loader_module(self):
  387. if not self.loaded:
  388. raise RuntimeError("Plugin %s not loaded yet."%self.name)
  389. return self.__loader_module
  390. def __str__(self):
  391. return "<LodelPlugin '%s' version %s>" % (self.name, self.__version)
  392. ##@brief Call load method on every pre-loaded plugins
  393. #
  394. # Called by loader to trigger hooks registration.
  395. # This method have to avoid circular dependencies infinite loops. For this
  396. # purpose a class attribute _load_called exists.
  397. # @throw PluginError
  398. @classmethod
  399. def load_all(cls):
  400. errors = dict()
  401. cls._load_called = []
  402. for name, plugin in cls._plugin_instances.items():
  403. try:
  404. plugin._load()
  405. except PluginError as e:
  406. errors[name] = e
  407. if len(errors) > 0:
  408. msg = "Errors while loading plugins :"
  409. for name, e in errors.items():
  410. msg += "\n\t%20s : %s" % (name,e)
  411. msg += "\n"
  412. raise PluginError(msg)
  413. from lodel.plugin.hooks import LodelHook
  414. LodelHook.call_hook(
  415. "lodel2_plugins_loaded", cls, cls._plugin_instances)
  416. ##@return a copy of __confspecs attr
  417. @property
  418. def confspecs(self):
  419. return copy.copy(self.__confspecs)
  420. @classmethod
  421. def plist_confspecs(cls):
  422. if cls._plist_confspecs is None:
  423. raise LodelFatalError('Unitialized _plist_confspecs attribute for \
  424. %s' % cls.__name__)
  425. return copy.copy(cls._plist_confspecs)
  426. ##@brief Retrieves plugin list confspecs
  427. #
  428. #This method ask for each Plugin child class the confspecs specifying where
  429. #the wanted plugin list is stored. (For example DatasourcePlugin expect
  430. #that a list of ds plugin to load stored in lodel2 section, datasources key
  431. # etc...
  432. @classmethod
  433. def plugin_list_confspec(cls):
  434. from lodel.settings.validator import confspec_append
  435. res = dict()
  436. for pcls in cls.plugin_types():
  437. plcs = pcls.plist_confspec()
  438. confspec_append(res, plcs)
  439. return res
  440. ##@brief Attempt to read plugin discover cache
  441. #@note If no cache yet make a discover with default plugin directory
  442. #@return a dict (see @ref _discover() )
  443. @classmethod
  444. def plugin_cache(cls):
  445. if cls._discover_cache is None:
  446. if not os.path.isfile(DISCOVER_CACHE_FILENAME):
  447. cls.discover()
  448. with open(DISCOVER_CACHE_FILENAME) as pdcache_fd:
  449. res = json.load(pdcache_fd)
  450. #Check consistency of loaded cache
  451. if 'path_list' not in res:
  452. raise LodelFatalError("Malformed plugin's discover cache file \
  453. : '%s'. Unable to find plugin's paths list." % DISCOVER_CACHE_FILENAME)
  454. expected_keys = ['type', 'path', 'version']
  455. for pname in res['plugins']:
  456. for ekey in expected_keys:
  457. if ekey not in res['plugins'][pname]:
  458. #Bad cache !
  459. logger.warning("Malformed plugin's discover cache \
  460. file : '%s'. Running discover again..." % DISCOVER_CACHE_FILENAME)
  461. cls._discover_cache = cls.discover(res['path_list'])
  462. break
  463. else:
  464. #The cache we just read was OK
  465. cls._discover_cache = res
  466. return cls._discover_cache
  467. ##@brief Register a new plugin
  468. #
  469. #@param plugin_name str : The plugin name
  470. #@return a Plugin instance
  471. #@throw PluginError
  472. @classmethod
  473. def register(cls, plugin_name):
  474. from .datasource_plugin import DatasourcePlugin
  475. if plugin_name in cls._plugin_instances:
  476. msg = "Plugin allready registered with same name %s"
  477. msg %= plugin_name
  478. raise PluginError(msg)
  479. #Here we check that previous discover found a plugin with that name
  480. pdcache = cls.plugin_cache()
  481. if plugin_name not in pdcache['plugins']:
  482. raise PluginError("No plugin named %s found" % plugin_name)
  483. pinfos = pdcache['plugins'][plugin_name]
  484. ptype = pinfos['type']
  485. if ptype not in MetaPlugType.all_ptype_names():
  486. raise PluginError("Unknown plugin type '%s'" % ptype)
  487. pcls = MetaPlugType.type_from_name(ptype)
  488. print("\n\n\nINSTANCIATING : ", pcls, " from name : ", ptype)
  489. plugin = pcls(plugin_name)
  490. cls._plugin_instances[plugin_name] = plugin
  491. logger.debug("Plugin %s available." % plugin)
  492. return plugin
  493. ##@brief Plugins instances accessor
  494. #
  495. #@param plugin_name str: The plugin name
  496. #@return a Plugin instance
  497. #@throw PluginError if plugin not found
  498. @classmethod
  499. def get(cls, plugin_name):
  500. try:
  501. return cls._plugin_instances[plugin_name]
  502. except KeyError:
  503. msg = "No plugin named '%s' loaded"
  504. msg %= plugin_name
  505. raise PluginError(msg)
  506. ##@brief Given a plugin name returns the plugin path
  507. # @param plugin_name str : The plugin name
  508. # @return the plugin directory path
  509. @classmethod
  510. def plugin_path(cls, plugin_name):
  511. plist = cls.plugin_list()
  512. if plugin_name not in plist:
  513. raise PluginError("No plugin named '%s' found" % plugin_name)
  514. try:
  515. return cls.get(plugin_name).path
  516. except PluginError:
  517. pass
  518. return plist[plugin_name]['path']
  519. @classmethod
  520. def plugin_module_name(cls, plugin_name):
  521. return "%s.%s" % (VIRTUAL_PACKAGE_NAME, plugin_name)
  522. ##@brief Start the Plugin class
  523. #
  524. # Called by Settings.__bootstrap()
  525. #
  526. # This method load path and preload plugins
  527. @classmethod
  528. def start(cls, plugins):
  529. for plugin_name in plugins:
  530. cls.register(plugin_name)
  531. @classmethod
  532. def clear(cls):
  533. if cls._plugin_directories is not None:
  534. cls._plugin_directories = None
  535. if cls._plugin_instances != dict():
  536. cls._plugin_instances = dict()
  537. if cls._load_called != []:
  538. cls._load_called = []
  539. ##@brief Reccursively walk throught paths to find plugin, then stores
  540. #found plugin in a file...
  541. #@param paths list : list of directory paths
  542. #@param no_cache bool : if true only return a list of found plugins
  543. #without modifying the cache file
  544. #@return a dict {'path_list': [...], 'plugins': { see @ref _discover }}
  545. #@todo add max_depth and symlink following options
  546. @classmethod
  547. def discover(cls, paths = None, no_cache = False):
  548. logger.info("Running plugin discover")
  549. if paths is None:
  550. paths = DEFAULT_PLUGINS_PATH_LIST
  551. tmp_res = []
  552. for path in paths:
  553. tmp_res += cls._discover(path)
  554. #Formating and dedoubloning result
  555. result = dict()
  556. for pinfos in tmp_res:
  557. pname = pinfos['name']
  558. if ( pname in result
  559. and pinfos['version'] > result[pname]['version'])\
  560. or pname not in result:
  561. result[pname] = pinfos
  562. else:
  563. #dropped
  564. pass
  565. result = {'path_list': paths, 'plugins': result}
  566. #Writing to cache
  567. if not no_cache:
  568. with open(DISCOVER_CACHE_FILENAME, 'w+') as pdcache:
  569. pdcache.write(json.dumps(result))
  570. return result
  571. ##@brief Return discover result
  572. #@param refresh bool : if true invalidate all plugin list cache
  573. #@note If discover cache file not found run discover first
  574. #@note if refresh is set to True discover MUST have been run at least
  575. #one time. In fact refresh action load the list of path to explore
  576. #from the plugin's discover cache
  577. @classmethod
  578. def plugin_list(cls, refresh = False):
  579. try:
  580. infos = cls._load_discover_cache()
  581. path_list = infos['path_list']
  582. except PluginError:
  583. refresh = True
  584. path_list = DEFAULT_PLUGINS_PATH_LIST
  585. if cls._plugin_list is None or refresh:
  586. if not os.path.isfile(DISCOVER_CACHE_FILENAME) or refresh:
  587. infos = cls.discover(path_list)
  588. cls._plugin_list = infos['plugins']
  589. return cls._plugin_list
  590. ##@brief Return a list of child Class Plugin
  591. @classmethod
  592. def plugin_types(cls):
  593. return MetaPlugType.all_types()
  594. ##@brief Attempt to open and load plugin discover cache
  595. #@return discover cache
  596. #@throw PluginError when open or load fails
  597. @classmethod
  598. def _load_discover_cache(cls):
  599. try:
  600. pdcache = open(DISCOVER_CACHE_FILENAME, 'r')
  601. except Exception as e:
  602. msg = "Unable to open discover cache : %s"
  603. msg %= e
  604. raise PluginError(msg)
  605. try:
  606. res = json.load(pdcache)
  607. except Exception as e:
  608. msg = "Unable to load discover cache : %s"
  609. msg %= e
  610. raise PluginError(msg)
  611. pdcache.close()
  612. return res
  613. ##@brief Check if a directory is a plugin module
  614. #@param path str : path to check
  615. #@return a dict with name, version and path if path is a plugin module, else False
  616. @classmethod
  617. def dir_is_plugin(cls, path):
  618. log_msg = "%s is not a plugin directory because : " % path
  619. #Checks that path exists
  620. if not os.path.isdir(path):
  621. raise ValueError(
  622. "Expected path to be a directory, but '%s' found" % path)
  623. #Checks that path contains plugin's init file
  624. initfile = os.path.join(path, INIT_FILENAME)
  625. if not os.path.isfile(initfile):
  626. log_msg += "'%s' not found" % (INIT_FILENAME)
  627. logger.debug(log_msg)
  628. return False
  629. #Importing plugin's init file to check contained datas
  630. try:
  631. initmod, modname = cls.import_init(path)
  632. except PluginError as e:
  633. log_msg += "unable to load '%s'. Exception raised : %s"
  634. log_msg %= (INIT_FILENAME, e)
  635. logger.debug(log_msg)
  636. return False
  637. #Checking mandatory init module variables
  638. for attr_name in MANDATORY_VARNAMES:
  639. if not hasattr(initmod,attr_name):
  640. log_msg += " mandatory variable '%s' not found in '%s'"
  641. log_msg %= (attr_name, INIT_FILENAME)
  642. logger.debug(log_msg)
  643. return False
  644. #Fetching plugin's version
  645. try:
  646. pversion = getattr(initmod, PLUGIN_VERSION_VARNAME)
  647. except (NameError, AttributeError) as e:
  648. msg = "Invalid plugin version found in %s : %s"
  649. msg %= (path, e)
  650. raise PluginError(msg)
  651. #Fetching plugin's type
  652. try:
  653. ptype = getattr(initmod, PLUGIN_TYPE_VARNAME)
  654. except (NameError, AttributeError) as e:
  655. ptype = DEFAULT_PLUGIN_TYPE
  656. pname = getattr(initmod, PLUGIN_NAME_VARNAME)
  657. return {'name': pname,
  658. 'version': pversion,
  659. 'path': path,
  660. 'type': ptype}
  661. ##@brief Import init file from a plugin path
  662. #@param path str : Directory path
  663. #@return a tuple (init_module, module_name)
  664. @classmethod
  665. def import_init(self, path):
  666. init_source = os.path.join(path, INIT_FILENAME)
  667. temp_module = '%s.%s.%s' % (
  668. VIRTUAL_TEMP_PACKAGE_NAME, os.path.basename(os.path.dirname(path)),
  669. 'test_init')
  670. try:
  671. loader = SourceFileLoader(temp_module, init_source)
  672. except (ImportError, FileNotFoundError) as e:
  673. raise PluginError("Unable to import init file from '%s' : %s" % (
  674. temp_module, e))
  675. try:
  676. res_module = loader.load_module()
  677. except Exception as e:
  678. raise PluginError("Unable to import initfile")
  679. return (res_module, temp_module)
  680. ##@brief Reccursiv plugin discover given a path
  681. #@param path str : the path to walk through
  682. #@return A dict with plugin_name as key and {'path':..., 'version':...} as value
  683. @classmethod
  684. def _discover(cls, path):
  685. res = []
  686. to_explore = [path]
  687. while len(to_explore) > 0:
  688. cur_path = to_explore.pop()
  689. for f in os.listdir(cur_path):
  690. f_path = os.path.join(cur_path, f)
  691. if f not in ['.', '..'] and os.path.isdir(f_path):
  692. #Check if it is a plugin directory
  693. test_result = cls.dir_is_plugin(f_path)
  694. if not (test_result is False):
  695. logger.info("Plugin found in %s" % f_path)
  696. res.append(test_result)
  697. else:
  698. to_explore.append(f_path)
  699. return res
  700. ##@brief Decorator class designed to allow plugins to add custom methods
  701. #to LeObject childs (dyncode objects)
  702. #
  703. class CustomMethod(object):
  704. ##@brief Stores registered custom methods
  705. #
  706. #Key = LeObject child class name
  707. #Value = CustomMethod instance
  708. _custom_methods = dict()
  709. INSTANCE_METHOD = 0
  710. CLASS_METHOD = 1
  711. STATIC_METHOD = 2
  712. ##@brief Decorator constructor
  713. #@param component_name str : the name of the component to enhance
  714. #@param method_name str : the name of the method to inject (if None given
  715. #@param method_type int : take value in one of
  716. #CustomMethod::INSTANCE_METHOD CustomMethod::CLASS_METHOD or
  717. #CustomMethod::STATIC_METHOD
  718. #use the function name
  719. def __init__(self, component_name, method_name = None, method_type=0):
  720. ##@brief The targeted LeObject child class
  721. self._comp_name = component_name
  722. ##@brief The method name
  723. self._method_name = method_name
  724. ##@brief The function (that will be the injected method)
  725. self._fun = None
  726. ##@brief Stores the type of method (instance, class or static)
  727. self._type = int(method_type)
  728. if self._type not in (self.INSTANCE_METHOD, self.CLASS_METHOD,\
  729. self.STATIC_METHOD):
  730. raise ValueError("Excepted value for method_type was one of \
  731. CustomMethod::INSTANCE_METHOD CustomMethod::CLASS_METHOD or \
  732. CustomMethod::STATIC_METHOD, but got %s" % self._type)
  733. ##@brief called just after __init__
  734. #@param fun function : the decorated function
  735. #@param return the function
  736. def __call__(self, fun):
  737. if self._method_name is None:
  738. self._method_name = fun.__name__
  739. if self._comp_name not in self._custom_methods:
  740. self._custom_methods[self._comp_name] = list()
  741. if self._method_name in [ scm._method_name for scm in self._custom_methods[self._comp_name]]:
  742. raise RuntimeError("A method named %s allready registered by \
  743. another plugin : %s" % (
  744. self._method_name,
  745. self._custom_methods[self._comp_name].__module__))
  746. self._fun = fun
  747. self._custom_methods[self._comp_name].append(self)
  748. ##@brief Textual representation
  749. #@return textual representation of the CustomMethod instance
  750. def __repr__(self):
  751. res = "<CustomMethod name={method_name} target={classname} \
  752. source={module_name}.{fun_name}>"
  753. return res.format(
  754. method_name = self._method_name,
  755. classname = self._comp_name,
  756. module_name = self._fun.__module__,
  757. fun_name = self._fun.__name__)
  758. ##@brief Return a well formed method
  759. #
  760. #@note the type of method depends on the _type attribute
  761. #@return a method directly injectable in the target class
  762. def __get_method(self):
  763. if self._type == self.INSTANCE_METHOD:
  764. def custom__get__(self, obj, objtype = None):
  765. return types.MethodType(self, obj, objtype)
  766. setattr(self._fun, '__get__', custom__get__)
  767. return self._fun
  768. elif self._type == self.CLASS_METHOD:
  769. return classmethod(self._fun)
  770. elif self._type == self.STATIC_METHOD:
  771. return staticmethod(self._fun)
  772. else:
  773. raise RuntimeError("Attribute _type is not one of \
  774. CustomMethod::INSTANCE_METHOD CustomMethod::CLASS_METHOD \
  775. CustomMethod::STATIC_METHOD")
  776. ##@brief Handle custom method dynamic injection in LeAPI dyncode
  777. #
  778. #Called by lodel2_dyncode_loaded hook defined at
  779. #lodel.plugin.core_hooks.lodel2_plugin_custom_methods()
  780. #
  781. #@param cls
  782. #@param dynclasses LeObject child classes : List of dynamically generated
  783. #LeObject child classes
  784. @classmethod
  785. def set_registered(cls, dynclasses):
  786. from lodel import logger
  787. dyn_cls_dict = { dc.__name__:dc for dc in dynclasses}
  788. for cls_name, custom_methods in cls._custom_methods.items():
  789. for custom_method in custom_methods:
  790. if cls_name not in dyn_cls_dict:
  791. logger.error("Custom method %s adding fails : No dynamic \
  792. LeAPI objects named %s." % (custom_method, cls_name))
  793. elif custom_method._method_name in dir(dyn_cls_dict[cls_name]):
  794. logger.warning("Overriding existing method '%s' on target \
  795. with %s" % (custom_method._method_name, custom_method))
  796. else:
  797. setattr(
  798. dyn_cls_dict[cls_name],
  799. custom_method._method_name,
  800. custom_method.__get_method())
  801. logger.debug(
  802. "Custom method %s added to target" % custom_method)