-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.py
executable file
·71 lines (62 loc) · 2.67 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""Simple Service that acts as a flatfile database"""
from service import Service
from message import Database_Message
import hash_util
from threading import Lock
from globals import *
class Database(Service):
"""docstring for Database"""
def __init__(self, message_router, root_directory):
super(Database, self).__init__()
self.message_router = message_router # should be in base class used by all services
self.service_id = SERVICE_DATABASE
message_router.register_service(self.service_id, self)
self.root_directory = root_directory
self.write_lock = Lock()
def handle_message(self, msg):
if not msg.service == self.service_id:
raise Exception("Mismatched service recipient for message.")
def lookup_record(self,hash_name):
try:
print "looking up:"+hash_name
path = self.root_directory+"/"+hash_name
##figure out what exceptions can go horribly wrong here
record_file = file(path,"r")
content = record_file.read()
record_file.close()
return content
except IOError:
return "404 Error"
def write_record(self,hash_name, file_contents):
self.write_lock.acquire()
print "writing record"
path = self.root_directory+"/"+hash_name
record_file= file(path,"w+")
record_file.write(file_contents)
record_file.close()
self.write_lock.release()
def handle_message(self, msg):
if not msg.service == self.service_id:
return False
if msg.type == "GET":
filename = str(msg.destination_key)
content = self.lookup_record(str(filename))
#this add other instances of database messages are borked
return_service = msg.get_content("service")
newmsg = Database_Message(self.owner, msg.reply_to.key, return_service, "RESP")
newmsg.add_content("file_contents",content)
self.send_message(newmsg, msg.reply_to)
if msg.type == "PUT":
filename = str(msg.destination_key)
self.write_record(filename, msg.get_content("file_contents"))
if msg.type == "RESP":
print msg.get_content("file_contents")
def put_record(self,name,data):
hash_loc = hash_util.hash_str(name)
newmsg = Database_Message(self.owner,hash_loc,"DATABASE","PUT")
newmsg.add_content("file_contents",data)
self.send_message(newmsg)
def get_record(self,name):
hash_loc = hash_util.hash_str(name)
newmsg = Database_Message(self.owner,hash_loc,"ECHO","GET")
self.send_message(newmsg)