-
Notifications
You must be signed in to change notification settings - Fork 0
/
keystore.py
81 lines (65 loc) · 2.2 KB
/
keystore.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
72
73
74
75
76
77
78
79
80
import sys
import httplib
import urllib
# TODO: read this from a config file
servers = ["localhost:8000"]
def usage():
print "Usage: keystore get <key> [servers]"
print " keystore set <key> <value> [servers]"
sys.exit()
class KeyStore:
def lookup_key(self, key):
num_servers = len(servers)
# compute an index given a the key hash
index = hash(key) % num_servers
print "Using server# ", index
conn = httplib.HTTPConnection(servers[index])
conn.request("GET", key)
resp = conn.getresponse()
if resp.status == 200 and resp.reason == "OK":
value = resp.read()
return value
else:
print "Could not read data from key store server"
return None
def set_key(self, key, value):
num_servers = len(servers)
# compute an index given a the key hash
index = hash(key) % num_servers
print "Using server# ", index
conn = httplib.HTTPConnection(servers[index])
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
params = urllib.urlencode({key: value})
conn.request("POST", "/", params, headers)
resp = conn.getresponse()
if resp.status == 200 and resp.reason == "OK":
pass
else:
print "Could not add value to server"
if len(sys.argv) < 3 or len(sys.argv) > 5:
usage()
key_store = KeyStore()
if sys.argv[1] == "get":
if len(sys.argv) <> 3 and len(sys.argv) <> 4:
usage()
if len(sys.argv) == 4:
# get server list from command line
servers = sys.argv[3].split(",")
key = sys.argv[2]
print "Lookup key: ", key
value = key_store.lookup_key(key)
if value == None:
print "Key not found"
else:
print "Found value: ", value
elif sys.argv[1] == "set":
if len(sys.argv) <> 4 and len(sys.argv) <> 5:
usage()
if len(sys.argv) == 5:
# get server list from command line
servers = sys.argv[4].split(",")
key = sys.argv[2]
value = sys.argv[3]
print "Setting key: ", key, " to: ", value
key_store.set_key(key, value)