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.

614 lines
16 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 functools
  26. import glob
  27. import hashlib
  28. import importlib.resources
  29. import mock
  30. import os.path
  31. import pathlib
  32. import shutil
  33. import sys
  34. import tempfile
  35. import urllib.request
  36. from importlib.abc import MetaPathFinder, Loader
  37. from importlib.machinery import ModuleSpec
  38. def _printanyexc(f): # pragma: no cover
  39. '''Prints any exception that gets raised by the wrapped function.'''
  40. @functools.wraps(f)
  41. def wrapper(*args, **kwargs):
  42. try:
  43. return f(*args, **kwargs)
  44. except Exception:
  45. import traceback
  46. traceback.print_exc()
  47. raise
  48. return wrapper
  49. @contextlib.contextmanager
  50. def tempset(obj, key, value):
  51. '''A context (with) manager for changing the value of an item in a
  52. dictionary, and restoring it after the with block.
  53. Example usage:
  54. ```
  55. d = dict(a=5, b=10)
  56. with tempset(d, 'a', 15):
  57. print(repr(d['a'])
  58. print(repr(d['a'])
  59. ```
  60. '''
  61. try:
  62. oldvalue = obj[key]
  63. obj[key] = value
  64. yield
  65. finally:
  66. obj[key] = oldvalue
  67. @contextlib.contextmanager
  68. def tempattrset(obj, key, value):
  69. '''A context (with) manager for changing the value of an attribute
  70. of an object, and restoring it after the with block.
  71. If the attribute does not exist, it will be deleted afterward.
  72. Example usage:
  73. ```
  74. with tempattrset(someobj, 'a', 15):
  75. print(repr(someobj.a)
  76. print(repr(someobj.a)
  77. ```
  78. '''
  79. try:
  80. dodelattr = False
  81. if hasattr(obj, key):
  82. oldvalue = getattr(obj, key)
  83. else:
  84. dodelattr = True
  85. setattr(obj, key, value)
  86. yield
  87. finally:
  88. if not dodelattr:
  89. setattr(obj, key, oldvalue)
  90. else:
  91. delattr(obj, key)
  92. class IPFSCAS(object):
  93. gwhost = 'gateway.ipfs.io'
  94. gwhost = 'cloudflare-ipfs.com'
  95. def make_url(self, url):
  96. return urllib.parse.urlunparse(('https', self.gwhost,
  97. '/ipfs/' + url.netloc) + ('', ) * 3)
  98. def fetch_data(self, url):
  99. if url.scheme != 'ipfs':
  100. raise ValueError('cannot handle scheme %s' %
  101. repr(url.scheme))
  102. gwurl = self.make_url(url)
  103. with urllib.request.urlopen(gwurl) as req:
  104. if req.status // 100 != 2:
  105. raise RuntimeError('bad fetch')
  106. return req.read()
  107. class FileDirCAS(object):
  108. '''A file loader for CAS that operates on a directory. It looks
  109. at files, caches their hash, and loads them upon request.'''
  110. def __init__(self, path):
  111. self._path = pathlib.Path(path)
  112. self._hashes = {}
  113. def refresh_dir(self):
  114. '''Internal method to refresh the internal cache of
  115. hashes.'''
  116. for i in glob.glob(os.path.join(self._path, '*.py')):
  117. _, hash = self.read_hash_file(i)
  118. self._hashes[hash] = i
  119. @staticmethod
  120. def read_hash_file(fname):
  121. '''Helper function that will read the file at fname, and
  122. return the tuple of it's contents and it's hash.'''
  123. with open(fname, 'rb') as fp:
  124. data = fp.read()
  125. hash = hashlib.sha256(data).hexdigest()
  126. return data, hash
  127. def is_package(self, hash):
  128. '''Decode the provided hash, and decide if it's a package
  129. or not.'''
  130. return False
  131. def fetch_data(self, url):
  132. '''Given the URL (must be a hash URL), return the code for
  133. it.'''
  134. self.refresh_dir()
  135. hashurl = url
  136. if hashurl.scheme != 'hash' or hashurl.netloc != 'sha256':
  137. raise ValueError('invalid hash url')
  138. hash = hashurl.path[1:]
  139. fname = self._hashes[hash]
  140. data, fhash = self.read_hash_file(fname)
  141. if fhash != hash:
  142. raise ValueError('file no longer matches hash on disk')
  143. return data
  144. class CASFinder(MetaPathFinder, Loader):
  145. '''Overall class for using Content Addressable Storage to load
  146. Python modules into your code. It contains code to dispatch to
  147. the various loaders to attempt to load the hash.'''
  148. def __init__(self):
  149. self._loaders = []
  150. self._aliases = {}
  151. if [ x for x in sys.meta_path if
  152. isinstance(x, self.__class__) ]:
  153. raise RuntimeError(
  154. 'cannot register more than on CASFinder')
  155. sys.meta_path.append(self)
  156. def __enter__(self):
  157. return self
  158. def __exit__(self, exc_type, exc_value, traceback):
  159. self.disconnect()
  160. def load_mod_aliases(self, name):
  161. '''Load the aliases from the module with the passed in name.'''
  162. aliases = importlib.resources.read_text(sys.modules[name],
  163. 'cas_aliases.txt')
  164. self._aliases.update(self._parsealiases(aliases))
  165. @staticmethod
  166. def _makebasichashurl(url):
  167. try:
  168. hashurl = urllib.parse.urlparse(url)
  169. except AttributeError:
  170. hashurl = url
  171. return urllib.parse.urlunparse(hashurl[:3] + ('', '', ''))
  172. @classmethod
  173. def _parsealiases(cls, data):
  174. ret = {}
  175. lines = data.split('\n')
  176. for i in lines:
  177. if not i:
  178. continue
  179. name, hash = i.split()
  180. ret.setdefault(name, []).append(hash)
  181. # split out the hashes
  182. for items in list(ret.values()):
  183. lst = [ x for x in items if
  184. not x.startswith('hash://') ]
  185. for h in [ x for x in items if
  186. x.startswith('hash://') ]:
  187. h = cls._makebasichashurl(h)
  188. ret[h] = lst
  189. return ret
  190. def disconnect(self):
  191. '''Disconnect this Finder from being used to load modules.
  192. As this claims an entire namespace, only the first loaded
  193. one will work, and any others will be hidden until the
  194. first one is disconnected.
  195. This can be used w/ a with block to automatically
  196. disconnect when no longer needed. This is mostly useful
  197. for testing.'''
  198. try:
  199. sys.meta_path.remove(self)
  200. except ValueError:
  201. pass
  202. def register(self, loader):
  203. '''Register a loader w/ this finder. This will attempt
  204. to load the hash passed to it. It is also (currently)
  205. responsible for executing the code in the module.'''
  206. self._loaders.append(loader)
  207. # MetaPathFinder methods
  208. def find_spec(self, fullname, path, target=None):
  209. if path is None:
  210. ms = ModuleSpec(fullname, self, is_package=True)
  211. else:
  212. parts = fullname.split('.')
  213. ver, typ, arg = parts[1].split('_')
  214. if typ == 'f':
  215. # make hash url:
  216. hashurl = ('hash://sha256/%s' %
  217. bytes.fromhex(arg).hex())
  218. hashurl = urllib.parse.urlparse(hashurl)
  219. for l in self._loaders:
  220. ispkg = l.is_package(hashurl)
  221. break
  222. else:
  223. return None
  224. else:
  225. # an alias
  226. for i in self._aliases[arg]:
  227. hashurl = urllib.parse.urlparse(i)
  228. if hashurl.scheme == 'hash':
  229. break
  230. else:
  231. raise ValueError('unable to find bash hash url for alias %s' % repr(arg))
  232. ms = ModuleSpec(fullname, self, is_package=False,
  233. loader_state=(hashurl,))
  234. return ms
  235. def invalidate_caches(self):
  236. return None
  237. # Loader methods
  238. def exec_module(self, module):
  239. if module.__name__ == 'cas':
  240. pass
  241. else:
  242. (url,) = module.__spec__.loader_state
  243. for load in self._loaders:
  244. try:
  245. data = load.fetch_data(url)
  246. break
  247. except Exception:
  248. pass
  249. else:
  250. for url in self._aliases[
  251. self._makebasichashurl(url)]:
  252. url = urllib.parse.urlparse(url)
  253. for load in self._loaders:
  254. try:
  255. data = load.fetch_data(url)
  256. break
  257. except Exception:
  258. pass
  259. else:
  260. continue
  261. break
  262. else:
  263. raise ValueError('unable to find loader for url %s' % repr(urllib.parse.urlunparse(url)))
  264. exec(data, module.__dict__)
  265. def defaultinit(casf):
  266. cachedir = pathlib.Path.home() / '.casimport_cache'
  267. cachedir.mkdir(exist_ok=True)
  268. casf.register(FileDirCAS(cachedir))
  269. casf.register(IPFSCAS())
  270. # The global version
  271. _casfinder = CASFinder()
  272. load_mod_aliases = _casfinder.load_mod_aliases
  273. defaultinit(_casfinder)
  274. import unittest
  275. class TestHelpers(unittest.TestCase):
  276. def test_testset(self):
  277. origobj = object()
  278. d = dict(a=origobj, b=10)
  279. # that when we temporarily set it
  280. with tempset(d, 'a', 15):
  281. # the new value is there
  282. self.assertEqual(d['a'], 15)
  283. # and that the original object is restored
  284. self.assertIs(d['a'], origobj)
  285. def test_testattrset(self):
  286. class TestObj(object):
  287. pass
  288. testobj = TestObj()
  289. # that when we temporarily set it
  290. with tempattrset(testobj, 'a', 15):
  291. # the new value is there
  292. self.assertEqual(testobj.a, 15)
  293. # and that there is no object
  294. self.assertFalse(hasattr(testobj, 'a'))
  295. origobj = object()
  296. newobj = object()
  297. testobj.b = origobj
  298. # that when we temporarily set it
  299. with tempattrset(testobj, 'b', newobj):
  300. # the new value is there
  301. self.assertIs(testobj.b, newobj)
  302. # and the original value is restored
  303. self.assertIs(testobj.b, origobj)
  304. class Test(unittest.TestCase):
  305. def setUp(self):
  306. # clear out the default casfinder if there is one
  307. self.old_meta_path = sys.meta_path
  308. sys.meta_path = [ x for x in sys.meta_path if
  309. not isinstance(x, CASFinder) ]
  310. # setup temporary directory
  311. d = pathlib.Path(os.path.realpath(tempfile.mkdtemp()))
  312. self.basetempdir = d
  313. self.tempdir = d / 'subdir'
  314. self.tempdir.mkdir()
  315. self.fixtures = \
  316. pathlib.Path(__file__).parent.parent / 'fixtures'
  317. def tearDown(self):
  318. # restore environment
  319. sys.meta_path = self.old_meta_path
  320. importlib.invalidate_caches()
  321. # clean up sys.modules
  322. [ sys.modules.pop(x) for x in list(sys.modules.keys()) if
  323. x == 'cas' or x.startswith('cas.') ]
  324. shutil.rmtree(self.basetempdir)
  325. self.tempdir = None
  326. def test_filedircas_limit_refresh(self):
  327. # XXX - only refresh when the dir has changed, and each
  328. # file has changed
  329. pass
  330. def test_casimport(self):
  331. # That a CASFinder
  332. f = CASFinder()
  333. # make sure that we can't import anything at first
  334. with self.assertRaises(ImportError):
  335. import cas.v1_f_2398472398
  336. # when registering the fixtures directory
  337. f.register(FileDirCAS(self.fixtures))
  338. # can import the function
  339. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  340. name = 'Olof'
  341. # and run the code
  342. self.assertEqual(hello(name), 'hello ' + name)
  343. # and when finished, can disconnect
  344. f.disconnect()
  345. # and is no longer in the meta_path
  346. self.assertNotIn(f, sys.meta_path)
  347. # and when disconnected as second time, nothing happens
  348. f.disconnect()
  349. def test_defaultinit(self):
  350. temphome = self.tempdir / 'home'
  351. temphome.mkdir()
  352. cachedir = temphome / '.casimport_cache'
  353. with tempset(os.environ, 'HOME', str(temphome)):
  354. with CASFinder() as f:
  355. # Setup the defaults
  356. defaultinit(f)
  357. # that the cache got created
  358. self.assertTrue(cachedir.is_dir())
  359. # and that when hello.py is copied to the cache
  360. shutil.copy(self.fixtures / 'hello.py', cachedir)
  361. # it can be imported
  362. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  363. # and that the last loader is the IPFSCAS
  364. self.assertIsInstance(f._loaders[-1], IPFSCAS)
  365. with CASFinder() as f:
  366. defaultinit(f)
  367. # and that a new CASFinder can still find it
  368. from cas.v1_f_330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3 import hello
  369. def test_multiplecas(self):
  370. # that once we have one
  371. with CASFinder() as f:
  372. # if we try to create a second, it fails
  373. self.assertRaises(RuntimeError, CASFinder)
  374. def test_parsealiases(self):
  375. with open(self.fixtures / 'randpkg' / 'cas_aliases.txt') as fp:
  376. aliasdata = fp.read()
  377. res = CASFinder._parsealiases(aliasdata)
  378. self.assertEqual(res, {
  379. 'hello': [
  380. 'hash://sha256/330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3?type=text/x-python',
  381. 'ipfs://bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym',
  382. ],
  383. 'hash://sha256/330884aa2febb5e19fb7194ec6a69ed11dd3d77122f1a5175ee93e73cf0161c3': [
  384. 'ipfs://bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym',
  385. ],
  386. })
  387. def test_aliasimports(self):
  388. # setup the cache
  389. temphome = self.tempdir / 'home'
  390. temphome.mkdir()
  391. cachedir = temphome / '.casimport_cache'
  392. # add the test module's path
  393. fixdir = str(self.fixtures)
  394. sys.path.append(fixdir)
  395. with tempset(os.environ, 'HOME', str(temphome)):
  396. try:
  397. with CASFinder() as f, \
  398. tempattrset(sys.modules[__name__],
  399. 'load_mod_aliases', f.load_mod_aliases):
  400. defaultinit(f)
  401. # and that hello.py is in the cache
  402. shutil.copy(self.fixtures / 'hello.py',
  403. cachedir)
  404. # that the import is successful
  405. import randpkg
  406. # and pulled in the method
  407. self.assertTrue(hasattr(randpkg, 'hello'))
  408. del sys.modules['randpkg']
  409. finally:
  410. sys.path.remove(fixdir)
  411. def test_aliasipfsimports(self):
  412. # add the test module's path
  413. fixdir = str(self.fixtures)
  414. sys.path.append(fixdir)
  415. # that a fake ipfsloader
  416. with open(self.fixtures / 'hello.py') as fp:
  417. # that returns the correct data
  418. fakedata = fp.read()
  419. def fakeload(url, fd=fakedata):
  420. if url.scheme != 'ipfs' or url.netloc != 'bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym':
  421. raise ValueError
  422. return fd
  423. fakeipfsloader = mock.MagicMock()
  424. fakeipfsloader.fetch_data = fakeload
  425. try:
  426. with CASFinder() as f, \
  427. tempattrset(sys.modules[__name__], 'load_mod_aliases',
  428. f.load_mod_aliases):
  429. f.register(fakeipfsloader)
  430. # that the import is successful
  431. import randpkg
  432. # and pulled in the method
  433. self.assertTrue(hasattr(randpkg, 'hello'))
  434. finally:
  435. sys.path.remove(fixdir)
  436. @mock.patch('urllib.request.urlopen')
  437. def test_ipfscasloader(self, uomock):
  438. # prep return test data
  439. with open(self.fixtures / 'hello.py') as fp:
  440. # that returns the correct data
  441. ipfsdata = fp.read()
  442. # that the ipfs CAS loader
  443. ipfs = IPFSCAS()
  444. # that the request is successfull
  445. uomock.return_value.__enter__.return_value.status = 200
  446. # and returns the correct data
  447. uomock.return_value.__enter__.return_value.read.return_value = ipfsdata
  448. # that when called
  449. hashurl = urllib.parse.urlparse('ipfs://bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym')
  450. data = ipfs.fetch_data(hashurl)
  451. # it opens the correct url
  452. uomock.assert_called_with('https://cloudflare-ipfs.com/ipfs/bafkreibtbcckul7lwxqz7nyzj3dknhwrdxj5o4jc6gsroxxjhzz46albym')
  453. # and returns the correct data
  454. self.assertEqual(data, ipfsdata)
  455. with self.assertRaises(ValueError):
  456. # that a hash url fails
  457. ipfs.fetch_data(urllib.parse.urlparse('hash://sha256/asldfkj'))
  458. # that when the request fails
  459. uomock.return_value.__enter__.return_value.status = 400
  460. # it raises a RuntimeError
  461. with self.assertRaises(RuntimeError):
  462. ipfs.fetch_data(hashurl)
  463. def test_overlappingaliases(self):
  464. # make sure that an aliases file is consistent and does not
  465. # override other urls. That is that any hashes are
  466. # consistent, and that they have at least one root hash that
  467. # is the same, and will be used for fetching.
  468. #
  469. # Likely will also have to deal w/ an issue where two
  470. # aliases share sha256, and a third shares sha512, which in
  471. # this case, BOTH hashse have to be checked.
  472. pass
  473. def test_loaderpriority(self):
  474. # XXX - write test to allow you to specify the priority of
  475. # a loader, to ensure that cache stays at top.
  476. # Maybe also think of a way to say local/remote, because
  477. # some loaders may be "more local" than others, like using
  478. # a local ipfs gateway makes more sense than hitting a
  479. # public gateway
  480. pass