]> khamidou — GitHub mirrors - kite.git/commitdiff
replaced my bug-ridden ad-hoc json file db by leveldb
authorkarim hamidou <khamidou@gmail.com>
Fri, 2 May 2014 18:00:25 +0000 (20:00 +0200)
committerkarim hamidou <khamidou@gmail.com>
Fri, 2 May 2014 18:00:25 +0000 (20:00 +0200)
manifests/default.pp
src/back/kite/cabinet.py [new file with mode: 0644]
src/back/kite/filterdaemon.py
src/back/kite/jsonfile.py [deleted file]
src/back/kite/server.py
src/back/kite/utils.py

index ccbb325e95dc61db12e5d6a5093fb59a4657ed38..cf97a8d779d27d6d745fd50bdff41db5fb569dbc 100644 (file)
@@ -5,7 +5,7 @@ exec {"apt-get update":
 }
 
 $packages = ["python", "python-pip", "bpython", 
-             "mutt", "python-pyinotify", "mailutils"]
+             "mutt", "python-pyinotify", "mailutils", "python-leveldb"]
 
 $python_packages = ["python-dateutil"]
 
diff --git a/src/back/kite/cabinet.py b/src/back/kite/cabinet.py
new file mode 100644 (file)
index 0000000..c0859d2
--- /dev/null
@@ -0,0 +1,66 @@
+# A very thin layer over leveldb - it mostly serializes JSON back and forth.
+
+import leveldb
+import utils
+try:
+    import json
+except ImportError:
+    import simplejson as json
+
+
+class Cabinet(object):
+    """Persistent data storage using JSON and berkeley db"""
+    def __init__(self, filename, encoder=json.JSONEncoder, decoder=None, *args):
+        """Set up a Cabinet object.
+
+        The encoder parameter is the class that will be called by the json encoder to encode python objects.
+        decoder is a function which is called for each decoded object to apply special conversions.
+        For more informations, see :
+        http://docs.python.org/dev/library/json.html?highlight=json#encoders-and-decoders
+        """
+        self.filename = filename
+        self.cache = {}
+        self.encoder = encoder
+        self.decoder = decoder
+
+    def __getitem__(self, key):
+        if self.cache.has_key(key):
+            return self.cache[key]
+        else:
+            db = leveldb.LevelDB(self.filename)
+            val = db.Get(key)
+            del db
+            self.cache[key] = json.loads(val, object_hook=self.decoder)
+            return self.cache[key]
+
+    def __setitem__(self, key, item):
+        self.cache[key] = item
+
+    def __delitem__(self, key):
+        del self.cache[key]
+        db = leveldb.LevelDB(self.filename)
+        db.Delete(key)
+        del db
+
+    def __iter__(self):
+        return self.cache.iterkeys()
+
+    def __contains__(self, key):
+        if self.cache.has_key(key):
+            return True
+        else:
+            try:
+                db = leveldb.LevelDB(self.filename)
+                db.Get(key)
+                del db
+                return True
+            except KeyError:
+                return False
+
+    def sync(self):
+        db = leveldb.LevelDB(self.filename)
+        for key in self.cache:
+            db.Put(key, json.dumps(self.cache[key], cls=self.encoder))
+
+def DatetimeCabinet(path):
+    return Cabinet(path, encoder=utils.DatetimeEncoder, decoder=utils.deserialize_datetime)
index 91401210ce824d3646e709d3096e7459d1dc0f26..1b49d628aef670ecb0628a1fbc9ed4b774d7fc02 100755 (executable)
@@ -2,11 +2,6 @@
 # filterdaemon.py 
 # This background process creates indexes files for threads and filters.
 #
-# What is an index file ?
-# =======================
-#
-# An index file is a JSON list which holds the paths to files in a conversation.
-#
 
 import sys
 import os
@@ -19,7 +14,7 @@ import email.parser
 import threads
 import headers
 import users
