Import python modules by their hash.
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.

455 lines
12 KiB

  1. # Copyright 2020 John-Mark Gurney.
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions
  6. # are met:
  7. # 1. Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  14. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  17. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  19. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  20. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  23. # SUCH DAMAGE.
  24. import contextlib
  25. import glob
  26. import hashlib
  27. import importlib.resources
  28. import os.path
  29. import pathlib
  30. import shutil
  31. import sys
  32. import tempfile
  33. import urllib
  34. from importlib.abc import MetaPathFinder, Loader
  35. from importlib.machinery import ModuleSpec
  36. @contextlib.contextmanager
  37. def tempset(obj, key, value):
  38. '''A context (with) manager for changing the value of an item in a
  39. dictionary, and restoring it after the with block.
  40. Example usage:
  41. ```
  42. d = dict(a=5, b=10)
  43. with tempset(d, 'a', 15):
  44. print(repr(d['a'])
  45. print(repr(d['a'])
  46. ```
  47. '''
  48. try:
  49. oldvalue = obj[key]
  50. obj[key] = value
  51. yield
  52. finally:
  53. obj[key] = oldvalue
  54. @contextlib.contextmanager
  55. def tempattrset(obj, key, value):
  56. '''A context (with) manager for changing the value of an attribute
  57. of an object, and restoring it after the with block.
  58. If the attribute does not exist, it will be deleted afterward.
  59. Example usage:
  60. ```
  61. with tempattrset(someobj, 'a', 15):
  62. print(repr(someobj.a)
  63. print(repr(someobj.a)
  64. ```
  65. '''
  66. try:
  67. dodelattr = False
  68. if hasattr(obj, key):
  69. oldvalue = getattr(obj, key)
  70. else:
  71. dodelattr = True
  72. setattr(obj, key, value)
  73. yield
  74. finally:
  75. if not dodelattr:
  76. setattr(obj, key, oldvalue)
  77. else:
  78. delattr(obj, key)
  79. class FileDirCAS(object):
  80. '''A file loader for CAS that operates on a directory. It looks
  81. at files, caches their hash, and loads them upon request.'''
  82. def __init__(self, path):
  83. self._path = pathlib.Path(path)
  84. self._hashes = {}
  85. def refresh_dir(self):
  86. '''Internal method to refresh the internal cache of
  87. hashes.'''
  88. for i in glob.glob(os.path.join(self._path, '*.py')):
  89. _, hash = self.read_hash_file(i)
  90. self._hashes[hash] = i
  91. @staticmethod
  92. def read_hash_file(fname):
  93. '''Helper function that will read the file at fname, and
  94. return the tuple of it's contents and it's hash.'''
  95. with open(fname, 'rb') as fp:
  96. data = fp.read()
  97. hash = hashlib.sha256(data).hexdigest()
  98. return data, hash
  99. def is_package(self, hash):
  100. '''Decode the provided hash, and decide if it's a package
  101. or not.'''
  102. return False
  103. def fetch_data(self, url):
  104. '''Given the URL (must be a hash URL), return the code for it.'''
  105. self.refresh_dir()
  106. hashurl = url
  107. if hashurl.scheme != 'hash' or hashurl.netloc != 'sha256':
  108. raise ValueError('invalid hash url')
  109. hash = hashurl.path[1:]
  110. fname = self._hashes[hash]
  111. data, fhash = self.read_hash_file(fname)
  112. if fhash != hash:
  113. raise ValueError('file no longer matches hash on disk')
  114. return data
  115. class CASFinder(MetaPathFinder, Loader):
  116. '''Overall class for using Content Addressable Storage to load
  117. Python modules into your code. It contains code to dispatch to
  118. the various loaders to attempt to load the hash.'''
  119. def __init__(self):
  120. self._loaders = []
  121. self._aliases = {}
  122. if [ x for x in sys.meta_path if isinstance(x, self.__class__) ]:
  123. raise RuntimeError('cannot register more than on CASFinder')
  124. sys.meta_path.append(self)
  125. def __enter__(self):
  126. return self
  127. def __exit__(self, exc_type, exc_value, traceback):
  128. self.disconnect()
  129. def load_aliases(self, name):
  130. '''Load the aliases from the module with the passed in name.'''
  131. aliases = importlib.resources.read_text(sys.modules[name], 'cas_aliases.txt')
  132. self._aliases.update(self._parsealiases(aliases))
  133. @staticmethod
  134. def _parsealiases(data):
  135. ret = {}
  136. lines = data.split('\n')
  137. for i in lines:
  138. if not i:
  139. continue
  140. name, hash = i.split()
  141. ret.setdefault(name, []).append(hash)
  142. return ret
  143. def disconnect(self):
  144. '''Disconnect this Finder from being used to load modules.
  145. As this claims an entire namespace, only the first loaded
  146. one will work, and any others will be hidden until the
  147. first one is disconnected.
  148. This can be used w/ a with block to automatically
  149. disconnect when no longer needed. This is mostly useful
  150. for testing.'''
  151. try:
  152. sys.meta_path.remove(self)
  153. except ValueError:
  154. pass
  155. def register(self, loader):
  156. '''Register a loader w/ this finder. This will attempt
  157. to load the hash passed to it. It is also (currently)
  158. responsible for executing the code in the module.'''
  159. self._loaders.append(loader)
  160. # MetaPathFinder methods
  161. def find_spec(self, fullname, path, target=None):
  162. if path is None:
  163. ms = ModuleSpec(fullname, self, is_package=True)
  164. else:
  165. parts = fullname.split('.')
  166. ver, typ, arg = parts[1].split('_')
  167. if typ == 'f':
  168. # make hash url:
  169. hashurl = 'hash://sha256/%s' % bytes.fromhex(arg).hex()
  170. hashurl = urllib.parse.urlparse(hashurl)
  171. for l in self._loaders:
  172. ispkg = l.is_package(hashurl)
  173. break
  174. else:
  175. return None
  176. else:
  177. # an alias
  178. for i in self._aliases[arg]:
  179. hashurl = urllib.parse.urlparse(i)
  180. if hashurl.scheme == 'hash':
  181. break
  182. else:
  183. raise ValueError('unable to find bash hash url for alias %s' % repr(arg))
  184. ms = ModuleSpec(fullname, self, is_package=False, loader_state=(hashurl,))
  185. return ms
  186. def invalidate_caches(self):
  187. return None
  188. # Loader methods
  189. def exec_module(self, module):
  190. if module.__name__ == 'cas':
  191. pass
  192. else:
  193. (url,) = module.__spec__.loader_state
  194. for load in self._loaders:
  195. try:
  196. data = load.fetch_data(url)
  197. break
  198. except:
  199. pass
  200. else:
  201. raise ValueError('unable to find loader for url %s' % repr(urllib.parse.urlunparse(url)))
  202. exec(data, module.__dict__)
  203. def defaultinit(casf):
  204. cachedir = pathlib.Path.home() / '.casimport_cache'
  205. cachedir.mkdir(exist_ok=True)
  206. casf.register(FileDirCAS(cachedir))
  207. # The global version
  208. _casfinder = CASFinder()
  209. load_aliases = _casfinder.load_aliases
  210. defaultinit(_casfinder)
  211. import unittest
  212. class TestHelpers(unittest.TestCase):
  213. def test_testset(self):
  214. origobj = object()
  215. d = dict(a=origobj, b=10)
  216. # that when we temporarily set it
  217. with tempset(d, 'a', 15):
  218. # the new value is there
  219. self.assertEqual(d['a'], 15)
  220. # and that the original object is restored
  221. self.assertIs(d['a'], origobj)
  222. def test_testattrset(self):
  223. class TestObj(object):
  224. pass
  225. testobj = TestObj()
  226. # that when we temporarily set it
  227. with tempattrset(testobj, 'a', 15):
  228. # the new value is there
  229. self.assertEqual(testobj.a, 15)
  230. # and that there is no object
  231. self.assertFalse(hasattr(testobj, 'a'))
  232. origobj = object()
  233. newobj = object()
  234. testobj.b = origobj
  235. # that when we temporarily set it
  236. with tempattrset(testobj, 'b', newobj):
  237. # the new value is there
  238. self.assertIs(testobj.b, newobj)
  239. # and the original value is restored
  240. self.assertIs(testobj.b, origobj)
  241. class Test(unittest.TestCase):
  242. def setUp(self):
  243. # clear out the default casfinder if there is one
  244. self.old_meta_path = sys.meta_path
  245. sys.meta_path = [ x for x in sys.meta_path if not isinstance(x, CASFinder) ]
  246. # setup temporary directory
  247. d = pathlib.Path(os.path.realpath(tempfile.mkdtemp()))
  248. self.basetempdir = d
  249. self.tempdir = d / 'subdir'
  250. self.tempdir.mkdir()
  251. self.fixtures = pathlib.Path(__file__).parent.parent / 'fixtures'
  252. def tearDown(self):
  253. # restore environment
  254. sys.meta_path = self.old_meta_path
  255. importlib.invalidate_caches()
  256. # clean up sys.modules
  257. [ sys.modules.pop(x) for x in list(sys.modules.keys()) if
  258. x == 'cas' or x.startswith('cas.') ]
  259. shutil.rmtree(self.basetempdir)
  260. self.tempdir = None
  261. def test_filedircas_limit_refresh(self):
  262. # XXX - only refresh when the dir has changed, and each
  263. # file has changed
  264. pass
  265. def test_casimport(self):
  266. # That a CASFinder
  267. f = CASFinder()
  268. # make sure that we can't import anything at first
  269. with self.assertRaises(ImportError):
  270. import cas.v1_f_2398472398
  271. # when registering the fixtures directory
  272. f.register(FileDirCAS(self.fixtures))
  273. # can import the function
  274. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  275. name = 'Olof'
  276. # and run the code
  277. self.assertEqual(hello(name), 'hello ' + name)
  278. # and when finished, can disconnect
  279. f.disconnect()
  280. # and is no longer in the meta_path
  281. self.assertNotIn(f, sys.meta_path)
  282. # and when disconnected as second time, nothing happens
  283. f.disconnect()
  284. def test_defaultinit(self):
  285. temphome = self.tempdir / 'home'
  286. temphome.mkdir()
  287. cachedir = temphome / '.casimport_cache'
  288. with tempset(os.environ, 'HOME', str(temphome)):
  289. with CASFinder() as f:
  290. # Setup the defaults
  291. defaultinit(f)
  292. # that the cache got created
  293. self.assertTrue(cachedir.is_dir())
  294. # and that when hello.py is copied to the cache
  295. shutil.copy(self.fixtures / 'hello.py', cachedir)
  296. # it can be imported
  297. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  298. with CASFinder() as f:
  299. defaultinit(f)
  300. # and that a new CASFinder can still find it
  301. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  302. def test_multiplecas(self):
  303. # that once we have one
  304. with CASFinder() as f:
  305. # if we try to create a second, it fails
  306. self.assertRaises(RuntimeError, CASFinder)
  307. def test_parsealiases(self):
  308. with open(self.fixtures / 'randpkg' / 'cas_aliases.txt') as fp:
  309. aliasdata = fp.read()
  310. res = CASFinder._parsealiases(aliasdata)
  311. self.assertEqual(res, {
  312. 'hello': [
  313. 'hash://sha256/330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3?type=text/x-python',
  314. 'ipfs://bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym',
  315. ]
  316. })
  317. def test_aliasimports(self):
  318. # setup the cache
  319. temphome = self.tempdir / 'home'
  320. temphome.mkdir()
  321. cachedir = temphome / '.casimport_cache'
  322. # add the test module's path
  323. fixdir = str(self.fixtures)
  324. sys.path.append(fixdir)
  325. with tempset(os.environ, 'HOME', str(temphome)):
  326. try:
  327. with CASFinder() as f, \
  328. tempattrset(sys.modules[__name__], 'load_aliases',
  329. f.load_aliases):
  330. defaultinit(f)
  331. # and that hello.py is in the cache
  332. shutil.copy(self.fixtures / 'hello.py', cachedir)
  333. # that the import is successful
  334. import randpkg
  335. # and pulled in the method
  336. self.assertTrue(hasattr(randpkg, 'hello'))
  337. finally:
  338. sys.path.remove(fixdir)
  339. def test_overlappingaliases(self):
  340. # make sure that an aliases file is consistent and does not
  341. # override other urls. That is that any hashes are consistent,
  342. # and that they have at least one root hash that is the same, and
  343. # will be used for fetching.
  344. #
  345. # Likely will also have to deal w/ an issue where two aliases share
  346. # sha256, and a third shares sha512, which in this case, BOTH hashse
  347. # have to be checked.
  348. pass
  349. def test_loaderpriority(self):
  350. # XXX - write test to allow you to specify the priority of
  351. # a loader, to ensure that cache stays at top.
  352. # Maybe also think of a way to say local/remote, because
  353. # some loaders may be "more local" than others, like using
  354. # a local ipfs gateway makes more sense than hitting a
  355. # public gateway
  356. pass