-
Notifications
You must be signed in to change notification settings - Fork 0
/
bloom-api.py
186 lines (167 loc) · 7.03 KB
/
bloom-api.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import os
import sys
import tornado.ioloop
import tornado.web
import tornado.httpserver
import json
from time import sleep
from Bloom import Bloom
from pymongo import MongoClient, errors, ReturnDocument
from bson.objectid import ObjectId
from bson.binary import Binary
import logging
# MongoDB connection settings
# Local settings: {hostname: 'localhost', port: 27017, db_name = 'patari', api_port: 8888, api_addr:'localhost'}
new_filter_capacity = 500000
host = os.environ.get('DB_HOST', 'localhost')
port = os.environ.get('DB_PORT', 27017)
db_name = os.environ.get('DB_NAME', 'patari')
api_port = os.environ.get('BLOOMAPI_PORT', 8888)
api_addr = os.environ.get('BLOOMAPI_ADDR', 'localhost')
# Global connection and DB name
try:
client = MongoClient(host, port)
client.server_info()
except Exception as err:
print "Couldn't start the API. Database not available."
sys.exit(err)
db = client[db_name]
class BloomExists(tornado.web.RequestHandler):
def get(self, haystack, pin):
global db
haystack = str(haystack)
pin = str(pin)
response = {}
logger = logging.getLogger('bloom-api')
if len(pin) != 24 or len(haystack) != 24:
response['completed'] = 0
response['description'] = "Incorrect inputs"
logger.info('EXISTS - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:Bad inputs')
self.write(json.dumps(response))
self.finish()
else:
response['completed'] = 1
response['description'] = 'Completed'
# Check the existence
try:
result = db.bloom.find_one({'_id': ObjectId(haystack)})
except:
response['completed'] = 0
response['description'] = "Couldn't connect to database"
logger.error('EXISTS - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:DB down')
self.write(json.dumps(response))
self.finish()
return
if result is None:
logger.info('EXISTS - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:New document')
response['exists'] = 0
bf = Bloom.Bloom(new_filter_capacity)
serialized = Bloom.BloomSerializer.serialize(bf)
serialized['_id'] = ObjectId(haystack)
db.bloom.save(serialized)
else:
bf = Bloom.BloomSerializer.deserialize(result)
if pin in bf:
response['exists'] = 1
else:
response['exists'] = 0
logger.info('EXISTS - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:' + str(response['exists']))
self.write(json.dumps(response))
self.finish
class BloomAdd(tornado.web.RequestHandler):
def get(self, haystack, pin):
global db
haystack = str(haystack)
pin = str(pin)
response = {}
logger = logging.getLogger('bloom-api')
if len(pin) != 24 or (len(haystack)) != 24:
response['completed'] = 0
response['description'] = "Incorrect inputs"
logger.info('ADD - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:Bad inputs')
self.write(json.dumps(response))
self.finish()
else:
response['completed'] = 1
response['description'] = "Completed"
# Implementing the update-if-current pattern
# Just don't ask right now why I'm doing this
while True:
# Pull out the bloom filter
try:
result = db.bloom.find_one({'_id': ObjectId(haystack)})
except:
response['completed'] = 0
response['description'] = "Couldn't connect to database"
logger.error('ADD - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:DB down')
self.write(json.dumps(response))
self.finish()
return
# Add the PinID
if result is not None:
bf = Bloom.BloomSerializer.deserialize(result)
oldcount = bf.count
bf.add(pin)
# Mentioning old count makes you only access the older filter
entry = {'_id': ObjectId(haystack), 'count': oldcount}
to_update = {'$set':
{
'bitarray': Binary(bf.bitarray.tobytes()),
'count': bf.count
}
}
# Perform the update
updated = db.bloom.find_one_and_update(entry, to_update, return_document=ReturnDocument.AFTER)
if updated is not None:
logger.info('ADD - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:' + str(updated['count']))
break
else:
logger.info('ADD - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:Concurrency issue, trying again')
# Try fetching and updating again after delay, hence the infinite loop
sleep(1)
pass
else:
# The filter never existed in the first place
bf = Bloom.Bloom(new_filter_capacity)
bf.add(pin)
serialized = Bloom.BloomSerializer.serialize(bf)
serialized['_id'] = ObjectId(haystack)
db.bloom.save(serialized)
logger.info('ADD - Haystack:' + haystack + ' - Pin:' + pin + ' - Msg:New document')
break
self.write(json.dumps(response))
self.finish()
# Defining the routes
application = tornado.web.Application([
(r"/add/(\w+),(\w+)", BloomAdd),
(r"/exists/(\w+),(\w+)", BloomExists)
])
# Start the API
if __name__ == '__main__':
# Turn off Tornado's default logging
logging.getLogger('tornado.access').disabled = True
# Set up custom logging
logger = logging.getLogger('bloom-api')
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)s - %(asctime)s - %(message)s')
log_file = 'bloom.log'
log_fh = logging.FileHandler(log_file)
log_fh.setLevel(logging.DEBUG)
log_fh.setFormatter(formatter)
# Have to log to the file
logger.addHandler(log_fh)
# Don't have to log to the console
logger.propagate = False
print 'Logging in: ' + log_file
# Serve, slave. Serve.
print 'Serving at ' + host + ':' + str(api_port) + '/'
try:
logger.info("Booted up")
server = tornado.httpserver.HTTPServer(application)
server.listen(api_port, address=api_addr)
tornado.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
# Just to gracefully shutdown
print '\nQuitting API'
logger.info("Shutdown")
sys.exit()