-from jsonfile import JsonFile
+from cabinet import DatetimeCabinet
 import maildir
 
 # The architecture is pretty simple. This program is multithreaded.
@@ -61,21 +56,15 @@ class WatcherThread(threading.Thread):
         notifier.loop()
 
 class DumperThread(threading.Thread):
-    def __init__(self, path, threads_index_cache):
+    def __init__(self, path, threads_index):
         threading.Thread.__init__(self)
         self.path = path
-        self.threads_index_cache = threads_index_cache
+        self.threads_index = threads_index
 
     def run(self):
         while True:
             time.sleep(DUMPER_SLEEP_DURATION)
-            for user in self.threads_index_cache:
-                print "dumper " + user
-                if self.threads_index_cache[user]["dirty"]:
-                    print "Dumping threads index for user %s at location %s " % (user, self.threads_index_cache[user]["threads_index"].path)
-
-                    self.threads_index_cache[user]["threads_index"].save()
-                    self.threads_index_cache[user]["dirty"] = False
+            self.threads_index.sync()
             
 def process_new_email(path, threads_index):
     with open(path, "r") as fd:
@@ -113,10 +102,10 @@ def process_new_email(path, threads_index):
             threads_index.insert(0, thread)
 
 class ProcessorThread(threading.Thread):
-    def __init__(self, path, threads_index_cache):
+    def __init__(self, path, threads_index):
         threading.Thread.__init__(self)
         self.path = path
-        self.threads_index_cache = threads_index_cache
+        self.threads_index= threads_index
 
     def run(self):
         while True:
@@ -127,13 +116,12 @@ class ProcessorThread(threading.Thread):
                         username = users.get_username_from_folder(event["path"]) 
                         print "username: %s, path: %s\n" % (username, event["path"])
 
-                        if username not in self.threads_index_cache:
-                            threads_index = users.get_user_threads_index(event["path"])
-                            print "Getting threads_index for user : %s" % username
-                            self.threads_index_cache[username] = {"threads_index": threads_index, "dirty": True}
+                        if username not in self.threads_index:
+                            print "Setting threads_index for user : %s" % username
+                            self.threads_index[username] = {"threads_index": [], "dirty": True}
                         
-                        process_new_email(event["path"], self.threads_index_cache[username]["threads_index"].data)
-                        self.threads_index_cache[username]["dirty"] = True
+                        process_new_email(event["path"], self.threads_index[username]["threads_index"])
+                        self.threads_index[username]["dirty"] = True
                     except IOError as e:
                         # This may be a Postfix/Dovecot temporary file. Ignore it.
                         print "caught ioerror %s" % e.strerror
@@ -146,11 +134,11 @@ if __name__ == "__main__":
     path = sys.argv[1]
     print "Watching %s..." % path
 
-    threads_index_cache = {}
+    threads_index = DatetimeCabinet("/home/kite/threads.db")
 
     watcher_thread = WatcherThread(path)
-    processor_thread = ProcessorThread(path, threads_index_cache)
-    dumper_thread = DumperThread(path, threads_index_cache)
+    processor_thread = ProcessorThread(path, threads_index)
+    dumper_thread = DumperThread(path, threads_index)
 
     processor_thread.start()
     watcher_thread.start()
