-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
310 lines (240 loc) · 9.23 KB
/
server.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
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
#!/usr/bin/python
# nesessary imports
import socket
import sys
import json
import time
from urlparse import urlparse
from thread import *
# global variables
HOST = ''
PORT = 8081
CONN = {}
TIME = {}
# method to route according to request
def router(client_soc, client_addr):
data = client_soc.recv(1024) #receive data from client
string = bytes.decode(data) #decode it to string
# determine request method
request_method = string.split(' ')[0]
if request_method == 'GET':
route = string.split(' ')
route = route[1]
url = urlparse(route)
if url.path == '/api/request':
newconnection(client_soc, client_addr, url)
elif url.path == '/api/serverStatus':
serverstatus(client_soc, client_addr)
elif url.path == '/api/kill':
killconnection(client_soc, client_addr, url)
else:
welcome(client_soc)
else:
client_soc.send('\n')
client_soc.send('Wrong request method, only GET is supported.')
client_soc.close()
return
def newconnection(client_soc, client_addr, url):
query = url.query
query_components = dict(qc.split("=") for qc in query.split("&"))
# check if url has required query parameter and connId is not already running in server
if 'connId' and 'timeout' in query_components:
#get query parameters
conn = query_components['connId']
timeout = int(query_components['timeout'])
if conn not in CONN:
#get current time
curr_time = int(time.time())
#save client socket and running time in dict
CONN[conn] = client_soc
TIME[conn] = curr_time + timeout
# response
message = json.dumps({"status" : "OK"})
header = {
'Content-Type': 'application/json; charset=utf8',
'Content-Length': len(message),
'Connection': 'close',
}
header = ''.join('%s: %s\n' % (k, v) for k, v in \
header.iteritems())
time.sleep(float(timeout))
if conn in CONN:
protocol = 'HTTP/1.1'
status = '200'
status_text = 'OK'
client_soc.send('%s %s %s' % (protocol, status, \
status_text))
client_soc.send('\n')
client_soc.send(header)
client_soc.send('\n')
client_soc.send(message)
client_soc.close()
# pop client from running client dict if availale
CONN.pop(conn, None)
TIME.pop(conn, None)
else:
# handle in case of bad request or error
message = json.dumps({"errors": [{"code": 403,"message": "Request with connId already running"}]})
code = (403, 'Forbidden')
error(client_soc, message, code)
else:
# handle in case of bad request or error
message = json.dumps({"errors": [{"code": 400,"message": "Bad request or querry."}]})
code = (400, 'Bad Request')
error(client_soc, message, code)
return
def serverstatus(client_soc, client_addr):
#get current time
curr_time = int(time.time())
running_req = {}
# ittirate over dict keys - connId, substract req termination time from current time to get remaining time
for i in CONN.keys():
running_req[i] = str(TIME[i] - curr_time)
message = json.dumps(running_req)
header = {
'Content-Type': 'application/json; charset=utf8',
'Content-Length': len(message),
'Connection': 'close',
}
header = ''.join('%s: %s\n' % (k, v) for k, v in \
header.iteritems())
protocol = 'HTTP/1.1'
status = '200'
status_text = 'OK'
client_soc.send('%s %s %s' % (protocol, status, \
status_text))
client_soc.send('\n')
client_soc.send(header)
client_soc.send('\n')
client_soc.send(message)
client_soc.close()
return
def killconnection(client_soc, client_addr, url):
# get req query param
query = url.query
query_components = dict(qc.split("=") for qc in query.split("&"))
# If query has connId and connection requested is running
if 'connId' in query_components:
conn = query_components['connId']
if conn in CONN and TIME:
conn_soc = CONN[conn]
killit(conn_soc) # kills the connection at socket fiven
CONN.pop(conn, None)
TIME.pop(conn, None)
message = json.dumps({"status": "OK"})
header = {
'Content-Type': 'application/json; charset=utf8',
'Content-Length': len(message),
'Connection': 'close',
}
header = ''.join('%s: %s\n' % (k, v) for k, v in \
header.iteritems())
protocol = 'HTTP/1.1'
status = '200'
status_text = 'OK'
client_soc.send('%s %s %s' % (protocol, status, \
status_text))
client_soc.send('\n')
client_soc.send(header)
client_soc.send('\n')
client_soc.send(message)
client_soc.close()
else:
# handle in case of bad request or error
status = 'Invalid Connection Id: %s' %(conn)
message = json.dumps({"status": status})
code = (400, 'Forbidden')
error(client_soc, message, code)
else:
# handle in case of bad request or error
message = json.dumps({"errors": [{"code": 400,"message": "Bad request or querry."}]})
code = (400, 'Bad Request')
error(client_soc, message, code)
return
# welcome and fallback handler, when url or query is wrong
def welcome(client_soc):
message = 'Welcome!! We support three API requests as follows..'
message += '1. new connection - method = GET, path = /api/request with query = connId=<connection id>&timeout=<time>'
message += '2. server status - method = GET, path = /api/serverStatus'
message += '3. kill connection - method = GET, path = /api/kill'
header = {
'Content-Type': 'text/plain; charset=utf8',
'Content-Length': len(message),
'Connection': 'close',
}
header = ''.join('%s: %s\n' % (k, v) for k, v in \
header.iteritems())
protocol = 'HTTP/1.1'
status = '200'
status_text = 'OK'
client_soc.send('%s %s %s' % (protocol, status, \
status_text))
client_soc.send('\n')
client_soc.send(header)
client_soc.send('\n')
client_soc.send(message)
client_soc.close()
return
def error(client_soc, message, code):
message = message
header = {
'Content-Type': 'application/json; charset=utf8',
'Content-Length': len(message),
'Connection': 'close',
}
header = ''.join('%s: %s\n' % (k, v) for k, v in \
header.iteritems())
protocol = 'HTTP/1.1'
status = code[0]
status_text = code[1]
client_soc.send('%s %s %s' % (protocol, status, \
status_text))
client_soc.send('\n')
client_soc.send(header)
client_soc.send('\n')
client_soc.send(message)
client_soc.close()
return
def killit(client_socket):
message = json.dumps({"status": "KILLED"})
header = {
'Content-Type': 'application/json; charset=utf8',
'Content-Length': len(message),
'Connection': 'close',
}
header = ''.join('%s: %s\n' % (k, v) for k, v in \
header.iteritems())
protocol = 'HTTP/1.1'
status = '200'
status_text = 'OK'
client_socket.send('%s %s %s' % (protocol, status, \
status_text))
client_socket.send('\n')
client_socket.send(header)
client_socket.send('\n')
client_socket.send(message)
client_socket.close()
return
if __name__ == "__main__":
# start server and accept requests
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket sucessfully created')
print('Press Ctrl+C to shut down.')
except socket.error as error:
print 'socket creation failed with error %s' %(err)
sys.exit()
s.bind((HOST, PORT))
s.listen(10)
try:
while True:
client_soc, client_addr = s.accept()
print 'New request from', client_addr
start_new_thread(router ,(client_soc,client_addr))
except KeyboardInterrupt:
print 'Ctrl+C pressed... Server will shut down.'
except Exception, err:
print 'Exception caught: %s\nClosing...' % err
print 'Shutting down server.....'
s.close()
sys.exit()