-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweightedRoundRobin.py
74 lines (61 loc) · 1.43 KB
/
weightedRoundRobin.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
'''
1. node class
1. nodeId
2.nodeName
3.nodeWeight
2. weighted round robin class
variables
1. storing nodes
2. curNode
methods
1. aquireNode
2.freeNode
3.addNode
4.deleteNode
5. releaseNode
'''
import threading
class Node:
def __init__(self,nodeId,nodeName,nodeWeight):
self.id=nodeId
self.name=nodeName
self.weight=nodeWeight
self.lock=threading.Lock()
class WeightedRoundRobin:
def __init__(self,nodes):
self.nodes=list(nodes)
self.curNode=0
self.requestToNode={}
self.global_lock = threading.Lock()
self.length=len(nodes)
def addNode(self,node):
with self.global_lock:
self.nodes.append(node)
self.length+=1
def removeNode(self,node):
with self.global_lock:
self.nodes.remove(node)
self.length-=1
self.curNode=0
def aquireNode(self,request):
try:
with self.global_lock:
node=self.nodes[self.curNode]%self.length
while node.weight==0:
self.curNode+=1
node=self.nodes[self.curNode]
node.weight-=1
acquired=node.lock.acquire(blocking=False)
if acquired:
# Schedule the release of the node after 30 seconds
timer = threading.Timer(30, self.releaseNode, [node])
timer.start()
return node
except Exception as e:
raise "No Server Found"
def releaseNode(self):
try:
if node.lock.locked():
node.lock.release()
except Exception as e:
raise "No Server Found"