/
haystack_storage.py
557 lines (490 loc) · 16.8 KB
/
haystack_storage.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
import sys
import os
import gevent
import gevent.socket as socket
import gevent.select as select
import gevent.queue as queue
from geventsendfile import gevent_sendfile as sendfile
import json
import logging
try:
from http_parser.parser import HttpParser
except ImportError:
from http_parser.pyparser import HttpParser
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
import haystack
import haystack_logging
haystack_path = ""
haystack_index_path = ""
groupid = 0
listenip = ""
listenport = 0
master = False
slaves = []
track = None
masterip = ""
masterport = 0
TRACK_ONLINE = 1
TRACK_OFFLINE = 2
class HaystackTrack:
def __init__(self):
self.ip = ""
self.port = 0
self.channel = queue.Channel()
self.state = TRACK_OFFLINE
self.waiting = False
class HaystackSlave:
def __init__(self):
self.channel = queue.Channel()
self.last_fileno = 0
self.waiting = False
def make_fileid(groupid, fileno):
return (groupid<<54)|fileno
def parse_fileid(fileid):
fileno = fileid & ((1<<54)-1)
groupid = fileid>>54
return (groupid, fileno)
def handle_sync_upload(sock, parser):
logging.debug("handle sync upload")
body = parser.recv_body()
if not body:
return False
headers = parser.get_headers()
fileno = int(headers["FileNO"]) if headers.has_key("FileNO") else 0
if fileno <= haystack.haystack_last_fileno:
logging.error("fileno:%d less than %d", \
fileno, haystack.haystack_last_fileno)
return False
if fileno - haystack.haystack_last_fileno != 1:
logging.error("fileno is't continuous fileno:%d, last_fileno:%d", \
fileno, haystack.haystack_last_fileno)
needle = haystack.Needle()
needle.data = body
needle.key = fileno
offset = needle.write()
haystack.haystack_files[needle.key] = (offset, len(body))
haystack.haystack_last_fileno = fileno
logging.debug("fileno:%d", fileno)
for slave in slaves:
if slave.waiting:
slave.channel.put(haystack.haystack_last_fileno)
if track.waiting:
track.channel.put(haystack.haystack_last_fileno)
return True
def handle_upload(sock, parser):
body = parser.recv_body()
if not body:
return False
needle = haystack.Needle()
needle.data = body
needle.key = haystack.haystack_last_fileno+1
offset = needle.write()
haystack.haystack_last_fileno += 1
haystack.haystack_files[needle.key] = (offset, len(body))
fileid = make_fileid(groupid, haystack.haystack_last_fileno)
logging.debug("fileid:%d fileno:%d", fileid, haystack.haystack_last_fileno)
for slave in slaves:
if slave.waiting:
slave.channel.put(haystack.haystack_last_fileno)
if track.waiting:
track.channel.put(haystack.haystack_last_fileno)
return {"fileid":fileid}
def handle_download(sock, parser):
keepalived = parser.should_keep_alive()
args = urlparse.parse_qs(parser.get_query_string())
logging.debug("args:%r", args)
fileid = int(args["fileid"][0]) if args.has_key("fileid") else 0
_, fileid = parse_fileid(fileid)
if not haystack.haystack_files.has_key(fileid):
logging.debug("can't find file:%d", fileid)
sock.send("HTTP/1.1 404 Not Found\r\n")
sock.send("Content-Length: 0\r\n")
if keepalived:
sock.send("Connection: keep-alive\r\n")
else:
sock.send("Connection: close\r\n")
sock.send("\r\n")
else:
sock.send("HTTP/1.1 200 OK\r\n")
sock.send("Content-Type: application/octet-stream\r\n")
offset, size = haystack.haystack_files[fileid]
sock.send("Content-Length: %d\r\n"%size)
if keepalived:
sock.send("Connection: keep-alive\r\n")
else:
sock.send("Connection: close\r\n")
sock.send("\r\n")
logging.debug("offset:%d, size:%d\n", offset, size)
sendfile(sock.fileno(), haystack.haystack_file.fileno(), offset+haystack.Needle.HEADER_SIZE, size)
return bool(keepalived)
def heartbeat(sock):
ip, port = sock.getpeername()
parser = HttpParser()
sock.send("GET /ping HTTP/1.1\r\nHost: %s:%d\r\n\r\n"%(ip, port))
while True:
data = sock.recv(1024)
if not data:
return False
recved = len(data)
nparsed = parser.execute(data, recved)
assert(nparsed == recved)
if parser.is_message_complete():
break
return parser.get_status_code() == 200
def post_file(sock, fileno):
ip, port = sock.getpeername()
if not haystack.haystack_files.has_key(fileno):
logging.error("can't find file:%d", fileno)
return False
offset, size = haystack.haystack_files[fileno]
logging.debug("post file:%d size:%d", fileno, size)
sock.send("POST /sync_upload HTTP/1.1\r\n")
sock.send("Host: %s:%d\r\n"%(ip, port))
sock.send("Content-Length: %d\r\n"%size)
sock.send("Content-Type: application/octet-stream\r\n")
sock.send("Connection: keep-alive\r\n")
sock.send("FileNO: %d\r\n"%fileno)
sock.send("\r\n")
sendfile(sock.fileno(), haystack.haystack_file.fileno(), \
offset+haystack.Needle.HEADER_SIZE, size)
return True
def handle_sync(sock, parser):
logging.debug("handle sync")
body = parser.recv_body()
if not body:
return False
obj = json.loads(body)
last_fileno = obj["last_fileno"]
keepalived = parser.should_keep_alive()
assert(keepalived)
sock.send("HTTP/1.1 200 OK\r\n")
sock.send("Content-Length: 0\r\n")
sock.send("Connection: keep-alive\r\n")
sock.send("\r\n")
slave = HaystackSlave()
slave.last_fileno = last_fileno
slaves.append(slave)
try:
while True:
while slave.last_fileno < haystack.haystack_last_fileno:
if not post_file(sock, slave.last_fileno+1):
return False
slave.last_fileno += 1
try:
slave.waiting = True
slave.channel.get(timeout=5)
except queue.Empty:
if not heartbeat(sock):
return False
finally:
slave.waiting = False
finally:
slaves.remove(slave)
def handle_info(sock, parser):
logging.debug("handle info")
keepalived = parser.should_keep_alive()
obj = {}
obj["trackip"] = track.ip
obj["trackport"] = track.port
if track.state == TRACK_ONLINE:
obj["trackstate"] = "online"
elif track.state == TRACK_OFFLINE:
obj["trackstate"] = "offline"
if master:
obj["role"] = "master"
obj["nslaves"] = len(slaves)
else:
obj["role"] = "slave"
obj["masterip"] = masterip
obj["masterport"] = masterport
obj["last_fileno"] = haystack.haystack_last_fileno
return obj
def handle_ping(sock, parser):
logging.debug("handle ping")
return "pong"
def handle_request(sock, parser, preread):
logging.debug("handle request")
if parser:
assert(parser.is_headers_complete())
headers = parser.get_headers()
content_length = int(headers["Content-Length"]) if headers.has_key("Content-Length") else 0
assert(content_length >= len(preread))
if content_length:
if preread:
nparsed = parser.execute(preread, len(preread))
assert(nparsed == len(preread))
content_length -= len(preread)
while content_length:
data = sock.recv(content_length)
if not data:
logging.warn("client sock closed")
return False
recved = len(data)
content_length -= recved
nparsed = parser.execute(data, recved)
assert(nparsed == recved)
if parser.is_message_complete():
break
else:
parser = HttpParser()
while True:
logging.debug("recv........")
data = sock.recv(64*1024)
if not data:
logging.warn("client sock closed")
return False
recved = len(data)
nparsed = parser.execute(data, recved)
assert(nparsed == recved)
if parser.is_message_complete():
break
obj = None
if parser.get_path() == "/upload":
obj = handle_upload(sock, parser)
elif parser.get_path() == "/sync_upload":
obj = handle_sync_upload(sock, parser)
elif parser.get_path() == "/download":
obj = handle_download(sock, parser)
elif parser.get_path() == "/sync":
obj = handle_sync(sock, parser)
elif parser.get_path() == "/ping":
obj = handle_ping(sock, parser)
elif parser.get_path() == "/info":
obj = handle_info(sock, parser)
else:
logging.debug("unknown request path:%s", parser.get_path())
if obj is None:
sock.send("HTTP/1.1 404 Not Found\r\n")
sock.send("Content-Length: 0\r\n")
if keepalived:
sock.send("Connection: keep-alive\r\n")
else:
sock.send("Connection: close\r\n")
sock.send("\r\n")
return False
if not isinstance(obj, bool):
resp = json.dumps(obj)
keepalived = parser.should_keep_alive()
sock.send("HTTP/1.1 200 OK\r\n")
sock.send("Content-Type: application/json\r\n")
sock.send("Content-Length: %d\r\n"%len(resp))
if keepalived:
sock.send("Connection: keep-alive\r\n")
else:
sock.send("Connection: close\r\n")
sock.send("\r\n")
sock.send(resp)
return bool(keepalived)
else:
return obj
def handle_client(sock):
try:
while True:
rds, _, _ = select.select([sock], [], [], 60*5)
if not rds:
break
keepalived = handle_request(sock, None, None)
if not keepalived:
break
except socket.error, e:
logging.debug("socket error:%r", e)
finally:
logging.debug("close client")
sock.close()
def handle_batch_client(sock):
recvbuf = ""
while True:
rds, _, _ = select.select([sock], [], [], 60*5)
if not rds:
break
data = sock.recv(1024)
if not data:
break
recvbuf += data
pos = recvbuf.find("\r\n\r\n")
if pos == -1:
continue
parser = HttpParser()
nparsed = parser.execute(recvbuf, pos+4)
if nparsed != pos+4:
logging.debug("pos:%d, nparsed:%d, recvbuf:%r", pos, nparsed, recvbuf)
assert(nparsed == pos+4)
assert(parser.is_headers_complete())
headers = parser.get_headers()
content_length = int(headers["Content-Length"]) if headers.has_key("Content-Length") else 0
logging.debug("content length:%d", content_length)
recvbuf = recvbuf[pos+4:]
preread = recvbuf[:content_length]
recvbuf = recvbuf[content_length:]
keepalived = handle_request(sock, parser, preread)
if not keepalived:
break
logging.debug("close client")
sock.close()
def post_sync(sock, masterip, masterport):
obj = {"last_fileno":haystack.haystack_last_fileno}
body = json.dumps(obj)
sock.send("POST /sync HTTP/1.1\r\n")
sock.send("Host: %s:%d\r\n"%(masterip, masterport))
sock.send("Content-Length: %d\r\n"%len(body))
sock.send("Content-Type: application/json\r\n")
sock.send("Connection: keep-alive\r\n")
sock.send("\r\n")
sock.send(body)
parser = HttpParser()
while True:
#!!!ugly prevent recveive next http request
data = sock.recv(1)
if not data:
return False
recved = len(data)
nparsed = parser.execute(data, recved)
assert(nparsed == recved)
if parser.is_message_complete():
break
return parser.get_status_code() == 200
def _sync(masterip, masterport):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((masterip, masterport))
if not post_sync(sock, masterip, masterport):
return
logging.debug("slave sync begin recv...")
handle_batch_client(sock)
def sync_with_master(masterip, masterport):
while True:
try:
logging.debug("sync........")
_sync(masterip, masterport)
except socket.error, e:
logging.debug("disconnect with master, exception:%r", e)
gevent.sleep(5)
except Exception, e:
logging.debug("sync exception:%r", e)
gevent.sleep(5)
def post_report(sock):
st = os.statvfs(haystack_path)
available_size = st.f_bavail * st.f_frsize
obj = {}
obj["listenip"] = listenip
obj["listenport"] = listenport
obj["disk_available_size"] = available_size
obj["master"] = master
obj["groupid"] = groupid
obj["last_fileno"] = haystack.haystack_last_fileno
body = json.dumps(obj)
sock.send("POST /report HTTP/1.1\r\n")
sock.send("Host: %s:%d\r\n"%(track.ip, track.port))
sock.send("Content-Length: %d\r\n"%len(body))
sock.send("Content-Type: application/json\r\n")
sock.send("Connection: keep-alive\r\n")
sock.send("\r\n")
sock.send(body)
parser = HttpParser()
while True:
data = sock.recv(1024)
if not data:
return False
recved = len(data)
nparsed = parser.execute(data, recved)
assert(nparsed == recved)
if parser.is_message_complete():
break
return parser.get_status_code() == 200
#reconnect when 0,1,2,4,8,16.
def track_report():
nseconds = 0
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((track.ip, track.port))
while True:
last_fileno = haystack.haystack_last_fileno
post_report(sock)
track.state = TRACK_ONLINE
nseconds = 0
if last_fileno != haystack.haystack_last_fileno:
continue
try:
track.waiting = True
track.channel.get(timeout=5)
except queue.Empty:
continue
finally:
track.waiting = False
except socket.error, e:
logging.debug("socket error:%r", e)
except Exception, e:
logging.debug("exception:%r", e)
finally:
track.state = TRACK_OFFLINE
sock.close()
if nseconds == 0:
nseconds= 1
else:
gevent.sleep(nseconds)
if nseconds < 10:
nseconds *= 2
logging.debug("disconnect with track")
def file_exists(path):
try:
f = open(path, "rb")
f.close()
return True
except IOError:
return False
def main():
global listenip, listenport
global track, masterip, masterport
global groupid, master
global haystack_path, haystack_index_path
haystack_logging.init_logger("storage", logging.DEBUG)
config = {}
if len(sys.argv) == 1:
logging.error("needs config file")
return
config_file = sys.argv[1]
execfile(config_file, config)
haystack_path = config["dbfilename"]
haystack_index_path = config["dbindexfilename"]
groupid = config["groupid"]
if not file_exists(haystack_path) and not haystack.create_store(haystack_path):
logging.error("create store file fail")
sys.exit(1)
if not file_exists(haystack_index_path) and not haystack.create_index(haystack_index_path):
logging.error("create index file fail")
sys.exit(1)
if not haystack.recover(haystack_path, haystack_index_path):
logging.error("recover haystack store fail")
sys.exit(1)
if not haystack.load(haystack_path, haystack_index_path):
logging.error("load haystack file fail")
sys.exit(1)
masterip = config["masterip"] if config.has_key("masterip") else ""
masterport = config["masterport"] if config.has_key("masterport") else 0
listenip = config["listenip"]
listenport = config["listenport"]
trackip = config["trackip"]
trackport = config["trackport"]
track = HaystackTrack()
track.ip = trackip
track.port = trackport
assert(track.ip and track.port)
gevent.spawn(track_report)
if masterip and masterport:
gevent.spawn(sync_with_master, masterip, masterport)
master = False
else:
master = True
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (listenip, listenport)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(5)
while True:
client_sock, address = s.accept()
gevent.spawn(handle_client, client_sock)
if __name__ == "__main__":
main()