forked from eyjian/r3c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
r3c.cpp
2870 lines (2538 loc) · 107 KB
/
r3c.cpp
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
/*
* Copyright (c) 2016, Jian Yi <eyjian at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "r3c.h"
#include "sha1.h"
#include <arpa/inet.h>
#include <errno.h>
#include <inttypes.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#define R3C_ASSERT(x) assert(x)
#ifdef __GNUC__
# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__))
#else
# define UNUSED(x) UNUSED_ ## x
#endif
#define THROW_REDIS_EXCEPTION(errcode, errmsg) throw CRedisException(errcode, errmsg, __FILE__, __LINE__)
#define THROW_REDIS_EXCEPTION_WITH_NODE(errcode, errmsg, node_ip, node_port) throw CRedisException(errcode, errmsg, __FILE__, __LINE__, node_ip, node_port, NULL, NULL)
#define THROW_REDIS_EXCEPTION_WITH_NODE_AND_COMMAND(errcode, errmsg, node_ip, node_port, command, key) throw CRedisException(errcode, errmsg, __FILE__, __LINE__, node_ip, node_port, command, key)
////////////////////////////////////////////////////////////////////////////////
std::ostream& operator <<(std::ostream& os, const struct redisReply& redis_reply)
{
if (REDIS_REPLY_STRING == redis_reply.type)
{
os << "type: string" << std::endl
<< redis_reply.str << std::endl;
}
else if (REDIS_REPLY_ARRAY == redis_reply.type)
{
os << "type: array" << std::endl;
}
else if (REDIS_REPLY_INTEGER == redis_reply.type)
{
os << "type: integer" << std::endl
<< redis_reply.integer << std::endl;
}
else if (REDIS_REPLY_NIL == redis_reply.type)
{
os << "type: nil" << std::endl;
}
else if (REDIS_REPLY_STATUS == redis_reply.type)
{
os << "type: status" << std::endl
<< redis_reply.integer << std::endl;
}
else if (REDIS_REPLY_ERROR == redis_reply.type)
{
os << "type: error" << std::endl
<< redis_reply.str << std::endl;
}
else
{
os << "type: unknown" << std::endl;
}
return os;
}
namespace r3c {
enum
{
CLUSTER_SLOTS = 16384 // number of slots, defined in cluster.h
};
// help to release va_list
struct va_list_helper
{
va_list_helper(va_list& ap)
: _ap(ap)
{
}
~va_list_helper()
{
va_end(_ap);
}
va_list& _ap;
};
/*
* Implemented in crc16.c
*/
extern uint16_t crc16(const char *buf, int len);
/* Copy from cluster.c
*
* We have 16384 hash slots. The hash slot of a given key is obtained
* as the least significant 14 bits of the crc16 of the key.
*
* However if the key contains the {...} pattern, only the part between
* { and } is hashed. This may be useful in the future to force certain
* keys to be in the same node (assuming no resharding is in progress). */
static unsigned int keyHashSlot(const char *key, size_t keylen) {
size_t s, e; /* start-end indexes of { and } */
for (s = 0; s < keylen; s++)
if (key[s] == '{') break;
/* No '{' ? Hash the whole key. This is the base case. */
if (s == keylen) return crc16(key,keylen) & 0x3FFF;
/* '{' found? Check if we have the corresponding '}'. */
for (e = s+1; e < keylen; e++)
if (key[e] == '}') break;
/* No '}' or nothing betweeen {} ? Hash the whole key. */
if (e == keylen || e == s+1) return crc16(key,keylen) & 0x3FFF;
/* If we are here there is both a { and a } on its right. Hash
* what is in the middle between { and }. */
return crc16(key+s+1,e-s-1) & 0x3FFF; // 0x3FFF == 16383
}
static bool parse_node_string(const std::string node_string, std::string* ip, uint16_t* port)
{
std::string::size_type colon_pos = node_string.find(':');
if (colon_pos == std::string::npos)
{
return false;
}
else
{
const std::string port_str = node_string.substr(colon_pos+1);
*port = atoi(port_str.c_str());
*ip = node_string.substr(0, colon_pos);
return true;
}
}
static void parse_slot_string(const std::string slot_string, int* start_slot, int* end_slot)
{
std::string::size_type bar_pos = slot_string.find('-');
if (bar_pos == std::string::npos)
{
*start_slot = atoi(slot_string.c_str());
*end_slot = *start_slot;
}
else
{
const std::string end_slot_str = slot_string.substr(bar_pos+1);
*end_slot = atoi(end_slot_str.c_str());
*start_slot = atoi(slot_string.substr(0, bar_pos).c_str());
}
}
std::string ip2string(uint32_t ip)
{
struct in_addr in;
in.s_addr = ip;
return inet_ntoa(in);
}
std::string strsha1(const std::string& str)
{
static unsigned char hex_table[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
std::string result(40, '\0'); // f3512504d8a2f422b45faad2f2f44d569a963da1
unsigned char hash[20];
SHA1_CTX ctx;
SHA1Init(&ctx);
SHA1Update(&ctx, (const unsigned char*)str.data(), str.size());
SHA1Final(hash, &ctx);
for (size_t i=0,j=0; i<sizeof(hash)/sizeof(hash[0]); ++i,j+=2)
{
result[j] = hex_table[(hash[i] >> 4) & 0x0f];
result[j+1] = hex_table[hash[i] & 0x0f];
}
return result;
}
int split(std::vector<std::string>* tokens, const std::string& source, const std::string& sep, bool skip_sep)
{
if (sep.empty())
{
tokens->push_back(source);
}
else if (!source.empty())
{
std::string str = source;
std::string::size_type pos = str.find(sep);
while (true)
{
std::string token = str.substr(0, pos);
tokens->push_back(token);
if (std::string::npos == pos)
{
break;
}
if (skip_sep)
{
bool end = false;
while (0 == strncmp(sep.c_str(), &str[pos+1], sep.size()))
{
pos += sep.size();
if (pos >= str.size())
{
end = true;
tokens->push_back(std::string(""));
break;
}
}
if (end)
break;
}
str = str.substr(pos + sep.size());
pos = str.find(sep);
}
}
return static_cast<int>(tokens->size());
}
void millisleep(uint32_t millisecond)
{
struct timespec ts = { millisecond / 1000, (millisecond % 1000) * 1000000 };
while ((-1 == nanosleep(&ts, &ts)) && (EINTR == errno));
}
void free_redis_reply(const redisReply* redis_reply)
{
freeReplyObject((void*)redis_reply);
}
unsigned int get_key_slot(const std::string* key)
{
if (key != NULL)
{
return keyHashSlot(key->c_str(), key->size());
}
else
{
struct timeval tv;
gettimeofday(&tv, NULL);
srandom(tv.tv_usec);
return random() & 0x3FFF;
}
}
std::string format_string(const char* format, ...)
{
va_list ap;
size_t size = getpagesize();
char* buffer = new char[size];
while (true)
{
va_start(ap, format);
int expected = vsnprintf(buffer, size, format, ap);
va_end(ap);
if (expected > -1 && expected < (int)size)
break;
/* Else try again with more space. */
if (expected > -1) /* glibc 2.1 */
size = (size_t)expected + 1; /* precisely what is needed */
else /* glibc 2.0 */
size *= 2; /* twice the old size */
delete []buffer;
buffer = new char[size];
}
std::string str = buffer;
delete []buffer;
return str;
}
////////////////////////////////////////////////////////////////////////////////
static void null_log_write(const char* UNUSED(format), ...)
{
}
static void r3c_log_write(const char* format, ...)
{
va_list ap;
va_start(ap, format);
vprintf(format, ap);
va_end(ap);
}
static LOG_WRITE g_error_log = r3c_log_write;
static LOG_WRITE g_info_log = r3c_log_write;
static LOG_WRITE g_debug_log = r3c_log_write;
void set_error_log_write(LOG_WRITE info_log)
{
g_error_log = info_log;
if (NULL == g_error_log)
g_error_log = null_log_write;
}
void set_info_log_write(LOG_WRITE info_log)
{
g_info_log = info_log;
if (NULL == g_info_log)
g_info_log = null_log_write;
}
void set_debug_log_write(LOG_WRITE debug_log)
{
g_debug_log = debug_log;
if (NULL == g_debug_log)
g_debug_log = null_log_write;
}
class FreeArgvHelper
{
public:
FreeArgvHelper(int argc, char* argv[], size_t* argv_len)
: _argc(argc), _argv(argv), _argv_len(argv_len)
{
}
~FreeArgvHelper()
{
for (int i=0; i<_argc; ++i)
{
if (_argv_len[i] > 0)
delete []_argv[i];
}
delete []_argv;
delete []_argv_len;
}
private:
int _argc;
char** _argv;
size_t* _argv_len;
};
static void print_reply(const char* command, const char* key, unsigned int slot, redisReply* redis_reply, int excepted_reply_type, const std::pair<std::string, uint16_t>& node)
{
if (REDIS_REPLY_STRING == redis_reply->type)
(*g_debug_log)("[%s:%d][STRING][%s][SLOT:%u]["PRINT_COLOR_GREEN"KEY:%s"PRINT_COLOR_NONE"][%s:%d]reply: (%d/%d)%s\n", __FILE__, __LINE__, command, slot, key, node.first.c_str(), node.second, redis_reply->type, excepted_reply_type, redis_reply->str);
else if (REDIS_REPLY_INTEGER == redis_reply->type)
(*g_debug_log)("[%s:%d][INTEGER][%s][SLOT:%u]["PRINT_COLOR_GREEN"KEY:%s"PRINT_COLOR_NONE"][%s:%d]reply: (%d/%d)%lld\n", __FILE__, __LINE__, command, slot, key, node.first.c_str(), node.second, redis_reply->type, excepted_reply_type, redis_reply->integer);
else if (REDIS_REPLY_ARRAY == redis_reply->type)
(*g_debug_log)("[%s:%d][ARRAY][%s][SLOT:%u]["PRINT_COLOR_GREEN"KEY:%s"PRINT_COLOR_NONE"][%s:%d]reply: (%d/%d)%zd\n", __FILE__, __LINE__, command, slot, key, node.first.c_str(), node.second, redis_reply->type, excepted_reply_type, redis_reply->elements);
else if (REDIS_REPLY_NIL == redis_reply->type)
(*g_debug_log)("[%s:%d][NIL][%s][SLOT:%u]["PRINT_COLOR_GREEN"KEY:%s"PRINT_COLOR_NONE"][%s:%d]reply: (%d/%d)%s\n", __FILE__, __LINE__, command, slot, key, node.first.c_str(), node.second, redis_reply->type, excepted_reply_type, redis_reply->str);
else if (REDIS_REPLY_ERROR == redis_reply->type)
(*g_debug_log)("[%s:%d][ERROR][%s][SLOT:%u]["PRINT_COLOR_GREEN"KEY:%s"PRINT_COLOR_NONE"][%s:%d]reply: (%d/%d)(%d)%s\n", __FILE__, __LINE__, command, slot, key, node.first.c_str(), node.second, redis_reply->type, excepted_reply_type, redis_reply->integer, redis_reply->str);
else if (REDIS_REPLY_STATUS == redis_reply->type)
(*g_debug_log)("[%s:%d][STATUS][%s][SLOT:%u]["PRINT_COLOR_GREEN"KEY:%s"PRINT_COLOR_NONE"][%s:%d]reply: (%d/%d)%s\n", __FILE__, __LINE__, command, slot, key, node.first.c_str(), node.second, redis_reply->type, excepted_reply_type, redis_reply->str);
else
(*g_debug_log)("[%s:%d][->%d][%s][SLOT:%u]["PRINT_COLOR_GREEN"KEY:%s"PRINT_COLOR_NONE"][%s:%d]reply: (%d/%d)%s\n", __FILE__, __LINE__, redis_reply->type, command, slot, key, node.first.c_str(), node.second, redis_reply->type, excepted_reply_type, redis_reply->str);
}
std::ostream& operator <<(std::ostream& os, const struct NodeInfo& node_info)
{
os << node_info.id << " " << node_info.ip << ":" << node_info.port << " " << node_info.flags << " "
<< node_info.master_id << " " << node_info.ping_sent << " " << node_info.pong_recv << " " << node_info.epoch << " ";
if (node_info.connected)
os << "connected" << " ";
else
os << "disconnected" << " ";
for (std::vector<std::pair<int, int> >::size_type i=0; i<node_info.slots.size(); ++i)
{
if (node_info.slots[i].first == node_info.slots[i].second)
os << node_info.slots[i].first;
else
os << node_info.slots[i].first << "-" << node_info.slots[i].second;
}
return os;
}
////////////////////////////////////////////////////////////////////////////////
CRedisException::CRedisException(int errcode, const std::string& errmsg, const char* file, int line, const std::string& node_ip, uint16_t node_port, const char* command, const char* key) throw ()
: _errcode(errcode), _errmsg(errmsg), _file(file), _line(line), _node_ip(node_ip), _node_port(node_port)
{
if (command != NULL)
_command = command;
if (key != NULL)
_key = key;
}
const char* CRedisException::what() const throw()
{
return _errmsg.c_str();
}
std::string CRedisException::str() const throw ()
{
return format_string("redis://%s:%d/%s/%s/%d:%s@%s:%d", _node_ip.c_str(), _node_port, _command.c_str(), _key.c_str(), _errcode, _errmsg.c_str(), _file.c_str(), _line);
}
////////////////////////////////////////////////////////////////////////////////
struct SlotInfo
{
int slot;
redisContext* redis_context;
std::pair<uint32_t, uint16_t> node;
};
struct ParamInfo
{
const char* command;
size_t command_length;
const std::string* key;
const std::string* str1;
const std::string* str2;
const std::string* str3;
const std::string* str4;
const std::string* str5;
const std::vector<std::string>* array;
const std::map<std::string, std::string>* in_map1;
const std::map<std::string, int64_t>* in_map2;
const std::string* str6;
const std::string* str7;
const char* tag;
size_t tag_length;
std::string* value;
std::vector<std::string>* values;
std::map<std::string, std::string>* out_map;
std::vector<std::pair<std::string, int64_t> >* out_vec;
const bool* keep_null;
const bool* withscores;
std::pair<std::string, uint16_t>* which;
ParamInfo(const char* command_, size_t command_length_, const std::string* key_, std::pair<std::string, uint16_t>* which_)
: command(command_), command_length(command_length_), key(key_),
str1(NULL), str2(NULL), str3(NULL), str4(NULL), str5(NULL),
array(NULL), in_map1(NULL), in_map2(NULL),
str6(NULL), str7(NULL),
tag(NULL), tag_length(0),
value(NULL), values(NULL),
out_map(NULL), out_vec(NULL),
keep_null(NULL), withscores(NULL),
which(which_)
{
}
};
CRedisClient::CRedisClient(const std::string& nodes, int connect_timeout_milliseconds, int data_timeout_milliseconds, const std::string& password) throw (CRedisException)
: _cluster_mode(false), _password(password), _nodes_string(nodes),
_connect_timeout_milliseconds(connect_timeout_milliseconds), _data_timeout_milliseconds(data_timeout_milliseconds),
_retry_times(RETRY_TIMES), _retry_sleep_milliseconds(RETRY_SLEEP_MILLISECONDS),
_redis_context(NULL), _slots(CLUSTER_SLOTS, NULL)
{
parse_nodes();
if (_nodes.empty())
{
THROW_REDIS_EXCEPTION(ERR_PARAMETER, "invalid nodes or not set");
}
else if (_nodes.size() > 1)
{
_cluster_mode = true;
init();
}
}
CRedisClient::~CRedisClient()
{
clear();
}
bool CRedisClient::cluster_mode() const
{
return _cluster_mode;
}
void CRedisClient::set_retry(int retry_times, int retry_sleep_milliseconds)
{
_retry_times = retry_times;
_retry_sleep_milliseconds = retry_sleep_milliseconds;
if (_retry_times < 0)
_retry_times = 0;
if (_retry_sleep_milliseconds < 1)
_retry_sleep_milliseconds = 1;
}
////////////////////////////////////////////////////////////////////////////////
int CRedisClient::list_nodes(std::vector<struct NodeInfo>* nodes_info, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
if (!_cluster_mode)
{
return 0;
}
else
{
int i = 0;
int errcode = 0;
int num_nodes = static_cast<int>(_nodes.size());
std::string errmsg;
std::pair<std::string, uint16_t> node;
for (i=0; i<num_nodes; ++i)
{
redisReply* redis_reply = NULL;
redisContext* redis_context = connect_node(&errcode, &errmsg, &node);
if (NULL == redis_context)
{
THROW_REDIS_EXCEPTION_WITH_NODE(errcode, errmsg.c_str(), node.first, node.second);
}
else if (redis_context->err != 0)
{
errcode = redis_context->err;
errmsg = redis_context->errstr;
redisFree(redis_context);
redis_context = NULL;
(*g_error_log)("[%d][%s:%d](%d)%s\n", i, __FILE__, __LINE__, errcode, errmsg.c_str());
continue;
}
(*g_debug_log)("[%d][%s:%d]connected %s:%d\n", i, __FILE__, __LINE__, node.first.c_str(), (int)node.second);
if (which != NULL)
{
which->first = node.first;
which->second = node.second;
}
redis_reply = (redisReply*)redisCommand(redis_context, "CLUSTER NODES");
if (NULL == redis_reply)
{
errcode = ERROR_COMMAND;
errmsg = "redis `CLUSTER NODES` error";
(*g_error_log)("[%d][%s:%d][%s:%d](%d)%s|(%d)%s\n", i, __FILE__, __LINE__, node.first.c_str(), (int)node.second, errcode, errmsg.c_str(), redis_context->err, redis_context->errstr);
redisFree(redis_context);
redis_context = NULL;
continue;
}
else if (redis_reply->type != REDIS_REPLY_STRING)
{
// LOADING Redis is loading the dataset in memory
errcode = redis_reply->type;
errmsg = redis_reply->str;
(*g_error_log)("[%d/%d][%s:%d][%s:%d](%d)%s|(%d)%s\n", i, num_nodes, __FILE__, __LINE__, node.first.c_str(), (int)node.second, errcode, errmsg.c_str(), redis_context->err, redis_context->errstr);
freeReplyObject(redis_reply);
redisFree(redis_context);
redis_reply = NULL;
redis_context = NULL;
//THROW_REDIS_EXCEPTION_WITH_NODE(errcode, errmsg.c_str(), node.first, node.second);
continue;
}
/*
* <id> <ip:port> <flags> <master> <ping-sent> <pong-recv> <config-epoch> <link-state> <slot> <slot> ... <slot>
* flags: A list of comma separated flags: myself, master, slave, fail?, fail, handshake, noaddr, noflags
* ping-sent: Milliseconds unix time at which the currently active ping was sent, or zero if there are no pending pings
* pong-recv: Milliseconds unix time the last pong was received
* link-state: The state of the link used for the node-to-node cluster bus. We use this link to communicate with the node. Can be connected or disconnected
*
* `redis_reply->str` example:
* 56686c7baad565d4370b8f1f6518a67b6cedb210 10.225.168.52:6381 slave 150f77d1000003811fb3c38c3768526a0b25ec31 0 1464662426768 22 connected
* 150f77d1000003811fb3c38c3768526a0b25ec31 10.225.168.51:6379 myself,master - 0 0 22 connected 3278-5687 11092-11958
* 6a7709bc680f7b224d0d20bdf7dd14db1f013baf 10.212.2.71:6381 master - 0 1464662429775 24 connected 8795-10922 11959-13107
*/
std::vector<std::string> lines;
int num_lines = split(&lines, redis_reply->str, "\n");
freeReplyObject(redis_reply);
redisFree(redis_context);
redis_reply = NULL;
redis_context = NULL;
errcode = 0; // Must reset to zero
errmsg.clear();
for (int row=0; row<num_lines; ++row)
{
std::vector<std::string> tokens;
const std::string& line = lines[row];
int num_tokens = split(&tokens, line, " ");
if (num_tokens >= 8)
{
NodeInfo node_info;
node_info.id = tokens[0];
if (!parse_node_string(tokens[1], &node_info.ip, &node_info.port))
{
(*g_debug_log)("[%s:%d][%s:%d]invalid node_string: %s\n", __FILE__, __LINE__, node.first.c_str(), (int)node.second, tokens[1].c_str());
}
else
{
std::string::size_type pos_fail = tokens[2].find("fail");
std::string::size_type pos_master = tokens[2].find("master");
node_info.flags = tokens[2];
node_info.is_fail = (pos_fail != std::string::npos);
node_info.is_master = (pos_master != std::string::npos);
node_info.master_id = tokens[3];
node_info.ping_sent = atoi(tokens[4].c_str());
node_info.pong_recv = atoi(tokens[5].c_str());
node_info.epoch = atoi(tokens[6].c_str());
node_info.connected = (tokens[7] == "connected");
if (node_info.is_fail)
{
//(*g_error_log)("[%s:%d]%s\n", __FILE__, __LINE__, node_info.str().c_str());
}
else
{
//(*g_debug_log)("[%s:%d]%s\n", __FILE__, __LINE__, node_info.str().c_str());
for (int col=8; col<num_tokens; ++col)
{
std::pair<int, int> slot;
parse_slot_string(tokens[col], &slot.first, &slot.second);
node_info.slots.push_back(slot);
}
}
nodes_info->push_back(node_info);
} // if (parse_node_string
} // if (num_tokens >= 8)
} // for (int row=0; row<num_lines; ++row)
break;
} // for
//(*g_debug_log)("[%d/%d][%s:%d][%s:%d][%d]errcode=(%d)%s\n", i, num_nodes, __FILE__, __LINE__, node.first.c_str(), (int)node.second, static_cast<int>(nodes_info->size()), errcode, errmsg.c_str());
if (errcode != 0)
THROW_REDIS_EXCEPTION_WITH_NODE(errcode, errmsg.c_str(), node.first, node.second);
return static_cast<int>(nodes_info->size());
}
}
void CRedisClient::flushall(std::vector<std::pair<std::string, std::string> >* results) throw (CRedisException)
{
std::vector<struct NodeInfo> nodes_info;
list_nodes(&nodes_info);
for (std::vector<struct NodeInfo>::size_type i=0; i<nodes_info.size(); ++i)
{
const struct NodeInfo& node_info = nodes_info[i];
std::pair<std::string, std::string> pair;
pair.first = node_info.ip + std::string(":") + any2string(node_info.port);
if (!node_info.is_master)
{
pair.second = "IS NOT MASTER";
}
else
{
redisContext* redis_context = NULL;
if (_connect_timeout_milliseconds <= 0)
{
redis_context = redisConnect(node_info.ip.c_str(), node_info.port);
}
else
{
struct timeval timeout;
timeout.tv_sec = _connect_timeout_milliseconds / 1000;
timeout.tv_usec = (_connect_timeout_milliseconds % 1000) * 1000;
redis_context = redisConnectWithTimeout(node_info.ip.c_str(), node_info.port, timeout);
}
if (NULL == redis_context)
{
pair.second = "INVALID CONTEXT";
}
else
{
if(_password.size() > 0)
{
redisReply* redis_reply = (redisReply*)redisCommand(redis_context, "auth %s", _password.c_str());
if (NULL == redis_reply)
{
(*g_error_log)("[%s:%d]auth failure\n", __FILE__, __LINE__);
}
}
redisReply* redis_reply = (redisReply*)redisCommand(redis_context, "FLUSHALL");
if (NULL == redis_reply)
{
pair.second = "FLUSHALL ERROR";
}
else
{
pair.second = redis_reply->str;
freeReplyObject(redis_reply);
}
redisFree(redis_context);
}
}
if (results != NULL)
{
results->push_back(pair);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// KEY VALUE
bool CRedisClient::key_type(const std::string& key, std::string* key_type, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
struct ParamInfo param_info("TYPE", sizeof("TYPE")-1, &key, which);
param_info.value = key_type;
redis_command(REDIS_REPLY_STATUS, ¶m_info);
return !key_type->empty();
}
#if 0
// binary unsafe, key and value can not contain space & LF etc.
bool CRedisClient::exists(const std::string& key, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
int64_t result = 0;
const std::string command_string = format_string("EXISTS %s", key.c_str());
const redisReply* redis_reply = redis_command(REDIS_REPLY_INTEGER, which, key, "EXISTS", command_string);
if (redis_reply != NULL)
{
result = redis_reply->integer;
freeReplyObject(const_cast<redisReply*>(redis_reply));
redis_reply = NULL;
}
return result > 0;
}
#else
// binary safe, key and value can contain any.
bool CRedisClient::exists(const std::string& key, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
struct ParamInfo param_info("EXISTS", sizeof("EXISTS")-1, &key, which);
int64_t result = redis_command(REDIS_REPLY_INTEGER, ¶m_info);
return result > 0;
}
#endif
bool CRedisClient::expire(const std::string& key, uint32_t seconds, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
const std::string str6 = any2string(seconds);
struct ParamInfo param_info("EXPIRE", sizeof("EXPIRE")-1, &key, which);
param_info.str6 = &str6;
int64_t result = redis_command(REDIS_REPLY_INTEGER, ¶m_info);
return result > 0;
}
// EVAL script numkeys key [key ...] arg [arg ...]
const RedisReplyHelper CRedisClient::eval(const std::string& key, const std::string& lua_scripts, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
const int excepted_reply_type = -1;
const int argc = 3;
size_t* argv_len = new size_t[argc];
char** argv = new char*[argc];
argv_len[0] = sizeof("EVAL")-1;
argv_len[1] = lua_scripts.size();
argv_len[2] = 1;
argv[0] = new char[argv_len[0]+1];
argv[1] = new char[argv_len[1]+1];
argv[2] = new char[argv_len[2]+1];
strncpy(argv[0], "EVAL", sizeof("EVAL"));
strncpy(argv[1], lua_scripts.c_str(), lua_scripts.size()+1);
strncpy(argv[2], "0", 2);
FreeArgvHelper fah(argc, argv, argv_len);
const std::string command_string;
const redisReply* redis_reply = redis_command(excepted_reply_type, which, &key, "EVAL", command_string, argc, (const char**)argv, argv_len);
return RedisReplyHelper(redis_reply);
}
// EVAL script numkeys key [key ...] arg [arg ...]
// EVALSHA sha1 numkeys key [key ...] arg [arg ...]
//
// r3c_cmd eval 123456 "local n; n=redis.call('setnx',KEYS[1],ARGV[1]); if (n>0) then redis.call('expire', KEYS[1], ARGV[2]) end; return n;" abcdefg 10
const RedisReplyHelper CRedisClient::eval(const std::string& key, const std::string& lua_scripts, const std::vector<std::string>& parameters, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
return do_eval("EVAL", key, lua_scripts, parameters, which);
}
const RedisReplyHelper CRedisClient::evalsha(const std::string& key, const std::string& sha1, const std::vector<std::string>& parameters, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
return do_eval("EVALSHA", key, sha1, parameters, which);
}
const RedisReplyHelper CRedisClient::do_eval(const char* eval_command, const std::string& key, const std::string& lua_script_or_sha1, const std::vector<std::string>& parameters, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
const int excepted_reply_type = -1;
// 3: EVAL script 1 key
const int argc = 4 + static_cast<int>(parameters.size());
size_t* argv_len = new size_t[argc];
char** argv = new char*[argc];
int argv_len_index = 0;
// EVAL/EVALSHA
argv_len[argv_len_index] = strlen(eval_command);
argv[argv_len_index] = new char[argv_len[argv_len_index]+1];
strncpy(argv[argv_len_index], eval_command, argv_len[argv_len_index]+1);
++argv_len_index;
// script/sha1
argv_len[argv_len_index] = lua_script_or_sha1.size();
argv[argv_len_index] = new char[argv_len[argv_len_index]+1];
strncpy(argv[argv_len_index], lua_script_or_sha1.c_str(), argv_len[argv_len_index]+1);
++argv_len_index;
// numkeys
argv_len[argv_len_index] = 1;
argv[argv_len_index] = new char[argv_len[argv_len_index]+1];
strncpy(argv[argv_len_index], "1", argv_len[argv_len_index]+1);
++argv_len_index;
// key
argv_len[argv_len_index] = key.size();
argv[argv_len_index] = new char[argv_len[argv_len_index]+1];
strncpy(argv[argv_len_index], key.c_str(), argv_len[argv_len_index]+1);
++argv_len_index;
for (std::vector<std::string>::size_type i=0; i<parameters.size(); ++i)
{
argv_len[argv_len_index] = parameters[i].size();
argv[argv_len_index] = new char[argv_len[argv_len_index]+1];
strncpy(argv[argv_len_index], parameters[i].c_str(), argv_len[argv_len_index]+1);
++argv_len_index;
}
FreeArgvHelper fah(argc, argv, argv_len);
const std::string command_string;
const redisReply* redis_reply = redis_command(excepted_reply_type, which, &key, eval_command, command_string, argc, (const char**)argv, argv_len);
return RedisReplyHelper(redis_reply);
}
int CRedisClient::ttl(const std::string& key, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
struct ParamInfo param_info("TTL", sizeof("TTL")-1, &key, which);
int64_t result = redis_command(REDIS_REPLY_INTEGER, ¶m_info);
return static_cast<int>(result);
}
void CRedisClient::set(const std::string& key, const std::string& value, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
struct ParamInfo param_info("SET", sizeof("SET")-1, &key, which);
param_info.str1 = &value;
(void)redis_command(REDIS_REPLY_STATUS, ¶m_info);
}
bool CRedisClient::setnx(const std::string& key, const std::string& value, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
struct ParamInfo param_info("SETNX", sizeof("SETNX")-1, &key, which);
param_info.str1 = &value;
return redis_command(REDIS_REPLY_INTEGER, ¶m_info) > 0;
}
void CRedisClient::setex(const std::string& key, const std::string& value, uint32_t expired_seconds, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
const std::string str1 = any2string(expired_seconds);
struct ParamInfo param_info("SETEX", sizeof("SETEX")-1, &key, which);
param_info.str1 = &str1;
param_info.str2 = &value;
(void)redis_command(REDIS_REPLY_STATUS, ¶m_info);
}
bool CRedisClient::setnxex(const std::string& key, const std::string& value, uint32_t expired_seconds, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
try
{
const std::string str2 = "NX";
const std::string str3 = "EX";
const std::string str4 = any2string(expired_seconds);
struct ParamInfo param_info("SET", sizeof("SET")-1, &key, which);
param_info.str1 = &value;
param_info.str2 = &str2;
param_info.str3 = &str3;
param_info.str4 = &str4;
(void)redis_command(REDIS_REPLY_STATUS, ¶m_info);
return true;
}
catch (CRedisException& ex)
{
if (ERROR_NIL == ex.errcode())
return false;
throw;
}
}
bool CRedisClient::get(const std::string& key, std::string* value, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
try
{
struct ParamInfo param_info("GET", sizeof("GET")-1, &key, which);
param_info.value = value;
(void)redis_command(REDIS_REPLY_STRING, ¶m_info);
return true;
}
catch (CRedisException& ex)
{
if (ERROR_NIL == ex.errcode())
return false;
throw;
}
}
int64_t CRedisClient::mget(const std::vector<std::string>& keys, std::vector<std::string>* values,
std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
struct ParamInfo param_info("MGET", sizeof("MGET")-1, NULL, which);
param_info.array = &keys;
param_info.values = values;
return redis_command(REDIS_REPLY_ARRAY, ¶m_info);
}
void CRedisClient::mset(const std::map<std::string, std::string>& kv_map,
std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
struct ParamInfo param_info("MSET", sizeof("MSET")-1, NULL, which);
param_info.in_map1 = &kv_map;
(void)redis_command(REDIS_REPLY_STATUS, ¶m_info);
}
bool CRedisClient::del(const std::string& key, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
struct ParamInfo param_info("DEL", sizeof("DEL")-1, &key, which);
return redis_command(REDIS_REPLY_INTEGER, ¶m_info) > 0;
}
int64_t CRedisClient::incrby(const std::string& key, int64_t increment, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
const std::string str6 = any2string(increment);
struct ParamInfo param_info("INCRBY", sizeof("INCRBY")-1, &key, which);
param_info.str6 = &str6;
return redis_command(REDIS_REPLY_INTEGER, ¶m_info);
}
int64_t CRedisClient::incrby(const std::string& key, int64_t increment, int64_t expired_increment, uint32_t expired_seconds, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
const std::string lua_scripts = format_string("local n; n=redis.call('incrby','%s','%" PRId64"'); if (n==%" PRId64") then redis.call('expire', '%s', '%u') end; return n;", key.c_str(), increment, expired_increment, key.c_str(), expired_seconds);
const RedisReplyHelper redis_reply = eval(key, lua_scripts, which);
if (redis_reply->type != REDIS_REPLY_INTEGER)
{
THROW_REDIS_EXCEPTION_WITH_NODE_AND_COMMAND(redis_reply->type, "unexpected type", which->first, which->second, "INCRBYEX", NULL);
}
int64_t ret = static_cast<int64_t>(redis_reply->integer);
return ret;
}
int64_t CRedisClient::scan(int64_t cursor, std::vector<std::string>* values, std::pair<std::string, uint16_t>* which) throw (CRedisException)
{
const std::string str1 = any2string(cursor);
struct ParamInfo param_info("SCAN", sizeof("SCAN")-1, NULL, which);
param_info.str1 = &str1;
param_info.values = values;
return redis_command(REDIS_REPLY_ARRAY, ¶m_info);
}