-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrediser.py
executable file
·1893 lines (1743 loc) · 70.1 KB
/
rediser.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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# rediser - A redis admin tool.
# Copyright (C) 2017 Joyield, Inc. <[email protected]>
# All rights reserved.
#
import os
import sys
import argparse
import socket
import select
import random
import time
import json
import traceback
import functools
import datetime
redis_lock_key = '{__rediser_cluster_lock_key6853__}'
redis_lock_key_ttl = 300
redis_lock_key_migrate = redis_lock_key + 'migrate'
redis_lock_key_tasks = redis_lock_key + 'tasks'
redis_lock_key_moving = redis_lock_key + 'moving'
redis_lock_key_finish = redis_lock_key + 'finish'
crc16tab = [
0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
]
def crc16(buf):
crc = 0
for c in buf:
v = ord(c)
crc = ((crc<<8) ^ crc16tab[((crc>>8) ^ v) & 0x00FF]) & 0xFFFF
return crc
def timestamp():
return int(time.time())
def get_unique_id():
hostname = socket.gethostname()
random = ''.join(['%02X'%ord(i) for i in os.urandom(8)])
now = datetime.datetime.now()
return '_'.join([hostname, random, now.strftime('%Y%m%d%H%M%S')])
def str_or_repr(v):
try:
return str(v)
except:
return repr(v)
def split_addr(addr):
try:
idx = addr.find('@')
if idx > 0:
addr = addr[:idx]
idx = addr.rfind(':')
return (addr[:idx], int(addr[idx+1:]))
except:
raise Exception('invalid address(%s)' % addr)
def tprint(*args):
if len(args) <= 1:
sys.stdout.write('%s %s\n' % (time.strftime('%Y-%m-%d %H:%M:%S'), args[0] if len(args) == 1 else ''))
sys.stdout.flush()
return
tag = args[0].lower()
if os.isatty(sys.stdout.fileno()):
if tag in ('error', 'fail', 'pfail', 'conflict', 'unassign'):
tag = '\033[31m%s\033[0m' % args[0]
elif tag in ('warn'):
tag = '\033[34m%s\033[0m' % args[0]
elif tag in ('ok', 'succ', 'pass'):
tag = '\033[32m%s\033[0m' % args[0]
else:
tag = args[0]
sys.stdout.write('%s %s %s\n' % (time.strftime('%Y-%m-%d %H:%M:%S'), tag, ' '.join([str(i) for i in args[1:]])))
sys.stdout.flush()
class ClusterSlotState:
stable = 0
importing = 1
migrating = 2
class Client(object):
class ErrorBase(Exception):
def __init__(self, *args, **kwargs):
super(Client.ErrorBase, self).__init__(*args, **kwargs)
class RespError(ErrorBase):
def __init__(self, *args, **kwargs):
super(Client.RespError, self).__init__(*args, **kwargs)
class ProtocolError(ErrorBase):
def __init__(self, *args, **kwargs):
super(Client.ProtocolError, self).__init__(*args, **kwargs)
class EmptyRecvError(ErrorBase):
def __init__(self, *args, **kwargs):
super(Client.EmptyRecvError, self).__init__(*args, **kwargs)
class ConnBusyError(ErrorBase):
def __init__(self, *args, **kwargs):
super(Client.ConnBusyError, self).__init__(*args, **kwargs)
def __init__(self, host='127.0.0.1', port=6379, db=0, password=None, timeout=None):
self.family = socket.AF_UNIX if port==None else socket.AF_INET
self.timeout = timeout
self.addr = host if port==None else (host, port)
self.db = db
self.password = password
self.conn = None
self.sent = 0
self.buf = ''
def __repr__(self):
return '<Client(addr=%s)>' % str(self.addr)
def close(self):
self.conn = None
self.sent = 0
self.buf = ''
def _conn(self):
if self.conn:
return self.conn
self.conn = socket.socket(self.family, socket.SOCK_STREAM)
self.conn.settimeout(self.timeout)
self.conn.connect(self.addr)
if self.password != None:
self.call('auth', self.password)
if self.db > 0:
self.call('select', self.db)
return self.conn
@staticmethod
def _parse(buf):
if len(buf) == 0:
return 0, None
c = buf[0]
if c == '+':
idx = buf.find('\r\n')
if idx < 0:
return 0, None
return idx + 2, buf[1:idx]
elif c == '-':
idx = buf.find('\r\n')
if idx < 0:
return 0, None
return idx + 2, Client.RespError(buf[1:idx])
elif c == ':':
idx = buf.find('\r\n')
if idx < 0:
return 0, None
return idx + 2, int(buf[1:idx])
elif c == '$':
idx = buf.find('\r\n')
if idx < 0:
return 0, None
n = int(buf[1:idx])
if n < 0:
return idx + 2, None
idx += 2
if n + 2 > len(buf) - idx:
return 0, None
if buf[idx+n:idx+n+2] != '\r\n':
raise Client.ProtocolError, 'Bulk strings no end valid'
return idx + n + 2, buf[idx:idx+n]
elif c == '*':
idx = buf.find('\r\n')
if idx < 0:
return 0, None
n = int(buf[1:idx])
if n < 0:
raise Client.ProtocolError, 'array response length invalid:%d' % n
idx += 2
res = []
while len(res) < n:
i, r = Client._parse(buf[idx:])
if i == 0:
return 0, None
res.append(r)
idx += i
return idx, res
else:
raise Client.ProtocolError, 'unknown response header:' + repr(buf[0])
return 0, None
def send(self, *args):
if len(args) == 0:
raise ValueError, 'args length is 0'
buf = '*%d\r\n' % len(args)
for i in args:
s = str(i)
buf += '$%d\r\n%s\r\n' % (len(s), s)
try:
n = 0
while n < len(buf):
n += self._conn().send(buf[n:])
self.sent += 1
except:
self.close()
raise
def recv(self, raise_resp_error=True):
if self.sent == 0:
raise Client.EmptyRecvError, 'no pend sent command'
while True:
idx = 0
res = None
try:
if len(self.buf) > 0:
idx, res = Client._parse(self.buf)
if idx == 0:
buf = self._conn().recv(16384)
self.buf += buf
idx, res = Client._parse(self.buf)
except:
self.close()
raise
if idx > 0:
self.buf = self.buf[idx:]
self.sent -= 1
if raise_resp_error and isinstance(res, Client.RespError):
raise res
return res
def recvall(self, raise_resp_error=True):
ret = []
while self.sent > 0:
r = self.recv(raise_resp_error)
ret.append(r)
return ret
def call(self, *args):
if self.sent > 0:
raise Client.ConnBusyError, 'some command exists'
self.send(*args)
return self.recv()
class ClusterClient(object):
def __init__(self, addrs, password=None, timeout=None):
self.password = password
self.timeout = timeout
self.addrs = addrs
self.conns = {}
self.slots = [None] * 16384
self.sent = []
def close(self):
for c in self.sent:
c.close()
self.sent = []
def _conn_by_addr(self, addr, slot = None):
c = self.conns.get(addr, None)
if not c:
host, port = split_addr(addr)
c = Client(host=host, port=int(port), password=self.password, timeout=self.timeout)
self.conns[addr] = c
if slot != None:
self.slots[slot] = c
return c
def _conn(self, *args):
c = None
idx = None
if len(args) > 1:
key = str(args[1])
i = key.find('{')
if i >= 0:
j = key.find('}', i)
if j > i + 1:
key = key[i+1 : j]
idx = crc16(key) & 16383
if idx != None and self.slots[idx]:
return self.slots[idx]
addr = self.addrs[random.randint(0, len(self.addrs) - 1)]
return self._conn_by_addr(addr, idx)
def send(self, *args):
c = self._conn(*args)
c.send(*args)
self.sent.append(c)
def recv(self, raise_resp_error=True):
if len(self.sent) == 0:
raise Client.EmptyRecvError, 'no pend sent command'
c = self.sent[0]
self.sent = self.sent[1:]
return c.recv(raise_resp_error)
def recvall(self, raise_resp_error=True):
ret = []
while len(self.sent) > 0:
try:
r = self.recv(raise_resp_error)
except:
self.close()
raise
ret.append(r)
return ret
def call(self, *args):
if len(self.sent) > 0:
raise Client.ConnBusyError, 'some command exists'
trycnt = 0
try:
c = self._conn(*args)
return c.call(*args)
except Client.RespError as r:
while True:
if trycnt == 2:
raise
trycnt += 1
if r.message.startswith('MOVED'):
e = r.message.split()
if len(e) != 3:
raise
c = self._conn_by_addr(e[2], int(e[1]))
try:
return c.call(*args)
except Client.RespError as excp:
r = excp
elif r.message.startswith('ASK'):
e = r.message.split()
if len(e) != 3:
raise
c = self._conn_by_addr(e[2], int(e[1]))
c.call('ASKING')
try:
return c.call(*args)
except Client.RespError as excp:
r = excp
else:
raise
class Poll(object):
def __init__(self):
self.p = select.poll()
self.conns = {}
def size(self):
return len(self.conns)
def elements(self):
return [c for _, c in self.conns.iteritems()]
def register(self, c, read=False, write=False):
evt = 0
if read:
evt |= select.POLLIN
if write:
evt |= select.POLLOUT
r = self.p.register(c, evt)
self.conns[c.fileno()] = c
return r
def unregister(self, c):
if c.fileno() in self.conns:
self.conns.pop(c.fileno())
self.p.unregister(c)
def modify(self, c, read=False, write=False):
if c.fileno() not in self.conns:
return
evt = 0
if read:
evt |= select.POLLIN
if write:
evt |= select.POLLOUT
return self.p.modify(c, evt)
def poll(self, timeout=-1):
r = self.p.poll(timeout)
for i, evt in r:
c = self.conns[i]
read = True if evt & select.POLLIN else False
write = True if evt & select.POLLOUT else False
err = True if evt & (select.POLLERR|select.POLLHUP) else False
c.handle(read, write, err)
return len(r)
def wait(self, timeout=-1):
t = -1 if timeout == -1 else timeout * 1000
while self.size() > 0:
n = self.poll(t)
if n == 0:
for c in self.elements():
c.abort('connection io timeout')
break
class AsyncClient(Client):
Read = 1
Write = 2
unconnected = 0
connecting = 1
connected = 2
def __init__(self, poll, host='127.0.0.1', port=1279, password=None):
super(AsyncClient, self).__init__(host, port, password=password)
self.poll = poll
self.pend = []
self.sent = []
self.state = AsyncClient.unconnected
self.event = 0
def _set_event(self, read=None, write=None):
evt = 0
if read == None:
evt |= self.event & AsyncClient.Read
elif read:
evt |= AsyncClient.Read
if write == None:
evt |= self.event & AsyncClient.Write
elif write:
evt |= AsyncClient.Write
if evt != self.event:
if evt:
if self.event:
self.poll.modify(self, evt & AsyncClient.Read, evt & AsyncClient.Write)
else:
self.poll.register(self, evt & AsyncClient.Read, evt & AsyncClient.Write)
else:
self.poll.unregister(self)
self.event = evt
def fileno(self):
return self.conn.fileno()
def call(self, cb, *args):
if len(args) == 0:
raise ValueError, 'args length is 0'
buf = '*%d\r\n' % len(args)
for i in args:
s = str(i)
buf += '$%d\r\n%s\r\n' % (len(s), s)
self.pend.append([cb, buf, 0])
try:
self._send()
except Exception as excp:
self._excp(excp)
def abort(self, res):
self._excp(Exception(res))
def _send(self):
if not self.conn:
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.setblocking(False)
try:
c.connect(self.addr)
except socket.error as err:
if err.errno != socket.errno.EINPROGRESS:
raise
self.conn = c
self.state = AsyncClient.connecting
self._set_event(write=True)
if self.password != None:
buf = '*2\r\n$4\r\nAUTH\r\n$%d\r\n%s\r\n' % (len(self.password), self.password)
self.pend.insert(0, [None, buf, 0])
if self.state == AsyncClient.connected:
try:
while len(self.pend) > 0:
m = self.pend[0]
n = self.conn.send(m[1][m[2]:])
m[2] += n
if m[2] >= len(m[1]):
self.sent.append(m)
self.pend = self.pend[1:]
except socket.error as err:
if err.errno not in (socket.errno.EAGAIN, socket.errno.EWOULDBLOCK, socket.errno.EINTR):
raise
self._set_event(True, len(self.pend)>0)
def _recv(self):
try:
while True:
buf = self.conn.recv(16384)
self.buf += buf
while len(self.buf) > 0:
n, res = self._parse(self.buf)
if n > 0:
cb = self.sent[0][0]
if cb:
cb(res)
self.sent = self.sent[1:]
self.buf = self.buf[n:]
else:
break
except socket.error as err:
if err.errno not in (socket.errno.EAGAIN, socket.errno.EWOULDBLOCK, socket.errno.EINTR):
raise
if len(self.sent) + len(self.pend) == 0:
self._set_event(False, False)
def _excp(self, excp):
reqs = self.sent + self.pend
for req in reqs:
if req[0]:
req[0](excp)
if self.conn:
self._set_event(False, False)
self.conn = None
self.sent = []
self.pend = []
self.buf = ''
self.state = AsyncClient.unconnected
def handle(self, read, write, err):
if err:
self._excp(Exception('recv error event'))
return
if write and self.state == AsyncClient.connecting:
self.state = AsyncClient.connected
try:
if write:
self._send()
if read:
self._recv()
except socket.error as err:
self._excp(err)
except Client.ErrorBase as cerr:
self._excp(cerr)
class Inst(object):
def __init__(self, addr, poll=None, password=None):
self.addr = addr
self.client = None
self.async_client = None
self.poll = poll
self.password = password
def call(self, *args):
if self.client == None:
host, port = split_addr(self.addr)
self.client = Client(host, port, password=self.password, timeout=60)
return self.client.call(*args)
def async_call(self, cb, *args):
if self.async_client == None:
host, port = split_addr(self.addr)
self.async_client = AsyncClient(self.poll, host, port, password=self.password)
return self.async_client.call(cb, *args)
class ClusterInst(Inst):
def __init__(self, addr, poll=None, password=None):
super(ClusterInst, self).__init__(addr, poll, password)
self.src = None
self.reset()
def reset(self):
self.id = None
self.flags = None
self.role = None
self.fail = None
self.noaddr = None
self.handshake = None
self.nofalgs = None
self.masterid = None
self.master = None
self.connected = None
self.slots = []
self.importing_slots = []
self.migrating_slots = []
self.insts = []
self.msgs = []
def set_node_line(self, line):
e = line.split()
self.id = e[0]
flags = []
for flag in e[2].split(','):
if len(flag) == 0 or flag in set(['myself','master','slave']):
continue
else:
flags.append(flag)
flags.sort()
if e[2].find('master') >= 0:
self.role = 'master'
elif e[2].find('slave') >= 0:
self.role = 'slave'
if e[2].find('fail?') >= 0:
self.fail = 'pfail'
elif e[2].find('fail') >= 0:
self.fail = 'fail'
if e[2].find('handshake') >= 0:
self.handshake = True
if e[2].find('noaddr') >= 0:
self.noaddr = True
if e[2].find('noflags') >= 0:
self.noflags = True
if self.role:
flags.insert(0, self.role)
self.flags = ','.join(flags) if len(flags) > 0 else ''
self.masterid = e[3]
self.master = None
self.connected = e[7] == 'connected'
for slot in e[8:]:
if slot.find('<') >= 0:
num, id = slot.split('-<-')
self.importing_slots.append((int(num[1:]), id[:-1]))
elif slot.find('>') >= 0:
num, id = slot.split('->-')
self.migrating_slots.append((int(num[1:]), id[:-1]))
elif slot.find('-') >= 0:
start, end = slot.split('-')
self.slots += range(int(start), int(end) + 1)
else:
self.slots.append(int(slot))
def set_by_client(self):
self.src = self.addr
nodes = ''
try:
nodes = self.call('cluster', 'nodes')
except Exception as excp:
self.msgs.append(('warn', '%s cluster nodes exception:%s' % (self.addr, str(excp))))
return
self._cb_cluster_nodes(nodes)
def set_by_async_client(self):
self.src = self.addr
self.async_call(self._cb_cluster_nodes, 'cluster', 'nodes')
def _cb_cluster_nodes(self, nodes):
if isinstance(nodes, Exception):
self.msgs.append(('warn', '%s cluster nodes exception:%s' % (self.addr, str(nodes))))
return
self.reset()
lines = nodes.split('\n')
id_map = {}
for line in lines:
inst = self
if line.find('myself') >= 0:
self.set_node_line(line)
else:
e = line.split()
if len(e) >= 8:
addr = e[1]
idx = addr.find('@')
if idx > 0:
addr = addr[:idx]
inst = ClusterInst(addr)
inst.set_node_line(line)
inst.src = self.addr
self.insts.append(inst)
id_map[inst.id] = inst
self.master = id_map.get(self.masterid, None)
for i in self.insts:
i.master = id_map.get(i.masterid, None)
def has_slot(self, importing=True, migrating=True):
if len(self.slots) > 0:
return True
if importing and len(self.importing_slots) > 0:
return True
if migrating and len(self.migrating_slots) > 0:
return True
return False
def slot_array_merge(slots, f=lambda v:v):
'''
slots: [value, value,...]
return: [(slot, value)|(begin_slot, end_slot, value),...]
'''
ret = []
def merge(begin, end):
if begin < end:
return (begin, end, slots[begin])
else:
return (begin, slots[begin])
begin = 0
end = 0
value = f(slots[0])
for i in xrange(1, len(slots)):
v = f(slots[i])
if value == v:
end = i
else:
ret.append(merge(begin, end))
begin = end = i
value = v
ret.append(merge(begin, end))
return ret
class Shard(object):
def __init__(self):
self.insts = []
self.slot_masters = []
self.null_masters = []
self.slaves = []
self.master = None
self.msgs = []
class InstsController(object):
def __init__(self, addrs, password=None):
self.poll = Poll()
self.insts = {}
for addr in addrs:
self.insts[addr] = Inst(addr, self.poll, password=password)
def call(self, *args, **kwargs):
r = {}
def cb(res, inst):
r[inst.addr] = res
for _, inst in self.insts.iteritems():
inst.async_call(functools.partial(cb, inst=inst), *args)
timeout = kwargs.get('timeout', 60)
self.poll.wait(timeout)
return r
class TaskMode:
assign = 1 << 0
migrate = 1 << 1
fix = 1 << 2
class MigrateSlotTask(object):
def __init__(self, dst, slot, src, cli, taskid, mode, pipeline=10, timeout=100):
self.dst = dst
self.host, self.port = split_addr(dst.addr)
self.slot = slot
self.src = src
self.cli = cli
self.taskid = taskid
self.mode = mode
self.pipeline = pipeline
self.timeout = timeout * 1000
self.total = 0
self.count = 0
self.finished = None
self.begin = timestamp()
self.last = 0
def start(self, cb_finish):
tprint('start migrate slot %d from %s to %s' % (self.slot, self.src.addr, self.dst.addr))
self.cb_finish = cb_finish
if self.mode == TaskMode.fix:
self.src.async_call(self._cb_get_keys, 'cluster', 'setslot', self.slot, 'importing', self.src.id)
else:
self.dst.async_call(self._cb_set_importing, 'cluster', 'setslot', self.slot, 'importing', self.src.id)
self.src.async_call(self._cb_countkeysinslot, 'cluster', 'countkeysinslot', self.slot)
def _cb_countkeysinslot(self, res):
if isinstance(res, int):
self.total = res
else:
self.total = 0
def _cb_set_importing(self, res):
if isinstance(res, Exception):
self._finish(res)
return
self.src.async_call(self._cb_get_keys, 'cluster', 'setslot', self.slot, 'migrating', self.dst.id)
def _cb_get_keys(self, res):
if isinstance(res, Exception):
self._finish(res)
return
self._get_keys()
def _get_keys(self):
now = timestamp()
if now > self.last + 1:
try:
self.last = now
tprint('migrate slot %d from %s to %s progress:%d/%d' % (self.slot, self.src.addr, self.dst.addr, self.count, self.total))
if self.cli.call('expire', redis_lock_key_migrate, redis_lock_key_ttl) == 0:
self.taskid = ''
self._finish('error:migrate lock expire noexists')
return
taskid = self.cli.call('get', redis_lock_key_migrate)
if taskid != self.taskid:
oldid = self.taskid
self.taskid = taskid
self._finish('error:migrate taskid changed(%s -> %s)' % (oldid, taskid))
return
self.cli.call('hset', redis_lock_key_moving, self.slot,
json.dumps({'count':self.count,
'total':self.total,
'src':self.src.addr,
'dst':self.dst.addr,
'start':self.begin,
'timestamp':now}))
except Exception as excp:
tprint('warn', '%s migrate slot %d record state exception:%s' % (self.src.addr, self.slot, str(excp)))
self.src.async_call(self._cb_getkeysinslot, 'cluster', 'getkeysinslot', self.slot, self.pipeline)
def _cb_getkeysinslot(self, res):
if isinstance(res, Exception):
self._finish(res)
return
if not res:
tprint('migrate slot %d from %s to %s progress:%d/%d' % (self.slot, self.src.addr, self.dst.addr, self.count, self.total))
self._finish('ok')
return
self.src.async_call(functools.partial(self._cb_migrate, keys=res), 'migrate', self.host, self.port, '', 0, self.timeout, 'replace', 'keys', *res)
def _cb_migrate(self, res, keys):
if isinstance(res, Exception) and not isinstance(res, Client.RespError):
self._finish(res)
return
self.count += len(keys)
self._get_keys()
def _finish(self, res):
if isinstance(res, Exception):
self.finished = 'error:' + str(res)
else:
self.finished = res
if self.mode == TaskMode.fix and self.finished == 'ok':
try:
self.src.call('cluster', 'setslot', self.slot, 'stable')
except Exception as excp:
self.finished = 'error:' + str(excp)
try:
self.cli.call('hdel', redis_lock_key_moving, self.slot)
self.cli.call('hset', redis_lock_key_finish, self.slot,
json.dumps({'count':self.count,
'total':self.total,
'src':self.src.addr,
'dst':self.dst.addr,
'finished':self.finished,
'start':self.begin,
'timestamp':timestamp()}))
except:
pass
if self.cb_finish:
self.cb_finish(self)
class MigrateSlotTaskFixer(object):
def __init__(self, num, cc):
self.num = num
self.cc = cc
self.tasks = {}
self.last_task = None
def add(self, t):
if t.dst.addr not in self.tasks:#always commit first slot for an addr
self._flush_last_task()
self.tasks[t.dst.addr] = []
if not self.last_task or self.last_task.dst.addr == t.dst.addr:
self._commit(t)
self.last_task = t
return
self.tasks[t.dst.addr].append(t)
if len(self.tasks[t.dst.addr]) >= self.num:
self._flush_last_task()
for i in self.tasks[t.dst.addr]:
self._commit(i)
self.last_task = t
self.tasks[t.dst.addr] = []
def flush(self):
for addr, tasks in self.tasks.iteritems():
if len(tasks) == 0:
continue
self._flush_last_task()
for t in tasks:
self._commit(t)
self.last_task = tasks[-1]
def _flush_last_task(self):
if not self.last_task:
return
succ = True
t = self.last_task
tprint('wait commit slot %s to %s' % (t.slot, t.dst.addr))
if not self._check(t):
succ = False
for i in xrange(0, 5):
self._commit(t)
time.sleep(0.8 * (i + 1))
if self._check(t):
succ = True
break
tag = 'ok' if succ else 'fail'
tprint(tag, 'commit slot %s to %s' % (t.slot, t.dst.addr))
self.last_task = None
def _commit(self, t):
cc = self.cc
try:
t.dst.call('cluster', 'setslot', t.slot, 'node', t.dst.id)
except Exception as excp:
tprint('warn', '%s cluster setslot %d node %s(%s) exception:%s' % (t.dst.addr, t.slot, t.dst.id, t.dst.addr, str(excp)))
for addr, nodes in cc.nodes.iteritems():
inst = nodes[0]
if inst.role == 'master':
def _cb_excp_warn(res, msg):
if isinstance(res, Exception):
tprint('warn', '%s exception:%s' % (msg, str(res)))
inst.async_call(functools.partial(_cb_excp_warn, msg='%s cluster setslot %d node %s' % (inst.addr, t.slot, t.dst.addr)), 'cluster', 'setslot', t.slot, 'node', t.dst.id)
if t.mode == TaskMode.fix:
inst.async_call(functools.partial(_cb_excp_warn, msg='%s cluster setslot %d stable' % (inst.addr, t.slot)), 'cluster', 'setslot', t.slot, 'stable')
cc.poll.wait(60)
if t.mode == TaskMode.fix:
def _cb_delslots(res, inst):
if isinstance(res, Exception):
tprint('warn', '%s cluster delslots %d exception:%s' % (inst.addr, t.slot, str(res)))
for addr, nodes in cc.nodes.iteritems():
inst = nodes[0]
if inst.role == 'slave':
inst.async_call(functools.partial(_cb_delslots, inst=inst), 'cluster', 'delslots', t.slot)
cc.poll.wait(60)
def _check(self, t):
cc = self.cc
res = cc.call('cluster', 'nodes')
for addr, nodes in res.iteritems():
if isinstance(nodes, Exception):
continue
idx = nodes.find(t.dst.addr)
if idx < 0:
continue
end = nodes.find('\n', idx)
line = nodes[idx:end] if end > 0 else nodes[idx:]
items = line.split()
items.reverse()
found = False
for seg in items:
if seg[0] == '[': #importing or migrating slot
continue
elif seg[0] < '0' or seg[0] > '9':
break
e = seg.split('-')
if len(e) == 1 or len(e) > 2:
if int(e[0]) == t.slot:
found = True
break
elif len(e) == 2:
if int(e[0]) <= t.slot and t.slot <= int(e[1]):
found = True
break
if not found:
return False
return True
class ClusterController(object):
def __init__(self):
self.poll = Poll()
self.client = None
self.nodes = {}
self.idmap = {}
def set_by_addrs(self, addrs, timeout=5, password=None):
nodes = {}
all = set(addrs)
visited = set()
while len(visited) < len(all):
pend = []
for i in all.difference(visited):
visited.add(i)
inst = ClusterInst(i, poll=self.poll, password=password)
pend.append(inst)
inst.set_by_async_client()
if i in nodes:
nodes[i].insert(0, inst)
else:
nodes[i] = [inst]
self.poll.wait(timeout)
for inst in pend:
if not inst.id: