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 37KB

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