diff --git a/src/back/kite/jsonfile.py b/src/back/kite/jsonfile.py
deleted file mode 100644 (file)
index 92949dc..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-# serialize and deserialize to json.
-# reading and writing is locking
-import os
-import json
-import datetime
-import time
-import dateutil.parser
-import dateutil.tz
-from lockfile import FileLock
-
-class DatetimeEncoder(json.JSONEncoder):
-    def default(self, obj):
-        if isinstance(obj, datetime.datetime):
-            return obj.isoformat()
-
-        return json.JSONEncoder.default(self, obj)
-
-def deserialize_datetime(obj):
-    try:
-        obj['date'] = dateutil.parser.parse(obj['date'])
-    except KeyError:
-        pass
-    return obj
-
-class JsonFile(object):
-    def __init__(self, path=None):
-        self.path = path
-        self.data = None
-        self.refresh()
-
-    def refresh(self):
-        try:
-            if self.path != None:
-                with FileLock(self.path):
-                    fd = open(self.path, "r")
-                    self.data = json.load(fd, object_hook=deserialize_datetime)
-                    fd.close()
-        except IOError:
-            pass
-     
-    def save(self, path=None):
-        if path == None:
-            path = self.path
-
-        def save_proper():
-            with open(path, "w+") as fd:
-                json.dump(self.data, fd, cls=DatetimeEncoder)
-
-        # Lock the file only if it already exists
-        # FIXME: this is maybe a race condition
-        if os.path.exists(path):
-            with FileLock(path):
-                save_proper()
-        else:
-            save_proper()
-        
-def serialize_json(obj):
-    return json.dumps(obj, cls=DatetimeEncoder)
-
-def deserialize_json(string):
-    return json.loads(string, object_hook=deserialize_datetime)
index 8efe1712c31703f5bff39edda27f4fe08422ea6a..f87b0e2f923ac7f75afab6d3cba66e22243154db 100755 (executable)
@@ -1,23 +1,28 @@
 #!/usr/bin/env python
 import bottle
 import json
-import jsonfile
 import sys
-from jsonfile import JsonFile, serialize_json
+from cabinet import DatetimeCabinet
 from bottle import route, template, response, abort
 from maildir import *
+from utils import serialize_json
 
 @route('/kite/<user>/mail')
 def index(user):
             # FIXME: input sanitization - check permissions for user
             try:
-                threads_index = JsonFile("/home/kite/Maildirs/%s/threads_index.json" % user)
+                threads_index = DatetimeCabinet("/home/kite/threads.db")
             except IOError:
                 response.status = 400
                 return
 
             ret_threads = []
-            for thread in threads_index.data[-50:]:
+            try:
+                threads = threads_index[user]["threads_index"]
+            except KeyError:
+                threads = []
+             
+            for thread in threads:
                 ret_threads.append(thread)
 
             response.content_type = "application/json"
@@ -26,10 +31,15 @@ def index(user):
 @route('/kite/<user>/mail/<id>')
 def index(user, id):
             # FIXME: input sanitization check perms
-            threads_index = JsonFile("/home/kite/Maildirs/%s/threads_index.json" % user)
-            thread = None
+            try:
+                threads_index = DatetimeCabinet("/home/kite/threads.db")
+                thread = None
+            except IOError:
+                response.status = 400
+                return
 
-            for thr in threads_index.data:
+            # FIXME: use an index for threads entries ?
+            for thr in threads_index[user]["threads_index"]:
                 if thr["id"] == id:
                     thread = thr
 
@@ -37,7 +47,7 @@ def index(user, id):
                 abort(404, "Thread not found.")
 
             thr["unread"] = False
-            threads_index.save() # FIXME: race condition here
+            threads_index.sync()
 
             response.content_type = "application/json"
 
index 3aa32c861d76a5220d8ac140d6c6329f89051d4c..513be2e4ebac7f549f8d499a19ce0c33b633b75e 100644 (file)
@@ -1,4 +1,28 @@
 # utils.py : various utilities
-
 import os
+import json
+import datetime
+import time
+import dateutil.parser
+import dateutil.tz
+
+
+class DatetimeEncoder(json.JSONEncoder):
+    def default(self, obj):
+        if isinstance(obj, datetime.datetime):
+            return obj.isoformat()
+
+        return json.JSONEncoder.default(self, obj)
+
+def serialize_json(obj):
+    return json.dumps(obj, cls=DatetimeEncoder)
+
+def deserialize_json(string):
+    return json.loads(string, object_hook=deserialize_datetime)
 
+def deserialize_datetime(obj):
+    try:
+        obj['date'] = dateutil.parser.parse(obj['date'])
+    except KeyError:
+        pass
+    return obj