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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 Return a module from current context
  149. def get_module(self, fullname):
  150. fullname = self._translate(fullname)
  151. module = importlib.import_module(fullname)
  152. return module
  153. ##@brief Delete a site's context
  154. #@param site_id str : the site's name to remove the context
  155. def remove(cls, site_id):
  156. if site_id is None:
  157. if cls._type == cls.MULTISITE:
  158. raise ContextError("Cannot have a context with \
  159. site_id set to None when we are in MULTISITE beahavior")
  160. del cls._contexts
  161. else:
  162. if cls._type == cls.MULTISITE:
  163. if site_id in cls._contexts:
  164. del cls._contexts[site_id]
  165. else:
  166. raise ContextError("No site %s exist" % site_id)
  167. else:
  168. raise ContextError("Cannot have a context with \
  169. site_id set when we are in MONOSITE beahavior")
  170. ##@return True if the class is in MULTISITE mode
  171. @classmethod
  172. def multisite(cls):
  173. return cls._type == cls.MULTISITE
  174. ##@brief helper class to use LodeContext with with statement
  175. #@note alias to get method
  176. #@note maybe useless
  177. #@todo delete me
  178. @classmethod
  179. def with_context(cls, target_ctx_id):
  180. return cls.get(target_ctx_id)
  181. ##@brief Set a context as active
  182. #@param site_id str : site identifier (identify a context)
  183. @classmethod
  184. def set(cls, site_id):
  185. if cls._type == cls.MONOSITE:
  186. raise ContextError("Context cannot be set in MONOSITE beahvior")
  187. site_id = LOAD_CTX if site_id is None else site_id
  188. if not cls.validate_identifier(site_id):
  189. raise ContextError("Given context name is not a valide identifier \
  190. : '%s'" % site_id)
  191. if site_id not in cls._contexts:
  192. raise ContextError("No context named '%s' found." % site_id)
  193. wanted_ctx = cls._contexts[site_id]
  194. if hasattr(wanted_ctx, '__instance_path'):
  195. os.chdir(self.__instance_path) #May cause problems
  196. cls._current = wanted_ctx
  197. return cls._current
  198. ##@brief Getter for contexts
  199. #@param ctx_id str | None | False : if False return the current context
  200. #@return A LodelContext instance
  201. @classmethod
  202. def get(cls, ctx_id = False):
  203. if ctx_id is False:
  204. if cls._current is None:
  205. raise ContextError("No context loaded")
  206. return cls._current
  207. ctx_id = LOAD_CTX if ctx_id is None else ctx_id
  208. if ctx_id not in cls._contexts:
  209. raise ContextError("No context identified by '%s'" % ctx_id)
  210. return cls._contexts[ctx_id]
  211. ##@brief Returns the name of the loaded context
  212. @classmethod
  213. def get_name(cls):
  214. if cls._current is None:
  215. raise ContextError("No context loaded")
  216. return copy.copy(cls._current.__id)
  217. ##@brief Create a new context given a context name
  218. #
  219. #@note It's just an alias to the LodelContext.__init__ method
  220. #@param site_id str : context name
  221. #@return the context instance
  222. @classmethod
  223. def new(cls, site_id, instance_path = None):
  224. if site_id is None:
  225. site_id = LOAD_CTX
  226. return cls(site_id, instance_path)
  227. ##@brief Helper function that import and expose specified modules
  228. #
  229. #The specs given is a dict. Each element is indexed by a module
  230. #fullname. Items can be of two types :
  231. #@par Simple import with alias
  232. #In this case items of specs is a string representing the alias name
  233. #for the module we are exposing
  234. #@par from x import i,j,k equivalent
  235. #In this case items are lists of object name to expose as it in globals.
  236. #You can specify an alias by giving a tuple instead of a string as
  237. #list element. In this case the first element of the tuple is the object
  238. #name and the second it's alias in the globals
  239. #
  240. #@todo make the specs format more consitant
  241. #@param cls : bultin params
  242. #@param globs dict : the globals dict of the caller module
  243. #@param specs dict : specs of exposure (see comments of this method)
  244. #@todo implements relative module imports. (maybe by looking for
  245. #"calling" package in globs dict)
  246. @classmethod
  247. def expose_modules(cls, globs, specs):
  248. ctx = cls.get()
  249. for spec in specs.items():
  250. ctx.expose(globs, spec)
  251. ##@brief Return a module from current context
  252. #@param fullname str : module fullname
  253. @classmethod
  254. def module(cls, fullname):
  255. return cls.get().get_module(fullname)
  256. ##@brief Expose leapi_dyncode module
  257. @classmethod
  258. def expose_dyncode(cls, globs, alias = 'leapi_dyncode'):
  259. cls.get()._expose_dyncode(globs, alias)
  260. ##@brief Initialize the context manager
  261. #
  262. #@note Add the LodelMetaPathFinder class to sys.metapath if type is
  263. #LodelContext.MULTISITE
  264. #@param type FLAG : takes value in LodelContext.MONOSITE or
  265. #LodelContext.MULTISITE
  266. @classmethod
  267. def init(cls, type=MONOSITE):
  268. if cls._current is not None:
  269. raise ContextError("Context allready started and used. Enable to \
  270. initialize it anymore")
  271. if type not in ( cls.MONOSITE, cls.MULTISITE):
  272. raise ContextError("Invalid flag given : %s" % type)
  273. cls._type = type
  274. if cls._type == cls.MULTISITE:
  275. cls._contexts = dict()
  276. #Add custom MetaPathFinder allowing implementing custom imports
  277. sys.meta_path = [LodelMetaPathFinder] + sys.meta_path
  278. #Create and set __loader__ context
  279. cls.new(LOAD_CTX)
  280. cls.set(LOAD_CTX)
  281. else:
  282. #Add a single context with no site_id
  283. cls._contexts = cls._current = cls(None)
  284. cls.__initialized = True
  285. ##@return True if the class is initialized
  286. @classmethod
  287. def is_initialized(cls):
  288. return cls.__initialized
  289. ##@brief Return the directory of the package of the current loaded context
  290. @classmethod
  291. def context_dir(cls):
  292. if cls._type == cls.MONOSITE:
  293. return './'
  294. return dir_for_context(cls._current.__id)
  295. ##@brief Validate a context identifier
  296. #@param identifier str : the identifier to validate
  297. #@return true if the name is valide else false
  298. @staticmethod
  299. def validate_identifier(identifier):
  300. if identifier == LOAD_CTX:
  301. return True
  302. return identifier is None or \
  303. re.match(r'^[a-zA-Z0-9][a-zA-Z0-9_]', identifier)
  304. ##@brief Safely expose a module in globals using an alias name
  305. #
  306. #@note designed to implements warning messages or stuff like that
  307. #when doing nasty stuff
  308. #
  309. #@warning Logging stuffs may lead in a performance issue
  310. #
  311. #@todo try to use the logger module instead of warnings
  312. #@param globs globals : the globals where we want to expose our
  313. #module alias
  314. #@param obj object : the object we want to expose
  315. #@param alias str : the alias name for our module
  316. @staticmethod
  317. def safe_exposure(globs, obj, alias):
  318. if alias in globs:
  319. if globs[alias] != obj:
  320. print("Context '%s' : A module exposure leads in globals overwriting for \
  321. key '%s' with a different value : %s != %s" % (LodelContext.get_name(), alias, globs[alias], obj))
  322. """#Uncomment this bloc to display a stack trace for dangerous modules overwriting
  323. print("DEBUG INFOS : ")
  324. import traceback
  325. traceback.print_stack()
  326. """
  327. else:
  328. print("Context '%s' : A module exposure leads in a useless replacement for \
  329. key '%s'" % (LodelContext.get_name(),alias))
  330. globs[alias] = obj
  331. ##@brief Create a context from a path and returns the context name
  332. #@param path str : the path from which we extract a sitename
  333. #@return the site identifier
  334. @classmethod
  335. def from_path(cls, path):
  336. if cls._type != cls.MULTISITE:
  337. raise ContextError("Cannot create a context from a path in \
  338. MONOSITE mode")
  339. site_id = os.path.basename(path.strip('/'))
  340. path = os.path.realpath(path)
  341. if not cls.validate_identifier(site_id):
  342. raise ContextError(
  343. "Unable to create a context named '%s'" % site_id)
  344. cls.new(site_id, path)
  345. return site_id
  346. ##@brief Utility method to expose a module with an alias name in globals
  347. #@param globs globals() : concerned globals dict
  348. #@param fullname str : module fullname
  349. #@param alias str : alias name
  350. @classmethod
  351. def _expose_module(cls, globs, fullname, alias):
  352. module = importlib.import_module(fullname)
  353. cls.safe_exposure(globs, module, alias)
  354. ##@brief Utility mehod to expose objects like in a from x import y,z
  355. #form
  356. #@param globs globals() : dict of globals
  357. #@param fullename str : module fullname
  358. #@param objects list : list of object names to expose
  359. @classmethod
  360. def _expose_objects(cls, globs, fullname, objects):
  361. errors = []
  362. module = importlib.import_module(fullname)
  363. for o_name in objects:
  364. if isinstance(o_name, str):
  365. alias = o_name
  366. else:
  367. o_name, alias = o_name
  368. if not hasattr(module, o_name):
  369. errors.append(o_name)
  370. else:
  371. cls.safe_exposure(globs, getattr(module, o_name), alias)
  372. if len(errors) > 0:
  373. msg = "Module %s does not have any of [%s] as attribute" % (
  374. fullname, ','.join(errors))
  375. raise ImportError(msg)
  376. ##@brief Implements LodelContext::expose_dyncode()
  377. #@todo change hardcoded leapi_dyncode.py filename
  378. def _expose_dyncode(self, globs, alias = 'leapi_dyncode'):
  379. fullname = '%s.%s.dyncode' % (CTX_PKG, self.__id)
  380. if fullname in sys.modules:
  381. dyncode = sys.modules[fullname]
  382. else:
  383. path = os.path.join(self.__instance_path, 'leapi_dyncode.py')
  384. sfl = importlib.machinery.SourceFileLoader(fullname, path)
  385. dyncode = sfl.load_module()
  386. self.safe_exposure(globs, dyncode, alias)
  387. ##@brief Translate a module fullname to the context equivalent
  388. #@param module_fullname str : a module fullname
  389. #@return The module name in the current context
  390. def _translate(self, module_fullname):
  391. if not module_fullname.startswith('lodel'):
  392. raise ContextModuleError("Given module is not lodel or any \
  393. submodule : '%s'" % module_fullname)
  394. return module_fullname.replace('lodel', self.__pkg_name)
  395. ##@brief Implements the with statement behavior
  396. #@see https://www.python.org/dev/peps/pep-0343/
  397. #@see https://wiki.python.org/moin/WithStatement
  398. def __enter__(self):
  399. if not self.multisite:
  400. warnings.warn("Using LodelContext with with statement in \
  401. MONOSITE mode")
  402. if self.__previous_ctx is not None:
  403. raise ContextError("__enter__ called but a previous context \
  404. is allready registered !!! Bailout")
  405. current = LodelContext.get().__id
  406. if current != self.__id:
  407. #Only switch if necessary
  408. self.__previous_ctx = LodelContext.get().__id
  409. LodelContext.set(self.__id)
  410. return self
  411. ##@brief Implements the with statement behavior
  412. #@see https://www.python.org/dev/peps/pep-0343/
  413. #@see https://wiki.python.org/moin/WithStatement
  414. def __exit__(self, exc_type, exc_val, exc_tb):
  415. prev = self.__previous_ctx
  416. self.__previous_ctx = None
  417. if prev is not None:
  418. #Only restore if needed
  419. LodelContext.set(self.__previous_ctx)