-
Notifications
You must be signed in to change notification settings - Fork 2
/
load_balancer.py
154 lines (117 loc) · 3.98 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
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
# coding: utf-8
import socket
import select
import signal
import logging
import argparse
# configure logger output format
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',datefmt='%m-%d %H:%M:%S')
logger = logging.getLogger('Load Balancer')
# used to stop the infinity loop
done = False
# implements a graceful shutdown
def graceful_shutdown(signalNumber, frame):
logger.debug('Graceful Shutdown...')
global done
done = True
# n to 1 policy
class N2One:
def __init__(self, servers):
self.servers = servers
def select_server(self):
return self.servers[0]
def update(self, *arg):
pass
# round robin policy
class RoundRobin:
def __init__(self, servers):
self.servers = servers
def select_server(self):
pass
def update(self, *arg):
pass
# least connections policy
class LeastConnections:
def __init__(self, servers):
self.servers = servers
def select_server(self):
pass
def update(self, *arg):
pass
# least response time
class LeastResponseTime:
def __init__(self, servers):
self.servers = servers
def select_server(self):
pass
def update(self, *arg):
pass
class SocketMapper:
def __init__(self, policy):
self.policy = policy
self.map = {}
def add(self, client_sock, upstream_server):
upstream_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
upstream_sock.connect(upstream_server)
logger.debug("Proxying to %s %s", *upstream_server)
self.map[client_sock] = upstream_sock
def delete(self, sock):
try:
self.map.pop(sock)
sock.close()
except KeyError:
pass
def get_sock(self, sock):
for c, u in self.map.items():
if u == sock:
return c
if c == sock:
return u
return None
def get_upstream_sock(self, sock):
for c, u in self.map.items():
if c == sock:
return u
return None
def get_all_socks(self):
""" Flatten all sockets into a list"""
return list(sum(self.map.items(), ()))
def main(addr, servers):
# register handler for interruption
# it stops the infinite loop gracefully
signal.signal(signal.SIGINT, graceful_shutdown)
policy = N2One(servers)
mapper = SocketMapper(policy)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.setblocking(False)
sock.bind(addr)
sock.listen()
logger.debug("Listening on %s %s", *addr)
while not done:
readable, writable, exceptional = select.select([sock]+mapper.get_all_socks(), [], [], 1)
if readable is not None:
for s in readable:
if s == sock:
client, addr = sock.accept()
logger.debug("Accepted connection %s %s", *addr)
client.setblocking(False)
mapper.add(client, policy.select_server())
if mapper.get_sock(s):
data = s.recv(4096)
if len(data) == 0: # No messages in socket, we can close down the socket
mapper.delete(s)
else:
mapper.get_sock(s).send(data)
except Exception as err:
logger.error(err)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Pi HTTP server')
parser.add_argument('-p', dest='port', type=int, help='load balancer port', default=8080)
parser.add_argument('-s', dest='servers', nargs='+', type=int, help='list of servers ports')
args = parser.parse_args()
servers = []
for p in args.servers:
servers.append(('localhost', p))
main(('127.0.0.1', args.port), servers)