From 58368be23587f5a6ed21d07a2bf3cd54d6ef13d1 Mon Sep 17 00:00:00 2001 From: karim hamidou Date: Fri, 2 May 2014 20:00:25 +0200 Subject: [PATCH] replaced my bug-ridden ad-hoc json file db by leveldb --- manifests/default.pp | 2 +- src/back/kite/cabinet.py | 66 +++++++++++++++++++++++++++++++++++ src/back/kite/filterdaemon.py | 40 ++++++++------------- src/back/kite/jsonfile.py | 61 -------------------------------- src/back/kite/server.py | 26 +++++++++----- src/back/kite/utils.py | 26 +++++++++++++- 6 files changed, 124 insertions(+), 97 deletions(-) create mode 100644 src/back/kite/cabinet.py delete mode 100644 src/back/kite/jsonfile.py diff --git a/manifests/default.pp b/manifests/default.pp index ccbb325..cf97a8d 100644 --- a/manifests/default.pp +++ b/manifests/default.pp @@ -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 index 0000000..c0859d2 --- /dev/null +++ b/src/back/kite/cabinet.py @@ -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) diff --git a/src/back/kite/filterdaemon.py b/src/back/kite/filterdaemon.py index 9140121..1b49d62 100755 --- a/src/back/kite/filterdaemon.py +++ b/src/back/kite/filterdaemon.py @@ -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 index 92949dc..0000000 --- a/src/back/kite/jsonfile.py +++ /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) diff --git a/src/back/kite/server.py b/src/back/kite/server.py index 8efe171..f87b0e2 100755 --- a/src/back/kite/server.py +++ b/src/back/kite/server.py @@ -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//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//mail/') 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" diff --git a/src/back/kite/utils.py b/src/back/kite/utils.py index 3aa32c8..513be2e 100644 --- a/src/back/kite/utils.py +++ b/src/back/kite/utils.py @@ -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 -- 2.43.0