forked from redis/redis
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathredis-cli.c
More file actions
10837 lines (9976 loc) · 404 KB
/
redis-cli.c
File metadata and controls
10837 lines (9976 loc) · 404 KB
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
/* Redis CLI (command line interface)
*
* Copyright (c) 2009-Present, Redis Ltd.
* All rights reserved.
*
* Licensed under your choice of (a) the Redis Source Available License 2.0
* (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the
* GNU Affero General Public License v3 (AGPLv3).
*/
#include "fmacros.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <assert.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <termios.h>
#include <hiredis.h>
#ifdef USE_OPENSSL
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <hiredis_ssl.h>
#endif
#include <sdscompat.h> /* Use hiredis' sds compat header that maps sds calls to their hi_ variants */
#include <sds.h> /* use sds.h from hiredis, so that only one set of sds functions will be present in the binary */
#include "dict.h"
#include "adlist.h"
#include "zmalloc.h"
#include "linenoise.h"
#include "anet.h"
#include "ae.h"
#include "connection.h"
#include "cli_common.h"
#include "mt19937-64.h"
#include "cli_commands.h"
#include "hdr_histogram.h"
#define UNUSED(V) ((void) V)
#define OUTPUT_STANDARD 0
#define OUTPUT_RAW 1
#define OUTPUT_CSV 2
#define OUTPUT_JSON 3
#define OUTPUT_QUOTED_JSON 4
#define REDIS_CLI_KEEPALIVE_INTERVAL 15 /* seconds */
#define REDIS_CLI_DEFAULT_PIPE_TIMEOUT 30 /* seconds */
#define REDIS_CLI_HISTFILE_ENV "REDISCLI_HISTFILE"
#define REDIS_CLI_HISTFILE_DEFAULT ".rediscli_history"
#define REDIS_CLI_RCFILE_ENV "REDISCLI_RCFILE"
#define REDIS_CLI_RCFILE_DEFAULT ".redisclirc"
#define REDIS_CLI_AUTH_ENV "REDISCLI_AUTH"
#define REDIS_CLI_CLUSTER_YES_ENV "REDISCLI_CLUSTER_YES"
#define CLUSTER_MANAGER_SLOTS 16384
#define CLUSTER_MANAGER_PORT_INCR 10000 /* same as CLUSTER_PORT_INCR */
#define CLUSTER_MANAGER_MIGRATE_TIMEOUT 60000
#define CLUSTER_MANAGER_MIGRATE_PIPELINE 10
#define CLUSTER_MANAGER_REBALANCE_THRESHOLD 2
#define CLUSTER_MANAGER_INVALID_HOST_ARG \
"[ERR] Invalid arguments: you need to pass either a valid " \
"address (ie. 120.0.0.1:7000) or space separated IP " \
"and port (ie. 120.0.0.1 7000)\n"
#define CLUSTER_MANAGER_MODE() (config.cluster_manager_command.name != NULL)
#define CLUSTER_MANAGER_MASTERS_COUNT(nodes, replicas) ((nodes)/((replicas) + 1))
#define CLUSTER_MANAGER_COMMAND(n,...) \
(redisCommand((n)->context, __VA_ARGS__))
#define CLUSTER_MANAGER_NODE_ARRAY_FREE(array) zfree((array)->alloc)
#define CLUSTER_MANAGER_PRINT_REPLY_ERROR(n, err) \
clusterManagerLogErr("Node %s:%d replied with error:\n%s\n", \
(n)->ip, (n)->port, (err));
#define clusterManagerLogInfo(...) \
clusterManagerLog(CLUSTER_MANAGER_LOG_LVL_INFO,__VA_ARGS__)
#define clusterManagerLogErr(...) \
clusterManagerLog(CLUSTER_MANAGER_LOG_LVL_ERR,__VA_ARGS__)
#define clusterManagerLogWarn(...) \
clusterManagerLog(CLUSTER_MANAGER_LOG_LVL_WARN,__VA_ARGS__)
#define clusterManagerLogOk(...) \
clusterManagerLog(CLUSTER_MANAGER_LOG_LVL_SUCCESS,__VA_ARGS__)
#define CLUSTER_MANAGER_FLAG_MYSELF 1 << 0
#define CLUSTER_MANAGER_FLAG_SLAVE 1 << 1
#define CLUSTER_MANAGER_FLAG_FRIEND 1 << 2
#define CLUSTER_MANAGER_FLAG_NOADDR 1 << 3
#define CLUSTER_MANAGER_FLAG_DISCONNECT 1 << 4
#define CLUSTER_MANAGER_FLAG_FAIL 1 << 5
#define CLUSTER_MANAGER_CMD_FLAG_FIX 1 << 0
#define CLUSTER_MANAGER_CMD_FLAG_SLAVE 1 << 1
#define CLUSTER_MANAGER_CMD_FLAG_YES 1 << 2
#define CLUSTER_MANAGER_CMD_FLAG_AUTOWEIGHTS 1 << 3
#define CLUSTER_MANAGER_CMD_FLAG_EMPTYMASTER 1 << 4
#define CLUSTER_MANAGER_CMD_FLAG_SIMULATE 1 << 5
#define CLUSTER_MANAGER_CMD_FLAG_REPLACE 1 << 6
#define CLUSTER_MANAGER_CMD_FLAG_COPY 1 << 7
#define CLUSTER_MANAGER_CMD_FLAG_COLOR 1 << 8
#define CLUSTER_MANAGER_CMD_FLAG_CHECK_OWNERS 1 << 9
#define CLUSTER_MANAGER_CMD_FLAG_FIX_WITH_UNREACHABLE_MASTERS 1 << 10
#define CLUSTER_MANAGER_CMD_FLAG_MASTERS_ONLY 1 << 11
#define CLUSTER_MANAGER_CMD_FLAG_SLAVES_ONLY 1 << 12
#define CLUSTER_MANAGER_OPT_GETFRIENDS 1 << 0
#define CLUSTER_MANAGER_OPT_COLD 1 << 1
#define CLUSTER_MANAGER_OPT_UPDATE 1 << 2
#define CLUSTER_MANAGER_OPT_QUIET 1 << 6
#define CLUSTER_MANAGER_OPT_VERBOSE 1 << 7
#define CLUSTER_MANAGER_LOG_LVL_INFO 1
#define CLUSTER_MANAGER_LOG_LVL_WARN 2
#define CLUSTER_MANAGER_LOG_LVL_ERR 3
#define CLUSTER_MANAGER_LOG_LVL_SUCCESS 4
#define CLUSTER_JOIN_CHECK_AFTER 20
#define LOG_COLOR_BOLD "29;1m"
#define LOG_COLOR_RED "31;1m"
#define LOG_COLOR_GREEN "32;1m"
#define LOG_COLOR_YELLOW "33;1m"
#define LOG_COLOR_RESET "0m"
/* cliConnect() flags. */
#define CC_FORCE (1<<0) /* Re-connect if already connected. */
#define CC_QUIET (1<<1) /* Don't log connecting errors. */
/* DNS lookup */
#define NET_IP_STR_LEN 46 /* INET6_ADDRSTRLEN is 46 */
#define REFRESH_INTERVAL 300 /* milliseconds */
#define IS_TTY_OR_FAKETTY() (isatty(STDOUT_FILENO) || getenv("FAKETTY"))
/* --latency-dist palettes. */
int spectrum_palette_color_size = 19;
int spectrum_palette_color[] = {0,233,234,235,237,239,241,243,245,247,144,143,142,184,226,214,208,202,196};
int spectrum_palette_mono_size = 13;
int spectrum_palette_mono[] = {0,233,234,235,237,239,241,243,245,247,249,251,253};
/* The actual palette in use. */
int *spectrum_palette;
int spectrum_palette_size;
static int orig_termios_saved = 0;
static struct termios orig_termios; /* To restore terminal at exit.*/
/* Dict Helpers */
static uint64_t dictSdsHash(const void *key);
static int dictSdsKeyCompare(dictCmpCache *cache, const void *key1,
const void *key2);
static void dictSdsDestructor(dict *d, void *val);
static void dictListDestructor(dict *d, void *val);
/* Cluster Manager Command Info */
typedef struct clusterManagerCommand {
char *name;
int argc;
char **argv;
sds stdin_arg; /* arg from stdin. (-X option) */
int flags;
int replicas;
char *from;
char *to;
char **weight;
int weight_argc;
char *master_id;
int slots;
int timeout;
int pipeline;
float threshold;
char *backup_dir;
char *from_user;
char *from_pass;
int from_askpass;
} clusterManagerCommand;
static int createClusterManagerCommand(char *cmdname, int argc, char **argv);
static redisContext *context;
static struct config {
cliConnInfo conn_info;
struct timeval connect_timeout;
char *hostsocket;
int tls;
cliSSLconfig sslconfig;
long repeat;
long interval;
int dbnum; /* db num currently selected */
int interactive;
int shutdown;
int monitor_mode;
int pubsub_mode;
int blocking_state_aborted; /* used to abort monitor_mode and pubsub_mode. */
int latency_mode;
int latency_dist_mode;
int latency_history;
int lru_test_mode;
long long lru_test_sample_size;
int cluster_mode;
int cluster_reissue_command;
int cluster_send_asking;
int slave_mode;
int pipe_mode;
int pipe_timeout;
int getrdb_mode;
int get_functions_rdb_mode;
int stat_mode;
int scan_mode;
int count;
int intrinsic_latency_mode;
int intrinsic_latency_duration;
sds pattern;
char *rdb_filename;
int bigkeys;
int memkeys;
long long memkeys_samples;
int hotkeys;
int keystats;
unsigned long long cursor;
unsigned long top_sizes_limit;
int stdin_lastarg; /* get last arg from stdin. (-x option) */
int stdin_tag_arg; /* get <tag> arg from stdin. (-X option) */
char *stdin_tag_name; /* Placeholder(tag name) for user input. */
int askpass;
int quoted_input; /* Force input args to be treated as quoted strings */
int output; /* output mode, see OUTPUT_* defines */
int push_output; /* Should we display spontaneous PUSH replies */
sds mb_delim;
sds cmd_delim;
char prompt[128];
char *eval;
int eval_ldb;
int eval_ldb_sync; /* Ask for synchronous mode of the Lua debugger. */
int eval_ldb_end; /* Lua debugging session ended. */
int enable_ldb_on_eval; /* Handle manual SCRIPT DEBUG + EVAL commands. */
int last_cmd_type;
redisReply *last_reply;
int verbose;
int set_errcode;
clusterManagerCommand cluster_manager_command;
int no_auth_warning;
int resp2; /* value of 1: specified explicitly with option -2 */
int resp3; /* value of 1: specified explicitly, value of 2: implicit like --json option */
int current_resp3; /* 1 if we have RESP3 right now in the current connection. */
int in_multi;
int pre_multi_dbnum;
char *server_version;
char *test_hint;
char *test_hint_file;
int prefer_ipv4; /* Prefer IPv4 over IPv6 on DNS lookup. */
int prefer_ipv6; /* Prefer IPv6 over IPv4 on DNS lookup. */
} config;
/* User preferences. */
static struct pref {
int hints;
} pref;
static volatile sig_atomic_t force_cancel_loop = 0;
static void usage(int err);
static void slaveMode(int send_sync);
static int cliConnect(int flags);
static char *getInfoField(char *info, char *field);
static long getLongInfoField(char *info, char *field);
/*------------------------------------------------------------------------------
* Utility functions
*--------------------------------------------------------------------------- */
size_t redis_strlcpy(char *dst, const char *src, size_t dsize);
static void cliPushHandler(void *, void *);
uint16_t crc16(const char *buf, int len);
static long long ustime(void) {
struct timeval tv;
long long ust;
gettimeofday(&tv, NULL);
ust = ((long long)tv.tv_sec)*1000000;
ust += tv.tv_usec;
return ust;
}
static long long mstime(void) {
return ustime()/1000;
}
static void cliRefreshPrompt(void) {
if (config.eval_ldb) return;
sds prompt = sdsempty();
if (config.hostsocket != NULL) {
prompt = sdscatfmt(prompt,"redis %s",config.hostsocket);
} else {
char addr[256];
formatAddr(addr, sizeof(addr), config.conn_info.hostip, config.conn_info.hostport);
prompt = sdscatlen(prompt,addr,strlen(addr));
}
/* Add [dbnum] if needed */
if (config.dbnum != 0)
prompt = sdscatfmt(prompt,"[%i]",config.dbnum);
/* Add TX if in transaction state*/
if (config.in_multi)
prompt = sdscatlen(prompt,"(TX)",4);
if (config.pubsub_mode)
prompt = sdscatfmt(prompt,"(subscribed mode)");
/* Copy the prompt in the static buffer. */
prompt = sdscatlen(prompt,"> ",2);
snprintf(config.prompt,sizeof(config.prompt),"%s",prompt);
sdsfree(prompt);
}
/* Return the name of the dotfile for the specified 'dotfilename'.
* Normally it just concatenates user $HOME to the file specified
* in 'dotfilename'. However if the environment variable 'envoverride'
* is set, its value is taken as the path.
*
* The function returns NULL (if the file is /dev/null or cannot be
* obtained for some error), or an SDS string that must be freed by
* the user. */
static sds getDotfilePath(char *envoverride, char *dotfilename) {
char *path = NULL;
sds dotPath = NULL;
/* Check the env for a dotfile override. */
path = getenv(envoverride);
if (path != NULL && *path != '\0') {
if (!strcmp("/dev/null", path)) {
return NULL;
}
/* If the env is set, return it. */
dotPath = sdsnew(path);
} else {
char *home = getenv("HOME");
if (home != NULL && *home != '\0') {
/* If no override is set use $HOME/<dotfilename>. */
dotPath = sdscatprintf(sdsempty(), "%s/%s", home, dotfilename);
}
}
return dotPath;
}
static uint64_t dictSdsHash(const void *key) {
return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
}
static int dictSdsKeyCompare(dictCmpCache *cache, const void *key1, const void *key2)
{
int l1,l2;
UNUSED(cache);
l1 = sdslen((sds)key1);
l2 = sdslen((sds)key2);
if (l1 != l2) return 0;
return memcmp(key1, key2, l1) == 0;
}
static void dictSdsDestructor(dict *d, void *val)
{
UNUSED(d);
sdsfree(val);
}
void dictListDestructor(dict *d, void *val)
{
UNUSED(d);
listRelease((list*)val);
}
/* Erase the lines before printing, and returns the number of lines printed */
int cleanPrintfln(char *fmt, ...) {
va_list args;
char buf[1024]; /* limitation */
int char_count, line_count = 0;
/* Clear the line if in TTY */
if (IS_TTY_OR_FAKETTY()) {
printf("\033[2K\r");
}
va_start(args, fmt);
char_count = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
if (char_count >= (int)sizeof(buf)) {
fprintf(stderr, "Warning: String was trimmed in cleanPrintln\n");
}
char *position, *string = buf;
while ((position = strchr(string, '\n')) != NULL) {
int line_length = (int)(position - string);
printf("%.*s\n", line_length, string);
string = position + 1;
line_count++;
}
printf("%s\n", string);
return line_count + 1;
}
/*------------------------------------------------------------------------------
* Help functions
*--------------------------------------------------------------------------- */
#define CLI_HELP_COMMAND 1
#define CLI_HELP_GROUP 2
typedef struct {
int type;
int argc;
sds *argv;
sds full;
/* Only used for help on commands */
struct commandDocs docs;
} helpEntry;
static helpEntry *helpEntries = NULL;
static int helpEntriesLen = 0;
/* For backwards compatibility with pre-7.0 servers.
* cliLegacyInitHelp() sets up the helpEntries array with the command and group
* names from the commands.c file. However the Redis instance we are connecting
* to may support more commands, so this function integrates the previous
* entries with additional entries obtained using the COMMAND command
* available in recent versions of Redis. */
static void cliLegacyIntegrateHelp(void) {
if (cliConnect(CC_QUIET) == REDIS_ERR) return;
redisReply *reply = redisCommand(context, "COMMAND");
if (reply == NULL) return;
if (reply->type != REDIS_REPLY_ARRAY) {
freeReplyObject(reply);
return;
}
/* Scan the array reported by COMMAND and fill only the entries that
* don't already match what we have. */
for (size_t j = 0; j < reply->elements; j++) {
redisReply *entry = reply->element[j];
if (entry->type != REDIS_REPLY_ARRAY || entry->elements < 4 ||
entry->element[0]->type != REDIS_REPLY_STRING ||
entry->element[1]->type != REDIS_REPLY_INTEGER ||
entry->element[3]->type != REDIS_REPLY_INTEGER) return;
char *cmdname = entry->element[0]->str;
int i;
for (i = 0; i < helpEntriesLen; i++) {
helpEntry *he = helpEntries+i;
if (!strcasecmp(he->argv[0],cmdname))
break;
}
if (i != helpEntriesLen) continue;
helpEntriesLen++;
helpEntries = zrealloc(helpEntries,sizeof(helpEntry)*helpEntriesLen);
helpEntry *new = helpEntries+(helpEntriesLen-1);
new->argc = 1;
new->argv = zmalloc(sizeof(sds));
new->argv[0] = sdsnew(cmdname);
new->full = new->argv[0];
new->type = CLI_HELP_COMMAND;
sdstoupper(new->argv[0]);
new->docs.name = new->argv[0];
new->docs.args = NULL;
new->docs.numargs = 0;
new->docs.params = sdsempty();
int args = llabs(entry->element[1]->integer);
args--; /* Remove the command name itself. */
if (entry->element[3]->integer == 1) {
new->docs.params = sdscat(new->docs.params,"key ");
args--;
}
while(args-- > 0) new->docs.params = sdscat(new->docs.params,"arg ");
if (entry->element[1]->integer < 0)
new->docs.params = sdscat(new->docs.params,"...options...");
new->docs.summary = "Help not available";
new->docs.since = "Not known";
new->docs.group = "generic";
}
freeReplyObject(reply);
}
/* Concatenate a string to an sds string, but if it's empty substitute double quote marks. */
static sds sdscat_orempty(sds params, const char *value) {
if (value[0] == '\0') {
return sdscat(params, "\"\"");
}
return sdscat(params, value);
}
static sds makeHint(char **inputargv, int inputargc, int cmdlen, struct commandDocs docs);
static void cliAddCommandDocArg(cliCommandArg *cmdArg, redisReply *argMap);
static void cliMakeCommandDocArgs(redisReply *arguments, cliCommandArg *result) {
for (size_t j = 0; j < arguments->elements; j++) {
cliAddCommandDocArg(&result[j], arguments->element[j]);
}
}
static void cliAddCommandDocArg(cliCommandArg *cmdArg, redisReply *argMap) {
if (argMap->type != REDIS_REPLY_MAP && argMap->type != REDIS_REPLY_ARRAY) {
return;
}
for (size_t i = 0; i < argMap->elements; i += 2) {
assert(argMap->element[i]->type == REDIS_REPLY_STRING);
char *key = argMap->element[i]->str;
if (!strcmp(key, "name")) {
assert(argMap->element[i + 1]->type == REDIS_REPLY_STRING);
cmdArg->name = sdsnew(argMap->element[i + 1]->str);
} else if (!strcmp(key, "display_text")) {
assert(argMap->element[i + 1]->type == REDIS_REPLY_STRING);
cmdArg->display_text = sdsnew(argMap->element[i + 1]->str);
} else if (!strcmp(key, "token")) {
assert(argMap->element[i + 1]->type == REDIS_REPLY_STRING);
cmdArg->token = sdsnew(argMap->element[i + 1]->str);
} else if (!strcmp(key, "type")) {
assert(argMap->element[i + 1]->type == REDIS_REPLY_STRING);
char *type = argMap->element[i + 1]->str;
if (!strcmp(type, "string")) {
cmdArg->type = ARG_TYPE_STRING;
} else if (!strcmp(type, "integer")) {
cmdArg->type = ARG_TYPE_INTEGER;
} else if (!strcmp(type, "double")) {
cmdArg->type = ARG_TYPE_DOUBLE;
} else if (!strcmp(type, "key")) {
cmdArg->type = ARG_TYPE_KEY;
} else if (!strcmp(type, "pattern")) {
cmdArg->type = ARG_TYPE_PATTERN;
} else if (!strcmp(type, "unix-time")) {
cmdArg->type = ARG_TYPE_UNIX_TIME;
} else if (!strcmp(type, "pure-token")) {
cmdArg->type = ARG_TYPE_PURE_TOKEN;
} else if (!strcmp(type, "oneof")) {
cmdArg->type = ARG_TYPE_ONEOF;
} else if (!strcmp(type, "block")) {
cmdArg->type = ARG_TYPE_BLOCK;
}
} else if (!strcmp(key, "arguments")) {
redisReply *arguments = argMap->element[i + 1];
cmdArg->subargs = zcalloc(arguments->elements * sizeof(cliCommandArg));
cmdArg->numsubargs = arguments->elements;
cliMakeCommandDocArgs(arguments, cmdArg->subargs);
} else if (!strcmp(key, "flags")) {
redisReply *flags = argMap->element[i + 1];
assert(flags->type == REDIS_REPLY_SET || flags->type == REDIS_REPLY_ARRAY);
for (size_t j = 0; j < flags->elements; j++) {
assert(flags->element[j]->type == REDIS_REPLY_STATUS);
char *flag = flags->element[j]->str;
if (!strcmp(flag, "optional")) {
cmdArg->flags |= CMD_ARG_OPTIONAL;
} else if (!strcmp(flag, "multiple")) {
cmdArg->flags |= CMD_ARG_MULTIPLE;
} else if (!strcmp(flag, "multiple_token")) {
cmdArg->flags |= CMD_ARG_MULTIPLE_TOKEN;
}
}
}
}
}
/* Fill in the fields of a help entry for the command/subcommand name. */
static void cliFillInCommandHelpEntry(helpEntry *help, char *cmdname, char *subcommandname) {
help->argc = subcommandname ? 2 : 1;
help->argv = zmalloc(sizeof(sds) * help->argc);
help->argv[0] = sdsnew(cmdname);
sdstoupper(help->argv[0]);
if (subcommandname) {
/* Subcommand name may be two words separated by a pipe character. */
char *pipe = strchr(subcommandname, '|');
if (pipe != NULL) {
help->argv[1] = sdsnew(pipe + 1);
} else {
help->argv[1] = sdsnew(subcommandname);
}
sdstoupper(help->argv[1]);
}
sds fullname = sdsnew(help->argv[0]);
if (subcommandname) {
fullname = sdscat(fullname, " ");
fullname = sdscat(fullname, help->argv[1]);
}
help->full = fullname;
help->type = CLI_HELP_COMMAND;
help->docs.name = help->full;
help->docs.params = NULL;
help->docs.args = NULL;
help->docs.numargs = 0;
help->docs.since = NULL;
}
/* Initialize a command help entry for the command/subcommand described in 'specs'.
* 'next' points to the next help entry to be filled in.
* 'groups' is a set of command group names to be filled in.
* Returns a pointer to the next available position in the help entries table.
* If the command has subcommands, this is called recursively for the subcommands.
*/
static helpEntry *cliInitCommandHelpEntry(char *cmdname, char *subcommandname,
helpEntry *next, redisReply *specs,
dict *groups) {
helpEntry *help = next++;
cliFillInCommandHelpEntry(help, cmdname, subcommandname);
assert(specs->type == REDIS_REPLY_MAP || specs->type == REDIS_REPLY_ARRAY);
for (size_t j = 0; j < specs->elements; j += 2) {
assert(specs->element[j]->type == REDIS_REPLY_STRING);
char *key = specs->element[j]->str;
if (!strcmp(key, "summary")) {
redisReply *reply = specs->element[j + 1];
assert(reply->type == REDIS_REPLY_STRING);
help->docs.summary = sdsnew(reply->str);
} else if (!strcmp(key, "since")) {
redisReply *reply = specs->element[j + 1];
assert(reply->type == REDIS_REPLY_STRING);
help->docs.since = sdsnew(reply->str);
} else if (!strcmp(key, "group")) {
redisReply *reply = specs->element[j + 1];
assert(reply->type == REDIS_REPLY_STRING);
help->docs.group = sdsnew(reply->str);
sds group = sdsdup(help->docs.group);
if (dictAdd(groups, group, NULL) != DICT_OK) {
sdsfree(group);
}
} else if (!strcmp(key, "arguments")) {
redisReply *arguments = specs->element[j + 1];
assert(arguments->type == REDIS_REPLY_ARRAY);
help->docs.args = zcalloc(arguments->elements * sizeof(cliCommandArg));
help->docs.numargs = arguments->elements;
cliMakeCommandDocArgs(arguments, help->docs.args);
help->docs.params = makeHint(NULL, 0, 0, help->docs);
} else if (!strcmp(key, "subcommands")) {
redisReply *subcommands = specs->element[j + 1];
assert(subcommands->type == REDIS_REPLY_MAP || subcommands->type == REDIS_REPLY_ARRAY);
for (size_t i = 0; i < subcommands->elements; i += 2) {
assert(subcommands->element[i]->type == REDIS_REPLY_STRING);
char *subcommandname = subcommands->element[i]->str;
redisReply *subcommand = subcommands->element[i + 1];
assert(subcommand->type == REDIS_REPLY_MAP || subcommand->type == REDIS_REPLY_ARRAY);
next = cliInitCommandHelpEntry(cmdname, subcommandname, next, subcommand, groups);
}
}
}
return next;
}
/* Returns the total number of commands and subcommands in the command docs table. */
static size_t cliCountCommands(redisReply* commandTable) {
size_t numCommands = commandTable->elements / 2;
/* The command docs table maps command names to a map of their specs. */
for (size_t i = 0; i < commandTable->elements; i += 2) {
assert(commandTable->element[i]->type == REDIS_REPLY_STRING); /* Command name. */
assert(commandTable->element[i + 1]->type == REDIS_REPLY_MAP ||
commandTable->element[i + 1]->type == REDIS_REPLY_ARRAY);
redisReply *map = commandTable->element[i + 1];
for (size_t j = 0; j < map->elements; j += 2) {
assert(map->element[j]->type == REDIS_REPLY_STRING);
char *key = map->element[j]->str;
if (!strcmp(key, "subcommands")) {
redisReply *subcommands = map->element[j + 1];
assert(subcommands->type == REDIS_REPLY_MAP || subcommands->type == REDIS_REPLY_ARRAY);
numCommands += subcommands->elements / 2;
}
}
}
return numCommands;
}
/* Comparator for sorting help table entries. */
int helpEntryCompare(const void *entry1, const void *entry2) {
helpEntry *i1 = (helpEntry *)entry1;
helpEntry *i2 = (helpEntry *)entry2;
return strcmp(i1->full, i2->full);
}
/* Initializes command help entries for command groups.
* Called after the command help entries have already been filled in.
* Extends the help table with new entries for the command groups.
*/
void cliInitGroupHelpEntries(dict *groups) {
dictIterator iter;
dictEntry *entry;
helpEntry tmp;
int numGroups = dictSize(groups);
int pos = helpEntriesLen;
helpEntriesLen += numGroups;
helpEntries = zrealloc(helpEntries, sizeof(helpEntry)*helpEntriesLen);
dictInitIterator(&iter, groups);
for (entry = dictNext(&iter); entry != NULL; entry = dictNext(&iter)) {
tmp.argc = 1;
tmp.argv = zmalloc(sizeof(sds));
tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",(char *)dictGetKey(entry));
tmp.full = tmp.argv[0];
tmp.type = CLI_HELP_GROUP;
tmp.docs.name = NULL;
tmp.docs.params = NULL;
tmp.docs.args = NULL;
tmp.docs.numargs = 0;
tmp.docs.summary = NULL;
tmp.docs.since = NULL;
tmp.docs.group = NULL;
helpEntries[pos++] = tmp;
}
dictResetIterator(&iter);
}
/* Initializes help entries for all commands in the COMMAND DOCS reply. */
void cliInitCommandHelpEntries(redisReply *commandTable, dict *groups) {
helpEntry *next = helpEntries;
for (size_t i = 0; i < commandTable->elements; i += 2) {
assert(commandTable->element[i]->type == REDIS_REPLY_STRING);
char *cmdname = commandTable->element[i]->str;
assert(commandTable->element[i + 1]->type == REDIS_REPLY_MAP ||
commandTable->element[i + 1]->type == REDIS_REPLY_ARRAY);
redisReply *cmdspecs = commandTable->element[i + 1];
next = cliInitCommandHelpEntry(cmdname, NULL, next, cmdspecs, groups);
}
}
/* Does the server version support a command/argument only available "since" some version?
* Returns 1 when supported, or 0 when the "since" version is newer than "version". */
static int versionIsSupported(sds version, sds since) {
int i;
char *versionPos = version;
char *sincePos = since;
if (!since) {
return 1;
}
for (i = 0; i != 3; i++) {
int versionPart = atoi(versionPos);
int sincePart = atoi(sincePos);
if (versionPart > sincePart) {
return 1;
} else if (sincePart > versionPart) {
return 0;
}
versionPos = strchr(versionPos, '.');
sincePos = strchr(sincePos, '.');
/* If we finished to parse both `version` and `since`, it means they are equal */
if (!versionPos && !sincePos) return 1;
/* Different number of digits considered as not supported */
if (!versionPos || !sincePos) return 0;
versionPos++;
sincePos++;
}
return 0;
}
static void removeUnsupportedArgs(struct cliCommandArg *args, int *numargs, sds version) {
int i = 0, j;
while (i != *numargs) {
if (versionIsSupported(version, args[i].since)) {
if (args[i].subargs) {
removeUnsupportedArgs(args[i].subargs, &args[i].numsubargs, version);
}
i++;
continue;
}
for (j = i; j != *numargs - 1; j++) {
args[j] = args[j + 1];
}
(*numargs)--;
}
}
static helpEntry *cliLegacyInitCommandHelpEntry(char *cmdname, char *subcommandname,
helpEntry *next, struct commandDocs *command,
dict *groups, sds version) {
helpEntry *help = next++;
cliFillInCommandHelpEntry(help, cmdname, subcommandname);
help->docs.summary = sdsnew(command->summary);
help->docs.since = sdsnew(command->since);
help->docs.group = sdsnew(command->group);
sds group = sdsdup(help->docs.group);
if (dictAdd(groups, group, NULL) != DICT_OK) {
sdsfree(group);
}
if (command->args != NULL) {
help->docs.args = command->args;
help->docs.numargs = command->numargs;
if (version)
removeUnsupportedArgs(help->docs.args, &help->docs.numargs, version);
help->docs.params = makeHint(NULL, 0, 0, help->docs);
}
if (command->subcommands != NULL) {
for (size_t i = 0; command->subcommands[i].name != NULL; i++) {
if (!version || versionIsSupported(version, command->subcommands[i].since)) {
char *subcommandname = command->subcommands[i].name;
next = cliLegacyInitCommandHelpEntry(
cmdname, subcommandname, next, &command->subcommands[i], groups, version);
}
}
}
return next;
}
int cliLegacyInitCommandHelpEntries(struct commandDocs *commands, dict *groups, sds version) {
helpEntry *next = helpEntries;
for (size_t i = 0; commands[i].name != NULL; i++) {
if (!version || versionIsSupported(version, commands[i].since)) {
next = cliLegacyInitCommandHelpEntry(commands[i].name, NULL, next, &commands[i], groups, version);
}
}
return next - helpEntries;
}
/* Returns the total number of commands and subcommands in the command docs table,
* filtered by server version (if provided).
*/
static size_t cliLegacyCountCommands(struct commandDocs *commands, sds version) {
int numCommands = 0;
for (size_t i = 0; commands[i].name != NULL; i++) {
if (version && !versionIsSupported(version, commands[i].since)) {
continue;
}
numCommands++;
if (commands[i].subcommands != NULL) {
numCommands += cliLegacyCountCommands(commands[i].subcommands, version);
}
}
return numCommands;
}
/* Gets the server version string by calling INFO SERVER.
* Stores the result in config.server_version.
* When not connected, or not possible, returns NULL. */
static sds cliGetServerVersion(void) {
static const char *key = "\nredis_version:";
redisReply *serverInfo = NULL;
char *pos;
if (config.server_version != NULL) {
return config.server_version;
}
if (!context) return NULL;
serverInfo = redisCommand(context, "INFO SERVER");
if (serverInfo == NULL || serverInfo->type == REDIS_REPLY_ERROR) {
freeReplyObject(serverInfo);
return sdsempty();
}
assert(serverInfo->type == REDIS_REPLY_STRING || serverInfo->type == REDIS_REPLY_VERB);
sds info = serverInfo->str;
/* Finds the first appearance of "redis_version" in the INFO SERVER reply. */
pos = strstr(info, key);
if (pos) {
pos += strlen(key);
char *end = strchr(pos, '\r');
if (end) {
sds version = sdsnewlen(pos, end - pos);
freeReplyObject(serverInfo);
config.server_version = version;
return version;
}
}
freeReplyObject(serverInfo);
return NULL;
}
static void cliLegacyInitHelp(dict *groups) {
sds serverVersion = cliGetServerVersion();
/* Scan the commandDocs array and fill in the entries */
helpEntriesLen = cliLegacyCountCommands(redisCommandTable, serverVersion);
helpEntries = zmalloc(sizeof(helpEntry)*helpEntriesLen);
helpEntriesLen = cliLegacyInitCommandHelpEntries(redisCommandTable, groups, serverVersion);
cliInitGroupHelpEntries(groups);
qsort(helpEntries, helpEntriesLen, sizeof(helpEntry), helpEntryCompare);
dictRelease(groups);
}
/* cliInitHelp() sets up the helpEntries array with the command and group
* names and command descriptions obtained using the COMMAND DOCS command.
*/
static void cliInitHelp(void) {
/* Dict type for a set of strings, used to collect names of command groups. */
dictType groupsdt = {
dictSdsHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL, /* val destructor */
NULL /* allow to expand */
};
redisReply *commandTable;
dict *groups;
if (cliConnect(CC_QUIET) == REDIS_ERR) {
/* Can not connect to the server, but we still want to provide
* help, generate it only from the static cli_commands.c data instead. */
groups = dictCreate(&groupsdt);
cliLegacyInitHelp(groups);
return;
}
commandTable = redisCommand(context, "COMMAND DOCS");
if (commandTable == NULL || commandTable->type == REDIS_REPLY_ERROR) {
/* New COMMAND DOCS subcommand not supported - generate help from
* static cli_commands.c data instead. */
freeReplyObject(commandTable);
groups = dictCreate(&groupsdt);
cliLegacyInitHelp(groups);
cliLegacyIntegrateHelp();
return;
};
if (commandTable->type != REDIS_REPLY_MAP && commandTable->type != REDIS_REPLY_ARRAY) {
freeReplyObject(commandTable);
return;
}
/* Scan the array reported by COMMAND DOCS and fill in the entries */
helpEntriesLen = cliCountCommands(commandTable);
helpEntries = zmalloc(sizeof(helpEntry)*helpEntriesLen);
groups = dictCreate(&groupsdt);
cliInitCommandHelpEntries(commandTable, groups);
cliInitGroupHelpEntries(groups);
qsort(helpEntries, helpEntriesLen, sizeof(helpEntry), helpEntryCompare);
freeReplyObject(commandTable);
dictRelease(groups);
}
/* Output command help to stdout. */
static void cliOutputCommandHelp(struct commandDocs *help, int group) {
printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
if (help->since != NULL) {
printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since);
}
if (group) {
printf(" \x1b[33mgroup:\x1b[0m %s\r\n", help->group);
}
}
/* Print generic help. */
static void cliOutputGenericHelp(void) {
sds version = cliVersion();
printf(
"redis-cli %s\n"
"To get help about Redis commands type:\n"
" \"help @<group>\" to get a list of commands in <group>\n"
" \"help <command>\" for help on <command>\n"
" \"help <tab>\" to get a list of possible help topics\n"
" \"quit\" to exit\n"
"\n"
"To set redis-cli preferences:\n"
" \":set hints\" enable online hints\n"
" \":set nohints\" disable online hints\n"
"Set your preferences in ~/.redisclirc\n",
version
);
sdsfree(version);
}