-
Notifications
You must be signed in to change notification settings - Fork 0
/
load_balancer.py
52 lines (45 loc) · 2.06 KB
/
load_balancer.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
from policies import *
from endpoint_waker import EndpointWaker
POLICIES = ['round robin', 'weighted round robin', 'least connection', 'weighted least connection', 'fixed weighting', 'randomized static']
MAX_ARGUMENTS = 2
NUMBER_OF_REQUESTS_IDX = 1
class LoadBalancer():
def __init__(self, cfg):
self.host = cfg['host']
self.port = cfg['port']
self.main_endpoint = cfg['main_endpoint']
self.policy = cfg['policy']
self.hosts_configuration = cfg['hosts_configuration']
self.req_num = cfg['req_num']
self.endpoints = []
# Configure the hosts
for e in self.hosts_configuration:
for i in range(self.hosts_configuration[e]):
endpoint = self.host + ':' + str(self.port) + '/' + self.main_endpoint + '/' + e + '/' + str(i)
self.endpoints.append(endpoint)
if self.policy not in POLICIES:
print('The policy is not supported. Try one of the following: {}'.format(POLICIES))
return
# If the servers are not awake the time for response will be abnormal
# and one solution for this is to make a request on each of them in the
# beginning and then 'listen' to other requests => this task can be performed
# in parallel for each endpoint
wakers = []
for e in self.endpoints:
t = EndpointWaker(e)
t.run()
for w in wakers:
w.join()
def run(self):
if self.policy == POLICIES[0]:
round_robin(self.endpoints, self.req_num)
elif self.policy == POLICIES[1]:
weigthed_round_robin(self.endpoints, self.req_num)
elif self.policy == POLICIES[2]:
least_connection(self.endpoints, self.req_num)
elif self.policy == POLICIES[3]:
weighted_lest_connnection(self.endpoints, self.req_num)
elif self.policy == POLICIES[4]:
fixed_weighting(self.endpoints, self.req_num)
elif self.policy == POLICIES[5]:
randomized_static(self.endpoints, self.req_num)