-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoadBalancer.py
46 lines (40 loc) · 1.54 KB
/
LoadBalancer.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
import bisect
class LoadBalancer:
def __init__(self, Replicas):
self.Server_Replicas=Replicas
self.Server_Ids = []
self.Server_Map = {}
def Hash_Value(self,key):
hash_value = key%360
return hash_value
def Map_ServerIP(self,Server_Name,Server_IP,Server_Port):
for Replica in range(self.Server_Replicas):
Server_Name=Server_Name+str(Replica)
Ascii_Value = self.Ascii(Server_Name)
Hash_Key = self.Hash_Value(Ascii_Value)
self.Server_Map[Hash_Key]=[Server_IP,Server_Port]
bisect.insort(self.Server_Ids, Hash_Key)
def Get_ServerIP(self, request):
Ascii_Value=self.Ascii(request)
Hash_Key = self.Hash_Value(Ascii_Value)
Index=bisect.bisect(self.Server_Ids,Hash_Key)
if Index==len(self.Server_Ids):
Index=0
ServerIP_Key=self.Server_Ids[Index]
ServerIP=self.Server_Map[ServerIP_Key]
return ServerIP[0],ServerIP[1]
def Delete_ServerIP(self,Server_Name):
for Replica in range(self.Server_Replicas):
Server_Name=Server_Name+str(Replica)
Ascii_Value=self.Ascii(Server_Name)
Hash_Key=self.Hash_Value(Ascii_Value)
try:
del self.Server_Map[Hash_Key]
self.Server_Ids.remove(Hash_Key)
except Exception as e:
print("ServerIP is Invalid")
def Ascii(self,string):
value=0
for char in string:
value+=ord(char)
return value