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.

context.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. import importlib
  2. import importlib.machinery
  3. import importlib.abc
  4. import sys
  5. import types
  6. import os
  7. import os.path
  8. import re
  9. import copy
  10. import warnings #For the moment no way to use the logger in this file (I guess)
  11. #A try to avoid circular dependencies problems
  12. if 'lodel' not in sys.modules:
  13. import lodel
  14. else:
  15. globals()['lodel'] = sys.modules['lodel']
  16. if 'lodelsites' not in sys.modules:
  17. import lodelsites
  18. else:
  19. globals()['lodelsites'] = sys.modules['lodelsites']
  20. ##@brief Name of the package that will contains all the virtual lodel
  21. #packages
  22. CTX_PKG = "lodelsites"
  23. ##@brief Reserved context name for loading steps
  24. #@note This context is designed to be set at loading time, allowing lodel2
  25. #main process to use lodel packages
  26. LOAD_CTX = "__loader__"
  27. #
  28. # Following exception classes are written here to avoid circular dependencies
  29. # problems.
  30. #
  31. ##@brief Designed to be raised by the context manager
  32. class ContextError(Exception):
  33. pass
  34. ##@brief Raised when an error concerning context modules occurs
  35. class ContextModuleError(ContextError):
  36. pass
  37. def dir_for_context(site_identifier):
  38. return os.path.join(lodelsites.__path__[0], site_identifier)
  39. ##@brief Designed to permit dynamic packages creation from the lodel package
  40. #
  41. #The class is added in first position in the sys.metapath variable. Doing this
  42. #we override the earlier steps of the import mechanism.
  43. #
  44. #When called the find_spec method determine wether the imported module is
  45. #a part of a virtual lodel package, else it returns None and the standart
  46. #import mechanism go further.
  47. #If it's a submodule of a virtual lodel package we create a symlink
  48. #to represent the lodel package os the FS and then we make python import
  49. #files from the symlink.
  50. #
  51. #@note Current implementation is far from perfection. In fact no deletion
  52. #mechanisms is written and the virtual package cannot be a subpackage of
  53. #the lodel package for the moment...
  54. #@note Current implementation asserts that all plugins are in CWD
  55. #a symlink will be done to create a copy of the plugins folder in
  56. #lodelsites/SITENAME/ folder
  57. class LodelMetaPathFinder(importlib.abc.MetaPathFinder):
  58. def find_spec(fullname, path, target = None):
  59. if fullname.startswith(CTX_PKG):
  60. spl = fullname.split('.')
  61. site_identifier = spl[1]
  62. #creating a symlink to represent the lodel site package
  63. mod_path = dir_for_context(site_identifier)
  64. if not os.path.exists(mod_path):
  65. os.symlink(lodel.__path__[0], mod_path, True)
  66. #Cache invalidation after we "created" the new package
  67. #importlib.invalidate_caches()
  68. return None
  69. ##@brief Class designed to handle context switching and virtual module
  70. #exposure
  71. #
  72. #@note a dedicated context named LOAD_CTX is used as context for the
  73. #loading process
  74. class LodelContext(object):
  75. ##@brief FLag telling that the context handler is in single context mode
  76. MONOSITE = 1
  77. ##@brief Flag telling that the context manager is in multi context mode
  78. MULTISITE = 2
  79. ##@brief Static property storing current context name
  80. _current = None
  81. ##@brief Stores the context type (single or multiple)
  82. _type = None
  83. ##@brief Stores the contexts
  84. _contexts = None
  85. ##@brief Flag indicating if the classe is initialized
  86. __initialized = False
  87. ##@brief Create a new context
  88. #@see LodelContext.new()
  89. def __init__(self, site_id, instance_path = None):
  90. if site_id is None and self.multisite():
  91. site_id = LOAD_CTX
  92. if self.multisite() and site_id is not LOAD_CTX:
  93. with LodelContext.with_context(None) as ctx:
  94. ctx.expose_modules(globals(), {'lodel.logger': 'logger'})
  95. logger.info("New context instanciation named '%s'" % site_id)
  96. if site_id is None:
  97. self.__id = "MONOSITE"
  98. #Monosite instanciation
  99. if self.multisite():
  100. raise ContextError("Cannot instanciate a context with \
  101. site_id set to None when we are in MULTISITE beahavior")
  102. else:
  103. #More verification can be done here (singleton specs ? )
  104. self.__class__._current = self.__class__._contexts = self
  105. self.__pkg_name = 'lodel'
  106. self.__package = lodel
  107. return
  108. else:
  109. #Multisite instanciation
  110. if not self.multisite():
  111. raise ContextError("Cannot instanciate a context with a \
  112. site_id when we are in MONOSITE beahvior")
  113. if not self.validate_identifier(site_id):
  114. raise ContextError("Given context name is not a valide identifier \
  115. : '%s'" % site_id)
  116. if site_id in self.__class__._contexts:
  117. raise ContextError(
  118. "A context named '%s' allready exists." % site_id)
  119. self.__id = site_id
  120. self.__pkg_name = '%s.%s' % (CTX_PKG, site_id)
  121. if instance_path is None:
  122. """
  123. raise ContextError("Cannot create a context without an \
  124. instance path")
  125. """
  126. warnings.warn("It can be a really BAD idea to create a \
  127. a context without a path......")
  128. else:
  129. self.__instance_path = os.path.realpath(instance_path)
  130. #Importing the site package to trigger its creation
  131. self.__package = importlib.import_module(self.__pkg_name)
  132. self.__class__._contexts[site_id] = self
  133. #Designed to be use by with statement
  134. self.__previous_ctx = None
  135. ##@brief Expose a module from the context
  136. #@param globs globals : globals where we have to expose the module
  137. #@param spec tuple : first item is module name, second is the alias
  138. def expose(self, globs, spec):
  139. if len(spec) != 2:
  140. raise ContextError("Invalid argument given. Expected a tuple of \
  141. length == 2 but got : %s" % spec)
  142. module_fullname, exposure_spec = spec
  143. module_fullname = self._translate(module_fullname)
  144. if isinstance(exposure_spec, str):
  145. self._expose_module(globs, module_fullname, exposure_spec)
  146. else:
  147. self._expose_objects(globs, module_fullname, exposure_spec)
  148. ##@brief Delete a site's context
  149. #@param site_id str : the site's name to remove the context
  150. def remove(cls, site_id):
  151. if site_id is None:
  152. if cls._type == cls.MULTISITE:
  153. raise ContextError("Cannot have a context with \
  154. site_id set to None when we are in MULTISITE beahavior")
  155. del cls._contexts
  156. else:
  157. if cls._type == cls.MULTISITE:
  158. if site_id in cls._contexts:
  159. del cls._contexts[site_id]
  160. else:
  161. raise ContextError("No site %s exist" % site_id)
  162. else:
  163. raise ContextError("Cannot have a context with \
  164. site_id set when we are in MONOSITE beahavior")
  165. ##@return True if the class is in MULTISITE mode
  166. @classmethod
  167. def multisite(cls):
  168. return cls._type == cls.MULTISITE
  169. ##@brief helper class to use LodeContext with with statement
  170. #@note alias to get method
  171. #@note maybe useless
  172. #@todo delete me
  173. @classmethod
  174. def with_context(cls, target_ctx_id):
  175. return cls.get(target_ctx_id)
  176. ##@brief Set a context as active
  177. #@param site_id str : site identifier (identify a context)
  178. @classmethod
  179. def set(cls, site_id):
  180. if cls._type == cls.MONOSITE:
  181. raise ContextError("Context cannot be set in MONOSITE beahvior")
  182. site_id = LOAD_CTX if site_id is None else site_id
  183. if not cls.validate_identifier(site_id):
  184. raise ContextError("Given context name is not a valide identifier \
  185. : '%s'" % site_id)
  186. if site_id not in cls._contexts:
  187. raise ContextError("No context named '%s' found." % site_id)
  188. cls._current = cls._contexts[site_id]
  189. return cls._current
  190. ##@brief Getter for contexts
  191. #@param ctx_id str | None | False : if False return the current context
  192. #@return A LodelContext instance
  193. @classmethod
  194. def get(cls, ctx_id = False):
  195. if ctx_id is False:
  196. if cls._current is None:
  197. raise ContextError("No context loaded")
  198. return cls._current
  199. ctx_id = LOAD_CTX if ctx_id is None else ctx_id
  200. if ctx_id not in cls._contexts:
  201. raise ContextError("No context identified by '%s'" % ctx_id)
  202. return cls._contexts[ctx_id]
  203. ##@brief Returns the name of the loaded context
  204. @classmethod
  205. def get_name(cls):
  206. if cls._current is None:
  207. raise ContextError("No context loaded")
  208. return copy.copy(cls._current.__id)
  209. ##@brief Create a new context given a context name
  210. #
  211. #@note It's just an alias to the LodelContext.__init__ method
  212. #@param site_id str : context name
  213. #@return the context instance
  214. @classmethod
  215. def new(cls, site_id, instance_path = None):
  216. if site_id is None:
  217. site_id = LOAD_CTX
  218. return cls(site_id, instance_path)
  219. ##@brief Helper function that import and expose specified modules
  220. #
  221. #The specs given is a dict. Each element is indexed by a module
  222. #fullname. Items can be of two types :
  223. #@par Simple import with alias
  224. #In this case items of specs is a string representing the alias name
  225. #for the module we are exposing
  226. #@par from x import i,j,k equivalent
  227. #In this case items are lists of object name to expose as it in globals.
  228. #You can specify an alias by giving a tuple instead of a string as
  229. #list element. In this case the first element of the tuple is the object
  230. #name and the second it's alias in the globals
  231. #
  232. #@todo make the specs format more consitant
  233. #@param cls : bultin params
  234. #@param globs dict : the globals dict of the caller module
  235. #@param specs dict : specs of exposure (see comments of this method)
  236. #@todo implements relative module imports. (maybe by looking for
  237. #"calling" package in globs dict)
  238. @classmethod
  239. def expose_modules(cls, globs, specs):
  240. ctx = cls.get()
  241. for spec in specs.items():
  242. ctx.expose(globs, spec)
  243. ##@brief Expose leapi_dyncode module
  244. @classmethod
  245. def expose_dyncode(cls, globs, alias = 'leapi_dyncode'):
  246. cls.get()._expose_dyncode(globs, alias)
  247. ##@brief Initialize the context manager
  248. #
  249. #@note Add the LodelMetaPathFinder class to sys.metapath if type is
  250. #LodelContext.MULTISITE
  251. #@param type FLAG : takes value in LodelContext.MONOSITE or
  252. #LodelContext.MULTISITE
  253. @classmethod
  254. def init(cls, type=MONOSITE):
  255. if cls._current is not None:
  256. raise ContextError("Context allready started and used. Enable to \
  257. initialize it anymore")
  258. if type not in ( cls.MONOSITE, cls.MULTISITE):
  259. raise ContextError("Invalid flag given : %s" % type)
  260. cls._type = type
  261. if cls._type == cls.MULTISITE:
  262. cls._contexts = dict()
  263. #Add custom MetaPathFinder allowing implementing custom imports
  264. sys.meta_path = [LodelMetaPathFinder] + sys.meta_path
  265. #Create and set __loader__ context
  266. cls.new(LOAD_CTX)
  267. cls.set(LOAD_CTX)
  268. else:
  269. #Add a single context with no site_id
  270. cls._contexts = cls._current = cls(None)
  271. cls.__initialized = True
  272. ##@return True if the class is initialized
  273. @classmethod
  274. def is_initialized(cls):
  275. return cls.__initialized
  276. ##@brief Return the directory of the package of the current loaded context
  277. @classmethod
  278. def context_dir(cls):
  279. if cls._type == cls.MONOSITE:
  280. return './'
  281. return dir_for_context(cls._current.__id)
  282. ##@brief Validate a context identifier
  283. #@param identifier str : the identifier to validate
  284. #@return true if the name is valide else false
  285. @staticmethod
  286. def validate_identifier(identifier):
  287. if identifier == LOAD_CTX:
  288. return True
  289. return identifier is None or \
  290. re.match(r'^[a-zA-Z0-9][a-zA-Z0-9_]', identifier)
  291. ##@brief Safely expose a module in globals using an alias name
  292. #
  293. #@note designed to implements warning messages or stuff like that
  294. #when doing nasty stuff
  295. #
  296. #@warning Logging stuffs may lead in a performance issue
  297. #
  298. #@todo try to use the logger module instead of warnings
  299. #@param globs globals : the globals where we want to expose our
  300. #module alias
  301. #@param obj object : the object we want to expose
  302. #@param alias str : the alias name for our module
  303. @staticmethod
  304. def safe_exposure(globs, obj, alias):
  305. if alias in globs:
  306. if globs[alias] != obj:
  307. print("Context '%s' : A module exposure leads in globals overwriting for \
  308. key '%s' with a different value : %s != %s" % (LodelContext.get_name(), alias, globs[alias], obj))
  309. """#Uncomment this bloc to display a stack trace for dangerous modules overwriting
  310. print("DEBUG INFOS : ")
  311. import traceback
  312. traceback.print_stack()
  313. """
  314. else:
  315. print("Context '%s' : A module exposure leads in a useless replacement for \
  316. key '%s'" % (LodelContext.get_name(),alias))
  317. globs[alias] = obj
  318. ##@brief Create a context from a path and returns the context name
  319. #@param path str : the path from which we extract a sitename
  320. #@return the site identifier
  321. @classmethod
  322. def from_path(cls, path):
  323. if cls._type != cls.MULTISITE:
  324. raise ContextError("Cannot create a context from a path in \
  325. MONOSITE mode")
  326. site_id = os.path.basename(path.strip('/'))
  327. path = os.path.realpath(path)
  328. if not cls.validate_identifier(site_id):
  329. raise ContextError(
  330. "Unable to create a context named '%s'" % site_id)
  331. cls.new(site_id, path)
  332. return site_id
  333. ##@brief Utility method to expose a module with an alias name in globals
  334. #@param globs globals() : concerned globals dict
  335. #@param fullname str : module fullname
  336. #@param alias str : alias name
  337. @classmethod
  338. def _expose_module(cls, globs, fullname, alias):
  339. module = importlib.import_module(fullname)
  340. cls.safe_exposure(globs, module, alias)
  341. ##@brief Utility mehod to expose objects like in a from x import y,z
  342. #form
  343. #@param globs globals() : dict of globals
  344. #@param fullename str : module fullname
  345. #@param objects list : list of object names to expose
  346. @classmethod
  347. def _expose_objects(cls, globs, fullname, objects):
  348. errors = []
  349. module = importlib.import_module(fullname)
  350. for o_name in objects:
  351. if isinstance(o_name, str):
  352. alias = o_name
  353. else:
  354. o_name, alias = o_name
  355. if not hasattr(module, o_name):
  356. errors.append(o_name)
  357. else:
  358. cls.safe_exposure(globs, getattr(module, o_name), alias)
  359. if len(errors) > 0:
  360. msg = "Module %s does not have any of [%s] as attribute" % (
  361. fullname, ','.join(errors))
  362. raise ImportError(msg)
  363. ##@brief Implements LodelContext::expose_dyncode()
  364. def _expose_dyncode(self, globs, alias = 'leapi_dyncode'):
  365. sys.path.append(self.__instance_path)
  366. dyncode = importlib.import_module('leapi_dyncode')
  367. self.safe_exposure(globs, dyncode, alias)
  368. ##@brief Translate a module fullname to the context equivalent
  369. #@param module_fullname str : a module fullname
  370. #@return The module name in the current context
  371. def _translate(self, module_fullname):
  372. if not module_fullname.startswith('lodel'):
  373. raise ContextModuleError("Given module is not lodel or any \
  374. submodule : '%s'" % module_fullname)
  375. return module_fullname.replace('lodel', self.__pkg_name)
  376. ##@brief Implements the with statement behavior
  377. #@see https://www.python.org/dev/peps/pep-0343/
  378. #@see https://wiki.python.org/moin/WithStatement
  379. def __enter__(self):
  380. if not self.multisite:
  381. warnings.warn("Using LodelContext with with statement in \
  382. MONOSITE mode")
  383. if self.__previous_ctx is not None:
  384. raise ContextError("__enter__ called but a previous context \
  385. is allready registered !!! Bailout")
  386. current = LodelContext.get().__id
  387. if current != self.__id:
  388. #Only switch if necessary
  389. self.__previous_ctx = LodelContext.get().__id
  390. LodelContext.set(self.__id)
  391. return self
  392. ##@brief Implements the with statement behavior
  393. #@see https://www.python.org/dev/peps/pep-0343/
  394. #@see https://wiki.python.org/moin/WithStatement
  395. def __exit__(self, exc_type, exc_val, exc_tb):
  396. prev = self.__previous_ctx
  397. self.__previous_ctx = None
  398. if prev is not None:
  399. #Only restore if needed
  400. LodelContext.set(self.__previous_ctx)