-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_node.py
More file actions
329 lines (275 loc) · 9.57 KB
/
data_node.py
File metadata and controls
329 lines (275 loc) · 9.57 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#!/usr/bin/python
import base64
import json
import logging
import os
import socket
import struct
import subprocess
import sys
import threading
from tinydb import Query, TinyDB
from tinydb.operations import delete
from gateway import Gateway
from kazoo_master import kazooMaster
db = TinyDB('db/db.json', indent=4, separators=(',', ': '))
sec_index_db = TinyDB("db/secondary.json", indent=4, separators=(',', ': '))
logging.basicConfig(filename='logs/node.log', filemode='w', level=logging.INFO)
class DataNode(object):
def __init__(self, IP_CONNECT, DEVICE):
self.DEVICE = DEVICE
self.IP_CONNECT = IP_CONNECT
self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.sock.connect((IP_CONNECT,54321))
self.kmaster = kazooMaster(IP_CONNECT, "p", "", "", "", "")
# create ephermeral node
self.create_ephemeral_node()
self.kmaster.start_client()
logging.info("Node initialized")
def create_ephemeral_node(self):
try:
self.kmaster.create("/ephemeral_{}".format(self.DEVICE), "e")
except Exception as e:
print("exception", e)
logging.error("Error in creating ephermeral node" + str(e))
def reliable_send(self, data):
self.sock.sendall(data)
def run(self):
print(self.IP_CONNECT)
while True:
logging.info("Listening from device: {} and gateway ip: ".format(self.DEVICE, self.IP_CONNECT))
print("Listening from device: {} and gateway ip: ".format(self.DEVICE, self.IP_CONNECT))
data_recv = self.reliable_recv()
if not data_recv:
continue
def recvall(self, n):
# Helper function to recv n bytes or return None if EOF is hit
data = bytearray()
while len(data) < n:
packet = self.sock.recv(n - len(data))
if not packet:
return None
data.extend(packet)
return data
def reliable_recv(self):
raw_msglen = self.recvall(4)
if not raw_msglen:
return None
msglen = struct.unpack('>I', raw_msglen)[0]
data = self.recvall(msglen)
#print(data.decode())
criteria = data.decode()
criteria = json.loads(criteria)
self.run_command(criteria)
def run_command(self, criteria):
logging.info("In run command, with data = " + str(criteria))
print("run command", criteria)
if criteria["COMMAND"] == "INSERT":
self.insertion(criteria)
self.insert_secondary_index(criteria)
elif criteria["COMMAND"] == "RETRIEVE":
self.retrieve(criteria)
elif criteria["COMMAND"] == "REPLACE":
self.replace(criteria)
elif criteria["COMMAND"] == "DELETE":
self.deletion(criteria)
elif criteria["COMMAND"] == "LISTCATEGORY":
self.list_category(criteria)
else:
logging.info("No command found")
def replace(self,criteria):
# VERIFY vibhor
logging.info("In replace, with data = " + str(criteria))
User = Query()
userid = criteria["USERID"]
updaed_products = criteria["UPDATEDLIST"]
max_product_id = criteria["MAX_PRODUCTID"]
user = db.get(User.USERID == userid)
if not user:
data = {
"USERID": userid,
"PRODUCTS": [criteria,]
}
db.insert(data)
logging.info("No such user exists in replace")
return
db_products = user["PRODUCTS"]
change_with = None
for i, product in enumerate(updaed_products):
if product["ID"] == max_product_id:
change_with = updaed_products[i]
break
if not change_with: return False
for i, product in enumerate(db_products):
if product["ID"] == max_product_id:
db_products[i] = change_with
break
db.update({'PRODUCTS': db_products}, User.USERID == userid)
return True
def retrieve(self, criteria):
logging.info("In retrieve, with data = " + str(criteria))
User = Query()
userid = criteria["USERID"]
user_products = db.get(User["USERID"] == criteria["USERID"])
print(user_products)
if not user_products:
products = json.dumps({"PRODUCT":{}})
self.reliable_send(products.encode())
return
productID = criteria["PRODUCTID"]
for product in user_products["PRODUCTS"]:
if productID == product["ID"]:
products = json.dumps({"PRODUCT":product})
self.reliable_send(products.encode())
return
products = json.dumps({"PRODUCT":{}})
self.reliable_send(products.encode())
@staticmethod
def get_store_dict(criteria, version):
return {
'USERID': criteria["USERID"],
'PRODUCTS': [
{
"ID": criteria["PRODUCTID"],
"PRICE": criteria["PRICE"],
"CATEGORY": str(criteria["CATEGORY"]),
"LATEST_VERSION_VECTOR": version,
"OPERATIONS": [
{
"OPERATION": criteria["OPERATION"],
"VERSION_VECTOR": version
}
]
}
]
}
def deletion(self,criteria):
logging.info("In deletion, with data = " + str(criteria))
User = Query()
# query = (User.USERID == criteria["USERID"]) & (User.PRODUCTS.all(Query().ID == criteria["PRODUCTID"]))
query = (User.USERID == criteria["USERID"])
db_user_product = db.get(query)
up_found = False
if db_user_product:
for db_user_prod in db_user_product["PRODUCTS"]:
if db_user_prod["ID"] == criteria["PRODUCTID"]:
up_found = True
break
path = "/" + criteria["USERID"] + "/" + criteria["PRODUCTID"] + '/' + self.DEVICE
path_rev = "/" + self.DEVICE + "/" +criteria["USERID"] + "/" + criteria["PRODUCTID"]
if up_found: # if product and user id DNE, simply push the 1st operation
for i, product in enumerate(db_user_product["PRODUCTS"]):
if product["ID"] == criteria["PRODUCTID"]:
version = int(db_user_product["PRODUCTS"][i]['LATEST_VERSION_VECTOR'])
zversion = int(self.kmaster.retrieve(path))
version = version + 1
if zversion != version:
logging.info("CONCURRENT TRANSACTION in node")
self.kmaster.setVersion(path, version)
self.kmaster.setVersion(path_rev, version)
for i, product in enumerate(db_user_product["PRODUCTS"]):
if product["ID"] == criteria["PRODUCTID"]:
db_user_product["PRODUCTS"][i]['LATEST_VERSION_VECTOR'] = str(version)
## append the operation and update
db_user_product["PRODUCTS"][i]['OPERATIONS'].append(
{"OPERATION": "DELETE", "VERSION_VECTOR": str(version)}
)
break
db.update(db_user_product)
else:
logging.info("DELETION NOT POSSIBLE, USERID, PRODUCTD DOES NOT FOUND")
def insert_secondary_index(self, criteria):
logging.info("Inserting product secondary index for {}".format(str(criteria)))
Product = Query()
query = (Product.CATEGORY == str(criteria["CATEGORY"]))
product = sec_index_db.get(query)
print(product, "in insert sec index")
if product:
if criteria["USERID"] not in product["USERID"]:
product["USERID"].append(criteria["USERID"])
sec_index_db.update(product)
else:
sec_index_db.insert({
"CATEGORY": str(criteria["CATEGORY"]),
"USERID": [criteria["USERID"]]
})
def list_category(self,criteria):
logging.info("Extracting product secondary index for {}".format(str(criteria)))
Product = Query()
query = (Product.CATEGORY == str(criteria["CATEGORY"]))
product = sec_index_db.get(query)
print(product, "in list category")
if product:
products = json.dumps({"PRODUCT":product["USERID"]})
self.reliable_send(products.encode())
else:
products = json.dumps({"PRODUCT":[]})
self.reliable_send(products.encode())
def insertion(self, criteria):
User = Query()
logging.info("In insertion, with data = " + str(criteria))
self.insert_secondary_index(criteria)
# query = (User.USERID == criteria["USERID"]) & (User.PRODUCTS.all(Query().ID == criteria["PRODUCTID"]))
query = (User.USERID == criteria["USERID"])
db_user_product = db.get(query)
up_found = False
if db_user_product:
for db_user_prod in db_user_product["PRODUCTS"]:
if db_user_prod["ID"] == criteria["PRODUCTID"]:
up_found = True
break
path = "/" + criteria["USERID"] + "/" + criteria["PRODUCTID"] + '/' + self.DEVICE
path_rev = "/" + self.DEVICE + "/" +criteria["USERID"] + "/" + criteria["PRODUCTID"]
if not up_found: # if product and user id DNE, simply push the 1st operation
if self.kmaster.exist("path"):
gateway = Gateway()
gateway.read_repair({"NODES":[self.DEVICE,]})
else:
self.kmaster.create(path)
self.kmaster.create(path_rev)
to_store = self.get_store_dict(criteria, "0")
db_user = db.get(query)
if db_user:
db_user["PRODUCTS"].append(to_store["PRODUCTS"][0])
db.update(db_user)
else:
db.insert(to_store)
self.kmaster.setVersion(path, 0)
else:
for i, product in enumerate(db_user_product["PRODUCTS"]):
if product["ID"] == criteria["PRODUCTID"]:
version = int(db_user_product["PRODUCTS"][i]['LATEST_VERSION_VECTOR'])
zversion = int(self.kmaster.retrieve(path))
version = version + 1
if zversion != version:
logging.info("CONCURRENT TRANSACTION in node")
self.kmaster.setVersion(path, version)
self.kmaster.setVersion(path_rev, version)
# update lastest version vector
for i, product in enumerate(db_user_product["PRODUCTS"]):
if product["ID"] == criteria["PRODUCTID"]:
db_user_product["PRODUCTS"][i]['LATEST_VERSION_VECTOR'] = str(version)
## append the operation and update
db_user_product["PRODUCTS"][i]['OPERATIONS'].append(
{"OPERATION": criteria["OPERATION"], "VERSION_VECTOR": str(version)}
)
break
db.update(db_user_product)
return True
def __del__(self):
self.sock.close()
def run_node_thread(GATWWAY_IP, DEVICE):
node = DataNode(GATWWAY_IP, DEVICE)
node.run()
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Please provide <DEVICE name>")
sys.exit(-1)
DEVICE = sys.argv[1]
with open("./config/config.json") as f:
config = f.read()
config = json.loads(config)
gateway_ips = config["gateway_ips"]
for gip in gateway_ips:
t = threading.Thread(target = run_node_thread, args=(gip, DEVICE))
t.start()