pickleshare.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. #!/usr/bin/env python
  2. """ PickleShare - a small 'shelve' like datastore with concurrency support
  3. Like shelve, a PickleShareDB object acts like a normal dictionary. Unlike
  4. shelve, many processes can access the database simultaneously. Changing a
  5. value in database is immediately visible to other processes accessing the
  6. same database.
  7. Concurrency is possible because the values are stored in separate files. Hence
  8. the "database" is a directory where *all* files are governed by PickleShare.
  9. Example usage::
  10. from pickleshare import *
  11. db = PickleShareDB('~/testpickleshare')
  12. db.clear()
  13. print "Should be empty:",db.items()
  14. db['hello'] = 15
  15. db['aku ankka'] = [1,2,313]
  16. db['paths/are/ok/key'] = [1,(5,46)]
  17. print db.keys()
  18. del db['aku ankka']
  19. This module is certainly not ZODB, but can be used for low-load
  20. (non-mission-critical) situations where tiny code size trumps the
  21. advanced features of a "real" object database.
  22. Installation guide: pip install path pickleshare
  23. Author: Ville Vainio <vivainio@gmail.com>
  24. License: MIT open source license.
  25. """
  26. from __future__ import print_function
  27. __version__ = "0.7.4"
  28. try:
  29. from pathlib import Path
  30. except ImportError:
  31. # Python 2 backport
  32. from pathlib2 import Path
  33. import os,stat,time
  34. import collections
  35. try:
  36. import cPickle as pickle
  37. except ImportError:
  38. import pickle
  39. import errno
  40. import sys
  41. if sys.version_info[0] >= 3:
  42. string_types = (str,)
  43. else:
  44. string_types = (str, unicode)
  45. def gethashfile(key):
  46. return ("%02x" % abs(hash(key) % 256))[-2:]
  47. _sentinel = object()
  48. class PickleShareDB(collections.MutableMapping):
  49. """ The main 'connection' object for PickleShare database """
  50. def __init__(self,root):
  51. """ Return a db object that will manage the specied directory"""
  52. if not isinstance(root, string_types):
  53. root = str(root)
  54. root = os.path.abspath(os.path.expanduser(root))
  55. self.root = Path(root)
  56. if not self.root.is_dir():
  57. # catching the exception is necessary if multiple processes are concurrently trying to create a folder
  58. # exists_ok keyword argument of mkdir does the same but only from Python 3.5
  59. try:
  60. self.root.mkdir(parents=True)
  61. except OSError as e:
  62. if e.errno != errno.EEXIST:
  63. raise
  64. # cache has { 'key' : (obj, orig_mod_time) }
  65. self.cache = {}
  66. def __getitem__(self,key):
  67. """ db['key'] reading """
  68. fil = self.root / key
  69. try:
  70. mtime = (fil.stat()[stat.ST_MTIME])
  71. except OSError:
  72. raise KeyError(key)
  73. if fil in self.cache and mtime == self.cache[fil][1]:
  74. return self.cache[fil][0]
  75. try:
  76. # The cached item has expired, need to read
  77. with fil.open("rb") as f:
  78. obj = pickle.loads(f.read())
  79. except:
  80. raise KeyError(key)
  81. self.cache[fil] = (obj,mtime)
  82. return obj
  83. def __setitem__(self,key,value):
  84. """ db['key'] = 5 """
  85. fil = self.root / key
  86. parent = fil.parent
  87. if parent and not parent.is_dir():
  88. parent.mkdir(parents=True)
  89. # We specify protocol 2, so that we can mostly go between Python 2
  90. # and Python 3. We can upgrade to protocol 3 when Python 2 is obsolete.
  91. with fil.open('wb') as f:
  92. pickle.dump(value, f, protocol=2)
  93. try:
  94. self.cache[fil] = (value, fil.stat().st_mtime)
  95. except OSError as e:
  96. if e.errno != errno.ENOENT:
  97. raise
  98. def hset(self, hashroot, key, value):
  99. """ hashed set """
  100. hroot = self.root / hashroot
  101. if not hroot.is_dir():
  102. hroot.mkdir()
  103. hfile = hroot / gethashfile(key)
  104. d = self.get(hfile, {})
  105. d.update( {key : value})
  106. self[hfile] = d
  107. def hget(self, hashroot, key, default = _sentinel, fast_only = True):
  108. """ hashed get """
  109. hroot = self.root / hashroot
  110. hfile = hroot / gethashfile(key)
  111. d = self.get(hfile, _sentinel )
  112. #print "got dict",d,"from",hfile
  113. if d is _sentinel:
  114. if fast_only:
  115. if default is _sentinel:
  116. raise KeyError(key)
  117. return default
  118. # slow mode ok, works even after hcompress()
  119. d = self.hdict(hashroot)
  120. return d.get(key, default)
  121. def hdict(self, hashroot):
  122. """ Get all data contained in hashed category 'hashroot' as dict """
  123. hfiles = self.keys(hashroot + "/*")
  124. hfiles.sort()
  125. last = len(hfiles) and hfiles[-1] or ''
  126. if last.endswith('xx'):
  127. # print "using xx"
  128. hfiles = [last] + hfiles[:-1]
  129. all = {}
  130. for f in hfiles:
  131. # print "using",f
  132. try:
  133. all.update(self[f])
  134. except KeyError:
  135. print("Corrupt",f,"deleted - hset is not threadsafe!")
  136. del self[f]
  137. self.uncache(f)
  138. return all
  139. def hcompress(self, hashroot):
  140. """ Compress category 'hashroot', so hset is fast again
  141. hget will fail if fast_only is True for compressed items (that were
  142. hset before hcompress).
  143. """
  144. hfiles = self.keys(hashroot + "/*")
  145. all = {}
  146. for f in hfiles:
  147. # print "using",f
  148. all.update(self[f])
  149. self.uncache(f)
  150. self[hashroot + '/xx'] = all
  151. for f in hfiles:
  152. p = self.root / f
  153. if p.name == 'xx':
  154. continue
  155. p.unlink()
  156. def __delitem__(self,key):
  157. """ del db["key"] """
  158. fil = self.root / key
  159. self.cache.pop(fil,None)
  160. try:
  161. fil.unlink()
  162. except OSError:
  163. # notfound and permission denied are ok - we
  164. # lost, the other process wins the conflict
  165. pass
  166. def _normalized(self, p):
  167. """ Make a key suitable for user's eyes """
  168. return str(p.relative_to(self.root)).replace('\\','/')
  169. def keys(self, globpat = None):
  170. """ All keys in DB, or all keys matching a glob"""
  171. if globpat is None:
  172. files = self.root.rglob('*')
  173. else:
  174. files = self.root.glob(globpat)
  175. return [self._normalized(p) for p in files if p.is_file()]
  176. def __iter__(self):
  177. return iter(self.keys())
  178. def __len__(self):
  179. return len(self.keys())
  180. def uncache(self,*items):
  181. """ Removes all, or specified items from cache
  182. Use this after reading a large amount of large objects
  183. to free up memory, when you won't be needing the objects
  184. for a while.
  185. """
  186. if not items:
  187. self.cache = {}
  188. for it in items:
  189. self.cache.pop(it,None)
  190. def waitget(self,key, maxwaittime = 60 ):
  191. """ Wait (poll) for a key to get a value
  192. Will wait for `maxwaittime` seconds before raising a KeyError.
  193. The call exits normally if the `key` field in db gets a value
  194. within the timeout period.
  195. Use this for synchronizing different processes or for ensuring
  196. that an unfortunately timed "db['key'] = newvalue" operation
  197. in another process (which causes all 'get' operation to cause a
  198. KeyError for the duration of pickling) won't screw up your program
  199. logic.
  200. """
  201. wtimes = [0.2] * 3 + [0.5] * 2 + [1]
  202. tries = 0
  203. waited = 0
  204. while 1:
  205. try:
  206. val = self[key]
  207. return val
  208. except KeyError:
  209. pass
  210. if waited > maxwaittime:
  211. raise KeyError(key)
  212. time.sleep(wtimes[tries])
  213. waited+=wtimes[tries]
  214. if tries < len(wtimes) -1:
  215. tries+=1
  216. def getlink(self,folder):
  217. """ Get a convenient link for accessing items """
  218. return PickleShareLink(self, folder)
  219. def __repr__(self):
  220. return "PickleShareDB('%s')" % self.root
  221. class PickleShareLink:
  222. """ A shortdand for accessing nested PickleShare data conveniently.
  223. Created through PickleShareDB.getlink(), example::
  224. lnk = db.getlink('myobjects/test')
  225. lnk.foo = 2
  226. lnk.bar = lnk.foo + 5
  227. """
  228. def __init__(self, db, keydir ):
  229. self.__dict__.update(locals())
  230. def __getattr__(self,key):
  231. return self.__dict__['db'][self.__dict__['keydir']+'/' + key]
  232. def __setattr__(self,key,val):
  233. self.db[self.keydir+'/' + key] = val
  234. def __repr__(self):
  235. db = self.__dict__['db']
  236. keys = db.keys( self.__dict__['keydir'] +"/*")
  237. return "<PickleShareLink '%s': %s>" % (
  238. self.__dict__['keydir'],
  239. ";".join([Path(k).basename() for k in keys]))
  240. def main():
  241. import textwrap
  242. usage = textwrap.dedent("""\
  243. pickleshare - manage PickleShare databases
  244. Usage:
  245. pickleshare dump /path/to/db > dump.txt
  246. pickleshare load /path/to/db < dump.txt
  247. pickleshare test /path/to/db
  248. """)
  249. DB = PickleShareDB
  250. import sys
  251. if len(sys.argv) < 2:
  252. print(usage)
  253. return
  254. cmd = sys.argv[1]
  255. args = sys.argv[2:]
  256. if cmd == 'dump':
  257. if not args: args= ['.']
  258. db = DB(args[0])
  259. import pprint
  260. pprint.pprint(db.items())
  261. elif cmd == 'load':
  262. cont = sys.stdin.read()
  263. db = DB(args[0])
  264. data = eval(cont)
  265. db.clear()
  266. for k,v in db.items():
  267. db[k] = v
  268. elif cmd == 'testwait':
  269. db = DB(args[0])
  270. db.clear()
  271. print(db.waitget('250'))
  272. elif cmd == 'test':
  273. test()
  274. stress()
  275. if __name__== "__main__":
  276. main()