]>
Commit | Line | Data |
---|---|---|
1 | /* Redis CLI (command line interface) | |
2 | * | |
3 | * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> | |
4 | * All rights reserved. | |
5 | * | |
6 | * Redistribution and use in source and binary forms, with or without | |
7 | * modification, are permitted provided that the following conditions are met: | |
8 | * | |
9 | * * Redistributions of source code must retain the above copyright notice, | |
10 | * this list of conditions and the following disclaimer. | |
11 | * * Redistributions in binary form must reproduce the above copyright | |
12 | * notice, this list of conditions and the following disclaimer in the | |
13 | * documentation and/or other materials provided with the distribution. | |
14 | * * Neither the name of Redis nor the names of its contributors may be used | |
15 | * to endorse or promote products derived from this software without | |
16 | * specific prior written permission. | |
17 | * | |
18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |
19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |
20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |
21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE | |
22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR | |
23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF | |
24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS | |
25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN | |
26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
28 | * POSSIBILITY OF SUCH DAMAGE. | |
29 | */ | |
30 | ||
31 | #include "fmacros.h" | |
32 | #include "version.h" | |
33 | ||
34 | #include <stdio.h> | |
35 | #include <string.h> | |
36 | #include <stdlib.h> | |
37 | #include <unistd.h> | |
38 | #include <ctype.h> | |
39 | #include <errno.h> | |
40 | #include <sys/stat.h> | |
41 | #include <sys/time.h> | |
42 | #include <assert.h> | |
43 | ||
44 | #include "hiredis.h" | |
45 | #include "sds.h" | |
46 | #include "zmalloc.h" | |
47 | #include "linenoise.h" | |
48 | #include "help.h" | |
49 | ||
50 | #define REDIS_NOTUSED(V) ((void) V) | |
51 | ||
52 | #define OUTPUT_STANDARD 0 | |
53 | #define OUTPUT_RAW 1 | |
54 | #define OUTPUT_CSV 2 | |
55 | ||
56 | static redisContext *context; | |
57 | static struct config { | |
58 | char *hostip; | |
59 | int hostport; | |
60 | char *hostsocket; | |
61 | long repeat; | |
62 | long interval; | |
63 | int dbnum; | |
64 | int interactive; | |
65 | int shutdown; | |
66 | int monitor_mode; | |
67 | int pubsub_mode; | |
68 | int latency_mode; | |
69 | int cluster_mode; | |
70 | int cluster_reissue_command; | |
71 | int slave_mode; | |
72 | int bigkeys; | |
73 | int stdinarg; /* get last arg from stdin. (-x option) */ | |
74 | char *auth; | |
75 | int output; /* output mode, see OUTPUT_* defines */ | |
76 | sds mb_delim; | |
77 | char prompt[128]; | |
78 | char *eval; | |
79 | } config; | |
80 | ||
81 | static void usage(); | |
82 | char *redisGitSHA1(void); | |
83 | char *redisGitDirty(void); | |
84 | ||
85 | /*------------------------------------------------------------------------------ | |
86 | * Utility functions | |
87 | *--------------------------------------------------------------------------- */ | |
88 | ||
89 | static long long mstime(void) { | |
90 | struct timeval tv; | |
91 | long long mst; | |
92 | ||
93 | gettimeofday(&tv, NULL); | |
94 | mst = ((long)tv.tv_sec)*1000; | |
95 | mst += tv.tv_usec/1000; | |
96 | return mst; | |
97 | } | |
98 | ||
99 | static void cliRefreshPrompt(void) { | |
100 | int len; | |
101 | ||
102 | if (config.hostsocket != NULL) | |
103 | len = snprintf(config.prompt,sizeof(config.prompt),"redis %s", | |
104 | config.hostsocket); | |
105 | else | |
106 | len = snprintf(config.prompt,sizeof(config.prompt),"redis %s:%d", | |
107 | config.hostip, config.hostport); | |
108 | /* Add [dbnum] if needed */ | |
109 | if (config.dbnum != 0) | |
110 | len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]", | |
111 | config.dbnum); | |
112 | snprintf(config.prompt+len,sizeof(config.prompt)-len,"> "); | |
113 | } | |
114 | ||
115 | /*------------------------------------------------------------------------------ | |
116 | * Help functions | |
117 | *--------------------------------------------------------------------------- */ | |
118 | ||
119 | #define CLI_HELP_COMMAND 1 | |
120 | #define CLI_HELP_GROUP 2 | |
121 | ||
122 | typedef struct { | |
123 | int type; | |
124 | int argc; | |
125 | sds *argv; | |
126 | sds full; | |
127 | ||
128 | /* Only used for help on commands */ | |
129 | struct commandHelp *org; | |
130 | } helpEntry; | |
131 | ||
132 | static helpEntry *helpEntries; | |
133 | static int helpEntriesLen; | |
134 | ||
135 | static sds cliVersion() { | |
136 | sds version; | |
137 | version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION); | |
138 | ||
139 | /* Add git commit and working tree status when available */ | |
140 | if (strtoll(redisGitSHA1(),NULL,16)) { | |
141 | version = sdscatprintf(version, " (git:%s", redisGitSHA1()); | |
142 | if (strtoll(redisGitDirty(),NULL,10)) | |
143 | version = sdscatprintf(version, "-dirty"); | |
144 | version = sdscat(version, ")"); | |
145 | } | |
146 | return version; | |
147 | } | |
148 | ||
149 | static void cliInitHelp() { | |
150 | int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp); | |
151 | int groupslen = sizeof(commandGroups)/sizeof(char*); | |
152 | int i, len, pos = 0; | |
153 | helpEntry tmp; | |
154 | ||
155 | helpEntriesLen = len = commandslen+groupslen; | |
156 | helpEntries = malloc(sizeof(helpEntry)*len); | |
157 | ||
158 | for (i = 0; i < groupslen; i++) { | |
159 | tmp.argc = 1; | |
160 | tmp.argv = malloc(sizeof(sds)); | |
161 | tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]); | |
162 | tmp.full = tmp.argv[0]; | |
163 | tmp.type = CLI_HELP_GROUP; | |
164 | tmp.org = NULL; | |
165 | helpEntries[pos++] = tmp; | |
166 | } | |
167 | ||
168 | for (i = 0; i < commandslen; i++) { | |
169 | tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc); | |
170 | tmp.full = sdsnew(commandHelp[i].name); | |
171 | tmp.type = CLI_HELP_COMMAND; | |
172 | tmp.org = &commandHelp[i]; | |
173 | helpEntries[pos++] = tmp; | |
174 | } | |
175 | } | |
176 | ||
177 | /* Output command help to stdout. */ | |
178 | static void cliOutputCommandHelp(struct commandHelp *help, int group) { | |
179 | printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params); | |
180 | printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary); | |
181 | printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since); | |
182 | if (group) { | |
183 | printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]); | |
184 | } | |
185 | } | |
186 | ||
187 | /* Print generic help. */ | |
188 | static void cliOutputGenericHelp() { | |
189 | sds version = cliVersion(); | |
190 | printf( | |
191 | "redis-cli %s\r\n" | |
192 | "Type: \"help @<group>\" to get a list of commands in <group>\r\n" | |
193 | " \"help <command>\" for help on <command>\r\n" | |
194 | " \"help <tab>\" to get a list of possible help topics\r\n" | |
195 | " \"quit\" to exit\r\n", | |
196 | version | |
197 | ); | |
198 | sdsfree(version); | |
199 | } | |
200 | ||
201 | /* Output all command help, filtering by group or command name. */ | |
202 | static void cliOutputHelp(int argc, char **argv) { | |
203 | int i, j, len; | |
204 | int group = -1; | |
205 | helpEntry *entry; | |
206 | struct commandHelp *help; | |
207 | ||
208 | if (argc == 0) { | |
209 | cliOutputGenericHelp(); | |
210 | return; | |
211 | } else if (argc > 0 && argv[0][0] == '@') { | |
212 | len = sizeof(commandGroups)/sizeof(char*); | |
213 | for (i = 0; i < len; i++) { | |
214 | if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) { | |
215 | group = i; | |
216 | break; | |
217 | } | |
218 | } | |
219 | } | |
220 | ||
221 | assert(argc > 0); | |
222 | for (i = 0; i < helpEntriesLen; i++) { | |
223 | entry = &helpEntries[i]; | |
224 | if (entry->type != CLI_HELP_COMMAND) continue; | |
225 | ||
226 | help = entry->org; | |
227 | if (group == -1) { | |
228 | /* Compare all arguments */ | |
229 | if (argc == entry->argc) { | |
230 | for (j = 0; j < argc; j++) { | |
231 | if (strcasecmp(argv[j],entry->argv[j]) != 0) break; | |
232 | } | |
233 | if (j == argc) { | |
234 | cliOutputCommandHelp(help,1); | |
235 | } | |
236 | } | |
237 | } else { | |
238 | if (group == help->group) { | |
239 | cliOutputCommandHelp(help,0); | |
240 | } | |
241 | } | |
242 | } | |
243 | printf("\r\n"); | |
244 | } | |
245 | ||
246 | static void completionCallback(const char *buf, linenoiseCompletions *lc) { | |
247 | size_t startpos = 0; | |
248 | int mask; | |
249 | int i; | |
250 | size_t matchlen; | |
251 | sds tmp; | |
252 | ||
253 | if (strncasecmp(buf,"help ",5) == 0) { | |
254 | startpos = 5; | |
255 | while (isspace(buf[startpos])) startpos++; | |
256 | mask = CLI_HELP_COMMAND | CLI_HELP_GROUP; | |
257 | } else { | |
258 | mask = CLI_HELP_COMMAND; | |
259 | } | |
260 | ||
261 | for (i = 0; i < helpEntriesLen; i++) { | |
262 | if (!(helpEntries[i].type & mask)) continue; | |
263 | ||
264 | matchlen = strlen(buf+startpos); | |
265 | if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) { | |
266 | tmp = sdsnewlen(buf,startpos); | |
267 | tmp = sdscat(tmp,helpEntries[i].full); | |
268 | linenoiseAddCompletion(lc,tmp); | |
269 | sdsfree(tmp); | |
270 | } | |
271 | } | |
272 | } | |
273 | ||
274 | /*------------------------------------------------------------------------------ | |
275 | * Networking / parsing | |
276 | *--------------------------------------------------------------------------- */ | |
277 | ||
278 | /* Send AUTH command to the server */ | |
279 | static int cliAuth() { | |
280 | redisReply *reply; | |
281 | if (config.auth == NULL) return REDIS_OK; | |
282 | ||
283 | reply = redisCommand(context,"AUTH %s",config.auth); | |
284 | if (reply != NULL) { | |
285 | freeReplyObject(reply); | |
286 | return REDIS_OK; | |
287 | } | |
288 | return REDIS_ERR; | |
289 | } | |
290 | ||
291 | /* Send SELECT dbnum to the server */ | |
292 | static int cliSelect() { | |
293 | redisReply *reply; | |
294 | if (config.dbnum == 0) return REDIS_OK; | |
295 | ||
296 | reply = redisCommand(context,"SELECT %d",config.dbnum); | |
297 | if (reply != NULL) { | |
298 | freeReplyObject(reply); | |
299 | return REDIS_OK; | |
300 | } | |
301 | return REDIS_ERR; | |
302 | } | |
303 | ||
304 | /* Connect to the client. If force is not zero the connection is performed | |
305 | * even if there is already a connected socket. */ | |
306 | static int cliConnect(int force) { | |
307 | if (context == NULL || force) { | |
308 | if (context != NULL) | |
309 | redisFree(context); | |
310 | ||
311 | if (config.hostsocket == NULL) { | |
312 | context = redisConnect(config.hostip,config.hostport); | |
313 | } else { | |
314 | context = redisConnectUnix(config.hostsocket); | |
315 | } | |
316 | ||
317 | if (context->err) { | |
318 | fprintf(stderr,"Could not connect to Redis at "); | |
319 | if (config.hostsocket == NULL) | |
320 | fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr); | |
321 | else | |
322 | fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr); | |
323 | redisFree(context); | |
324 | context = NULL; | |
325 | return REDIS_ERR; | |
326 | } | |
327 | ||
328 | /* Do AUTH and select the right DB. */ | |
329 | if (cliAuth() != REDIS_OK) | |
330 | return REDIS_ERR; | |
331 | if (cliSelect() != REDIS_OK) | |
332 | return REDIS_ERR; | |
333 | } | |
334 | return REDIS_OK; | |
335 | } | |
336 | ||
337 | static void cliPrintContextError() { | |
338 | if (context == NULL) return; | |
339 | fprintf(stderr,"Error: %s\n",context->errstr); | |
340 | } | |
341 | ||
342 | static sds cliFormatReplyTTY(redisReply *r, char *prefix) { | |
343 | sds out = sdsempty(); | |
344 | switch (r->type) { | |
345 | case REDIS_REPLY_ERROR: | |
346 | out = sdscatprintf(out,"(error) %s\n", r->str); | |
347 | break; | |
348 | case REDIS_REPLY_STATUS: | |
349 | out = sdscat(out,r->str); | |
350 | out = sdscat(out,"\n"); | |
351 | break; | |
352 | case REDIS_REPLY_INTEGER: | |
353 | out = sdscatprintf(out,"(integer) %lld\n",r->integer); | |
354 | break; | |
355 | case REDIS_REPLY_STRING: | |
356 | /* If you are producing output for the standard output we want | |
357 | * a more interesting output with quoted characters and so forth */ | |
358 | out = sdscatrepr(out,r->str,r->len); | |
359 | out = sdscat(out,"\n"); | |
360 | break; | |
361 | case REDIS_REPLY_NIL: | |
362 | out = sdscat(out,"(nil)\n"); | |
363 | break; | |
364 | case REDIS_REPLY_ARRAY: | |
365 | if (r->elements == 0) { | |
366 | out = sdscat(out,"(empty list or set)\n"); | |
367 | } else { | |
368 | unsigned int i, idxlen = 0; | |
369 | char _prefixlen[16]; | |
370 | char _prefixfmt[16]; | |
371 | sds _prefix; | |
372 | sds tmp; | |
373 | ||
374 | /* Calculate chars needed to represent the largest index */ | |
375 | i = r->elements; | |
376 | do { | |
377 | idxlen++; | |
378 | i /= 10; | |
379 | } while(i); | |
380 | ||
381 | /* Prefix for nested multi bulks should grow with idxlen+2 spaces */ | |
382 | memset(_prefixlen,' ',idxlen+2); | |
383 | _prefixlen[idxlen+2] = '\0'; | |
384 | _prefix = sdscat(sdsnew(prefix),_prefixlen); | |
385 | ||
386 | /* Setup prefix format for every entry */ | |
387 | snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen); | |
388 | ||
389 | for (i = 0; i < r->elements; i++) { | |
390 | /* Don't use the prefix for the first element, as the parent | |
391 | * caller already prepended the index number. */ | |
392 | out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1); | |
393 | ||
394 | /* Format the multi bulk entry */ | |
395 | tmp = cliFormatReplyTTY(r->element[i],_prefix); | |
396 | out = sdscatlen(out,tmp,sdslen(tmp)); | |
397 | sdsfree(tmp); | |
398 | } | |
399 | sdsfree(_prefix); | |
400 | } | |
401 | break; | |
402 | default: | |
403 | fprintf(stderr,"Unknown reply type: %d\n", r->type); | |
404 | exit(1); | |
405 | } | |
406 | return out; | |
407 | } | |
408 | ||
409 | static sds cliFormatReplyRaw(redisReply *r) { | |
410 | sds out = sdsempty(), tmp; | |
411 | size_t i; | |
412 | ||
413 | switch (r->type) { | |
414 | case REDIS_REPLY_NIL: | |
415 | /* Nothing... */ | |
416 | break; | |
417 | case REDIS_REPLY_ERROR: | |
418 | out = sdscatlen(out,r->str,r->len); | |
419 | out = sdscatlen(out,"\n",1); | |
420 | break; | |
421 | case REDIS_REPLY_STATUS: | |
422 | case REDIS_REPLY_STRING: | |
423 | out = sdscatlen(out,r->str,r->len); | |
424 | break; | |
425 | case REDIS_REPLY_INTEGER: | |
426 | out = sdscatprintf(out,"%lld",r->integer); | |
427 | break; | |
428 | case REDIS_REPLY_ARRAY: | |
429 | for (i = 0; i < r->elements; i++) { | |
430 | if (i > 0) out = sdscat(out,config.mb_delim); | |
431 | tmp = cliFormatReplyRaw(r->element[i]); | |
432 | out = sdscatlen(out,tmp,sdslen(tmp)); | |
433 | sdsfree(tmp); | |
434 | } | |
435 | break; | |
436 | default: | |
437 | fprintf(stderr,"Unknown reply type: %d\n", r->type); | |
438 | exit(1); | |
439 | } | |
440 | return out; | |
441 | } | |
442 | ||
443 | static sds cliFormatReplyCSV(redisReply *r) { | |
444 | unsigned int i; | |
445 | ||
446 | sds out = sdsempty(); | |
447 | switch (r->type) { | |
448 | case REDIS_REPLY_ERROR: | |
449 | out = sdscat(out,"ERROR,"); | |
450 | out = sdscatrepr(out,r->str,strlen(r->str)); | |
451 | break; | |
452 | case REDIS_REPLY_STATUS: | |
453 | out = sdscatrepr(out,r->str,r->len); | |
454 | break; | |
455 | case REDIS_REPLY_INTEGER: | |
456 | out = sdscatprintf(out,"%lld",r->integer); | |
457 | break; | |
458 | case REDIS_REPLY_STRING: | |
459 | out = sdscatrepr(out,r->str,r->len); | |
460 | break; | |
461 | case REDIS_REPLY_NIL: | |
462 | out = sdscat(out,"NIL\n"); | |
463 | break; | |
464 | case REDIS_REPLY_ARRAY: | |
465 | for (i = 0; i < r->elements; i++) { | |
466 | sds tmp = cliFormatReplyCSV(r->element[i]); | |
467 | out = sdscatlen(out,tmp,sdslen(tmp)); | |
468 | if (i != r->elements-1) out = sdscat(out,","); | |
469 | sdsfree(tmp); | |
470 | } | |
471 | break; | |
472 | default: | |
473 | fprintf(stderr,"Unknown reply type: %d\n", r->type); | |
474 | exit(1); | |
475 | } | |
476 | return out; | |
477 | } | |
478 | ||
479 | static int cliReadReply(int output_raw_strings) { | |
480 | void *_reply; | |
481 | redisReply *reply; | |
482 | sds out = NULL; | |
483 | int output = 1; | |
484 | ||
485 | if (redisGetReply(context,&_reply) != REDIS_OK) { | |
486 | if (config.shutdown) | |
487 | return REDIS_OK; | |
488 | if (config.interactive) { | |
489 | /* Filter cases where we should reconnect */ | |
490 | if (context->err == REDIS_ERR_IO && errno == ECONNRESET) | |
491 | return REDIS_ERR; | |
492 | if (context->err == REDIS_ERR_EOF) | |
493 | return REDIS_ERR; | |
494 | } | |
495 | cliPrintContextError(); | |
496 | exit(1); | |
497 | return REDIS_ERR; /* avoid compiler warning */ | |
498 | } | |
499 | ||
500 | reply = (redisReply*)_reply; | |
501 | ||
502 | /* Check if we need to connect to a different node and reissue the | |
503 | * request. */ | |
504 | if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR && | |
505 | (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK"))) | |
506 | { | |
507 | char *p = reply->str, *s; | |
508 | int slot; | |
509 | ||
510 | output = 0; | |
511 | /* Comments show the position of the pointer as: | |
512 | * | |
513 | * [S] for pointer 's' | |
514 | * [P] for pointer 'p' | |
515 | */ | |
516 | s = strchr(p,' '); /* MOVED[S]3999 127.0.0.1:6381 */ | |
517 | p = strchr(s+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */ | |
518 | *p = '\0'; | |
519 | slot = atoi(s+1); | |
520 | s = strchr(p+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */ | |
521 | *s = '\0'; | |
522 | sdsfree(config.hostip); | |
523 | config.hostip = sdsnew(p+1); | |
524 | config.hostport = atoi(s+1); | |
525 | if (config.interactive) | |
526 | printf("-> Redirected to slot [%d] located at %s:%d\n", | |
527 | slot, config.hostip, config.hostport); | |
528 | config.cluster_reissue_command = 1; | |
529 | } | |
530 | ||
531 | if (output) { | |
532 | if (output_raw_strings) { | |
533 | out = cliFormatReplyRaw(reply); | |
534 | } else { | |
535 | if (config.output == OUTPUT_RAW) { | |
536 | out = cliFormatReplyRaw(reply); | |
537 | out = sdscat(out,"\n"); | |
538 | } else if (config.output == OUTPUT_STANDARD) { | |
539 | out = cliFormatReplyTTY(reply,""); | |
540 | } else if (config.output == OUTPUT_CSV) { | |
541 | out = cliFormatReplyCSV(reply); | |
542 | out = sdscat(out,"\n"); | |
543 | } | |
544 | } | |
545 | fwrite(out,sdslen(out),1,stdout); | |
546 | sdsfree(out); | |
547 | } | |
548 | freeReplyObject(reply); | |
549 | return REDIS_OK; | |
550 | } | |
551 | ||
552 | static int cliSendCommand(int argc, char **argv, int repeat) { | |
553 | char *command = argv[0]; | |
554 | size_t *argvlen; | |
555 | int j, output_raw; | |
556 | ||
557 | if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) { | |
558 | cliOutputHelp(--argc, ++argv); | |
559 | return REDIS_OK; | |
560 | } | |
561 | ||
562 | if (context == NULL) return REDIS_ERR; | |
563 | ||
564 | output_raw = 0; | |
565 | if (!strcasecmp(command,"info") || | |
566 | (argc == 2 && !strcasecmp(command,"cluster") && | |
567 | (!strcasecmp(argv[1],"nodes") || | |
568 | !strcasecmp(argv[1],"info"))) || | |
569 | (argc == 2 && !strcasecmp(command,"client") && | |
570 | !strcasecmp(argv[1],"list"))) | |
571 | ||
572 | { | |
573 | output_raw = 1; | |
574 | } | |
575 | ||
576 | if (!strcasecmp(command,"shutdown")) config.shutdown = 1; | |
577 | if (!strcasecmp(command,"monitor")) config.monitor_mode = 1; | |
578 | if (!strcasecmp(command,"subscribe") || | |
579 | !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1; | |
580 | ||
581 | /* Setup argument length */ | |
582 | argvlen = malloc(argc*sizeof(size_t)); | |
583 | for (j = 0; j < argc; j++) | |
584 | argvlen[j] = sdslen(argv[j]); | |
585 | ||
586 | while(repeat--) { | |
587 | redisAppendCommandArgv(context,argc,(const char**)argv,argvlen); | |
588 | while (config.monitor_mode) { | |
589 | if (cliReadReply(output_raw) != REDIS_OK) exit(1); | |
590 | fflush(stdout); | |
591 | } | |
592 | ||
593 | if (config.pubsub_mode) { | |
594 | if (config.output != OUTPUT_RAW) | |
595 | printf("Reading messages... (press Ctrl-C to quit)\n"); | |
596 | while (1) { | |
597 | if (cliReadReply(output_raw) != REDIS_OK) exit(1); | |
598 | } | |
599 | } | |
600 | ||
601 | if (cliReadReply(output_raw) != REDIS_OK) { | |
602 | free(argvlen); | |
603 | return REDIS_ERR; | |
604 | } else { | |
605 | /* Store database number when SELECT was successfully executed. */ | |
606 | if (!strcasecmp(command,"select") && argc == 2) { | |
607 | config.dbnum = atoi(argv[1]); | |
608 | cliRefreshPrompt(); | |
609 | } | |
610 | } | |
611 | if (config.interval) usleep(config.interval); | |
612 | fflush(stdout); /* Make it grep friendly */ | |
613 | } | |
614 | ||
615 | free(argvlen); | |
616 | return REDIS_OK; | |
617 | } | |
618 | ||
619 | /*------------------------------------------------------------------------------ | |
620 | * User interface | |
621 | *--------------------------------------------------------------------------- */ | |
622 | ||
623 | static int parseOptions(int argc, char **argv) { | |
624 | int i; | |
625 | ||
626 | for (i = 1; i < argc; i++) { | |
627 | int lastarg = i==argc-1; | |
628 | ||
629 | if (!strcmp(argv[i],"-h") && !lastarg) { | |
630 | sdsfree(config.hostip); | |
631 | config.hostip = sdsnew(argv[++i]); | |
632 | } else if (!strcmp(argv[i],"-h") && lastarg) { | |
633 | usage(); | |
634 | } else if (!strcmp(argv[i],"--help")) { | |
635 | usage(); | |
636 | } else if (!strcmp(argv[i],"-x")) { | |
637 | config.stdinarg = 1; | |
638 | } else if (!strcmp(argv[i],"-p") && !lastarg) { | |
639 | config.hostport = atoi(argv[++i]); | |
640 | } else if (!strcmp(argv[i],"-s") && !lastarg) { | |
641 | config.hostsocket = argv[++i]; | |
642 | } else if (!strcmp(argv[i],"-r") && !lastarg) { | |
643 | config.repeat = strtoll(argv[++i],NULL,10); | |
644 | } else if (!strcmp(argv[i],"-i") && !lastarg) { | |
645 | double seconds = atof(argv[++i]); | |
646 | config.interval = seconds*1000000; | |
647 | } else if (!strcmp(argv[i],"-n") && !lastarg) { | |
648 | config.dbnum = atoi(argv[++i]); | |
649 | } else if (!strcmp(argv[i],"-a") && !lastarg) { | |
650 | config.auth = argv[++i]; | |
651 | } else if (!strcmp(argv[i],"--raw")) { | |
652 | config.output = OUTPUT_RAW; | |
653 | } else if (!strcmp(argv[i],"--csv")) { | |
654 | config.output = OUTPUT_CSV; | |
655 | } else if (!strcmp(argv[i],"--latency")) { | |
656 | config.latency_mode = 1; | |
657 | } else if (!strcmp(argv[i],"--slave")) { | |
658 | config.slave_mode = 1; | |
659 | } else if (!strcmp(argv[i],"--bigkeys")) { | |
660 | config.bigkeys = 1; | |
661 | } else if (!strcmp(argv[i],"--eval") && !lastarg) { | |
662 | config.eval = argv[++i]; | |
663 | } else if (!strcmp(argv[i],"-c")) { | |
664 | config.cluster_mode = 1; | |
665 | } else if (!strcmp(argv[i],"-d") && !lastarg) { | |
666 | sdsfree(config.mb_delim); | |
667 | config.mb_delim = sdsnew(argv[++i]); | |
668 | } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) { | |
669 | sds version = cliVersion(); | |
670 | printf("redis-cli %s\n", version); | |
671 | sdsfree(version); | |
672 | exit(0); | |
673 | } else { | |
674 | break; | |
675 | } | |
676 | } | |
677 | return i; | |
678 | } | |
679 | ||
680 | static sds readArgFromStdin(void) { | |
681 | char buf[1024]; | |
682 | sds arg = sdsempty(); | |
683 | ||
684 | while(1) { | |
685 | int nread = read(fileno(stdin),buf,1024); | |
686 | ||
687 | if (nread == 0) break; | |
688 | else if (nread == -1) { | |
689 | perror("Reading from standard input"); | |
690 | exit(1); | |
691 | } | |
692 | arg = sdscatlen(arg,buf,nread); | |
693 | } | |
694 | return arg; | |
695 | } | |
696 | ||
697 | static void usage() { | |
698 | sds version = cliVersion(); | |
699 | fprintf(stderr, | |
700 | "redis-cli %s\n" | |
701 | "\n" | |
702 | "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n" | |
703 | " -h <hostname> Server hostname (default: 127.0.0.1)\n" | |
704 | " -p <port> Server port (default: 6379)\n" | |
705 | " -s <socket> Server socket (overrides hostname and port)\n" | |
706 | " -a <password> Password to use when connecting to the server\n" | |
707 | " -r <repeat> Execute specified command N times\n" | |
708 | " -i <interval> When -r is used, waits <interval> seconds per command.\n" | |
709 | " It is possible to specify sub-second times like -i 0.1.\n" | |
710 | " -n <db> Database number\n" | |
711 | " -x Read last argument from STDIN\n" | |
712 | " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n" | |
713 | " -c Enable cluster mode (follow -ASK and -MOVED redirections)\n" | |
714 | " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n" | |
715 | " --latency Enter a special mode continuously sampling latency.\n" | |
716 | " --slave Simulate a slave showing commands received from the master.\n" | |
717 | " --bigkeys Sample Redis keys looking for big keys.\n" | |
718 | " --eval <file> Send an EVAL command using the Lua script at <file>.\n" | |
719 | " --help Output this help and exit\n" | |
720 | " --version Output version and exit\n" | |
721 | "\n" | |
722 | "Examples:\n" | |
723 | " cat /etc/passwd | redis-cli -x set mypasswd\n" | |
724 | " redis-cli get mypasswd\n" | |
725 | " redis-cli -r 100 lpush mylist x\n" | |
726 | " redis-cli -r 100 -i 1 info | grep used_memory_human:\n" | |
727 | " redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n" | |
728 | " (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n" | |
729 | "\n" | |
730 | "When no command is given, redis-cli starts in interactive mode.\n" | |
731 | "Type \"help\" in interactive mode for information on available commands.\n" | |
732 | "\n", | |
733 | version); | |
734 | sdsfree(version); | |
735 | exit(1); | |
736 | } | |
737 | ||
738 | /* Turn the plain C strings into Sds strings */ | |
739 | static char **convertToSds(int count, char** args) { | |
740 | int j; | |
741 | char **sds = zmalloc(sizeof(char*)*count); | |
742 | ||
743 | for(j = 0; j < count; j++) | |
744 | sds[j] = sdsnew(args[j]); | |
745 | ||
746 | return sds; | |
747 | } | |
748 | ||
749 | #define LINE_BUFLEN 4096 | |
750 | static void repl() { | |
751 | sds historyfile = NULL; | |
752 | int history = 0; | |
753 | char *line; | |
754 | int argc; | |
755 | sds *argv; | |
756 | ||
757 | config.interactive = 1; | |
758 | linenoiseSetCompletionCallback(completionCallback); | |
759 | ||
760 | /* Only use history when stdin is a tty. */ | |
761 | if (isatty(fileno(stdin))) { | |
762 | history = 1; | |
763 | ||
764 | if (getenv("HOME") != NULL) { | |
765 | historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME")); | |
766 | linenoiseHistoryLoad(historyfile); | |
767 | } | |
768 | } | |
769 | ||
770 | cliRefreshPrompt(); | |
771 | while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { | |
772 | if (line[0] != '\0') { | |
773 | argv = sdssplitargs(line,&argc); | |
774 | if (history) linenoiseHistoryAdd(line); | |
775 | if (historyfile) linenoiseHistorySave(historyfile); | |
776 | ||
777 | if (argv == NULL) { | |
778 | printf("Invalid argument(s)\n"); | |
779 | free(line); | |
780 | continue; | |
781 | } else if (argc > 0) { | |
782 | if (strcasecmp(argv[0],"quit") == 0 || | |
783 | strcasecmp(argv[0],"exit") == 0) | |
784 | { | |
785 | exit(0); | |
786 | } else if (argc == 3 && !strcasecmp(argv[0],"connect")) { | |
787 | sdsfree(config.hostip); | |
788 | config.hostip = sdsnew(argv[1]); | |
789 | config.hostport = atoi(argv[2]); | |
790 | cliConnect(1); | |
791 | } else if (argc == 1 && !strcasecmp(argv[0],"clear")) { | |
792 | linenoiseClearScreen(); | |
793 | } else { | |
794 | long long start_time = mstime(), elapsed; | |
795 | int repeat, skipargs = 0; | |
796 | ||
797 | repeat = atoi(argv[0]); | |
798 | if (argc > 1 && repeat) { | |
799 | skipargs = 1; | |
800 | } else { | |
801 | repeat = 1; | |
802 | } | |
803 | ||
804 | while (1) { | |
805 | config.cluster_reissue_command = 0; | |
806 | if (cliSendCommand(argc-skipargs,argv+skipargs,repeat) | |
807 | != REDIS_OK) | |
808 | { | |
809 | cliConnect(1); | |
810 | ||
811 | /* If we still cannot send the command print error. | |
812 | * We'll try to reconnect the next time. */ | |
813 | if (cliSendCommand(argc-skipargs,argv+skipargs,repeat) | |
814 | != REDIS_OK) | |
815 | cliPrintContextError(); | |
816 | } | |
817 | /* Issue the command again if we got redirected in cluster mode */ | |
818 | if (config.cluster_mode && config.cluster_reissue_command) { | |
819 | cliConnect(1); | |
820 | } else { | |
821 | break; | |
822 | } | |
823 | } | |
824 | elapsed = mstime()-start_time; | |
825 | if (elapsed >= 500) { | |
826 | printf("(%.2fs)\n",(double)elapsed/1000); | |
827 | } | |
828 | } | |
829 | } | |
830 | /* Free the argument vector */ | |
831 | while(argc--) sdsfree(argv[argc]); | |
832 | zfree(argv); | |
833 | } | |
834 | /* linenoise() returns malloc-ed lines like readline() */ | |
835 | free(line); | |
836 | } | |
837 | exit(0); | |
838 | } | |
839 | ||
840 | static int noninteractive(int argc, char **argv) { | |
841 | int retval = 0; | |
842 | if (config.stdinarg) { | |
843 | argv = zrealloc(argv, (argc+1)*sizeof(char*)); | |
844 | argv[argc] = readArgFromStdin(); | |
845 | retval = cliSendCommand(argc+1, argv, config.repeat); | |
846 | } else { | |
847 | /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */ | |
848 | retval = cliSendCommand(argc, argv, config.repeat); | |
849 | } | |
850 | return retval; | |
851 | } | |
852 | ||
853 | static int evalMode(int argc, char **argv) { | |
854 | sds script = sdsempty(); | |
855 | FILE *fp; | |
856 | char buf[1024]; | |
857 | size_t nread; | |
858 | char **argv2; | |
859 | int j, got_comma = 0, keys = 0; | |
860 | ||
861 | /* Load the script from the file, as an sds string. */ | |
862 | fp = fopen(config.eval,"r"); | |
863 | if (!fp) { | |
864 | fprintf(stderr, | |
865 | "Can't open file '%s': %s\n", config.eval, strerror(errno)); | |
866 | exit(1); | |
867 | } | |
868 | while((nread = fread(buf,1,sizeof(buf),fp)) != 0) { | |
869 | script = sdscatlen(script,buf,nread); | |
870 | } | |
871 | fclose(fp); | |
872 | ||
873 | /* Create our argument vector */ | |
874 | argv2 = zmalloc(sizeof(sds)*(argc+3)); | |
875 | argv2[0] = sdsnew("EVAL"); | |
876 | argv2[1] = script; | |
877 | for (j = 0; j < argc; j++) { | |
878 | if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) { | |
879 | got_comma = 1; | |
880 | continue; | |
881 | } | |
882 | argv2[j+3-got_comma] = sdsnew(argv[j]); | |
883 | if (!got_comma) keys++; | |
884 | } | |
885 | argv2[2] = sdscatprintf(sdsempty(),"%d",keys); | |
886 | ||
887 | /* Call it */ | |
888 | return cliSendCommand(argc+3-got_comma, argv2, config.repeat); | |
889 | } | |
890 | ||
891 | static void latencyMode(void) { | |
892 | redisReply *reply; | |
893 | long long start, latency, min = 0, max = 0, tot = 0, count = 0; | |
894 | double avg; | |
895 | ||
896 | if (!context) exit(1); | |
897 | while(1) { | |
898 | start = mstime(); | |
899 | reply = redisCommand(context,"PING"); | |
900 | if (reply == NULL) { | |
901 | fprintf(stderr,"\nI/O error\n"); | |
902 | exit(1); | |
903 | } | |
904 | latency = mstime()-start; | |
905 | freeReplyObject(reply); | |
906 | count++; | |
907 | if (count == 1) { | |
908 | min = max = tot = latency; | |
909 | avg = (double) latency; | |
910 | } else { | |
911 | if (latency < min) min = latency; | |
912 | if (latency > max) max = latency; | |
913 | tot += latency; | |
914 | avg = (double) tot/count; | |
915 | } | |
916 | printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)", | |
917 | min, max, avg, count); | |
918 | fflush(stdout); | |
919 | usleep(10000); | |
920 | } | |
921 | } | |
922 | ||
923 | static void slaveMode(void) { | |
924 | /* To start we need to send the SYNC command and return the payload. | |
925 | * The hiredis client lib does not understand this part of the protocol | |
926 | * and we don't want to mess with its buffers, so everything is performed | |
927 | * using direct low-level I/O. */ | |
928 | int fd = context->fd; | |
929 | char buf[1024], *p; | |
930 | ssize_t nread; | |
931 | unsigned long long payload; | |
932 | ||
933 | /* Send the SYNC command. */ | |
934 | if (write(fd,"SYNC\r\n",6) != 6) { | |
935 | fprintf(stderr,"Error writing to master\n"); | |
936 | exit(1); | |
937 | } | |
938 | ||
939 | /* Read $<payload>\r\n, making sure to read just up to "\n" */ | |
940 | p = buf; | |
941 | while(1) { | |
942 | nread = read(fd,p,1); | |
943 | if (nread <= 0) { | |
944 | fprintf(stderr,"Error reading bulk length while SYNCing\n"); | |
945 | exit(1); | |
946 | } | |
947 | if (*p == '\n') break; | |
948 | p++; | |
949 | } | |
950 | *p = '\0'; | |
951 | payload = strtoull(buf+1,NULL,10); | |
952 | fprintf(stderr,"SYNC with master, discarding %lld bytes of bulk tranfer...\n", | |
953 | payload); | |
954 | ||
955 | /* Discard the payload. */ | |
956 | while(payload) { | |
957 | nread = read(fd,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload); | |
958 | if (nread <= 0) { | |
959 | fprintf(stderr,"Error reading RDB payload while SYNCing\n"); | |
960 | exit(1); | |
961 | } | |
962 | payload -= nread; | |
963 | } | |
964 | fprintf(stderr,"SYNC done. Logging commands from master.\n"); | |
965 | ||
966 | /* Now we can use the hiredis to read the incoming protocol. */ | |
967 | config.output = OUTPUT_CSV; | |
968 | while (cliReadReply(0) == REDIS_OK); | |
969 | } | |
970 | ||
971 | #define TYPE_STRING 0 | |
972 | #define TYPE_LIST 1 | |
973 | #define TYPE_SET 2 | |
974 | #define TYPE_HASH 3 | |
975 | #define TYPE_ZSET 4 | |
976 | ||
977 | static void findBigKeys(void) { | |
978 | unsigned long long biggest[5] = {0,0,0,0,0}; | |
979 | unsigned long long samples = 0; | |
980 | redisReply *reply1, *reply2, *reply3 = NULL; | |
981 | char *sizecmd, *typename[] = {"string","list","set","hash","zset"}; | |
982 | int type; | |
983 | ||
984 | printf("\n# Press ctrl+c when you have had enough of it... :)\n"); | |
985 | printf("# You can use -i 0.1 to sleep 0.1 sec every 100 sampled keys\n"); | |
986 | printf("# in order to reduce server load (usually not needed).\n\n"); | |
987 | while(1) { | |
988 | /* Sample with RANDOMKEY */ | |
989 | reply1 = redisCommand(context,"RANDOMKEY"); | |
990 | if (reply1 == NULL) { | |
991 | fprintf(stderr,"\nI/O error\n"); | |
992 | exit(1); | |
993 | } else if (reply1->type == REDIS_REPLY_ERROR) { | |
994 | fprintf(stderr, "RANDOMKEY error: %s\n", | |
995 | reply1->str); | |
996 | exit(1); | |
997 | } | |
998 | /* Get the key type */ | |
999 | reply2 = redisCommand(context,"TYPE %s",reply1->str); | |
1000 | assert(reply2 && reply2->type == REDIS_REPLY_STATUS); | |
1001 | samples++; | |
1002 | ||
1003 | /* Get the key "size" */ | |
1004 | if (!strcmp(reply2->str,"string")) { | |
1005 | sizecmd = "STRLEN"; | |
1006 | type = TYPE_STRING; | |
1007 | } else if (!strcmp(reply2->str,"list")) { | |
1008 | sizecmd = "LLEN"; | |
1009 | type = TYPE_LIST; | |
1010 | } else if (!strcmp(reply2->str,"set")) { | |
1011 | sizecmd = "SCARD"; | |
1012 | type = TYPE_SET; | |
1013 | } else if (!strcmp(reply2->str,"hash")) { | |
1014 | sizecmd = "HLEN"; | |
1015 | type = TYPE_HASH; | |
1016 | } else if (!strcmp(reply2->str,"zset")) { | |
1017 | sizecmd = "ZCARD"; | |
1018 | type = TYPE_ZSET; | |
1019 | } else if (!strcmp(reply2->str,"none")) { | |
1020 | freeReplyObject(reply1); | |
1021 | freeReplyObject(reply2); | |
1022 | freeReplyObject(reply3); | |
1023 | continue; | |
1024 | } else { | |
1025 | fprintf(stderr, "Unknown key type '%s' for key '%s'\n", | |
1026 | reply2->str, reply1->str); | |
1027 | exit(1); | |
1028 | } | |
1029 | ||
1030 | reply3 = redisCommand(context,"%s %s", sizecmd, reply1->str); | |
1031 | if (reply3 && reply3->type == REDIS_REPLY_INTEGER) { | |
1032 | if (biggest[type] < reply3->integer) { | |
1033 | printf("[%6s] %s | biggest so far with size %llu\n", | |
1034 | typename[type], reply1->str, | |
1035 | (unsigned long long) reply3->integer); | |
1036 | biggest[type] = reply3->integer; | |
1037 | } | |
1038 | } | |
1039 | ||
1040 | if ((samples % 1000000) == 0) | |
1041 | printf("(%llu keys sampled)\n", samples); | |
1042 | ||
1043 | if ((samples % 100) == 0 && config.interval) | |
1044 | usleep(config.interval); | |
1045 | ||
1046 | freeReplyObject(reply1); | |
1047 | freeReplyObject(reply2); | |
1048 | if (reply3) freeReplyObject(reply3); | |
1049 | } | |
1050 | } | |
1051 | ||
1052 | int main(int argc, char **argv) { | |
1053 | int firstarg; | |
1054 | ||
1055 | config.hostip = sdsnew("127.0.0.1"); | |
1056 | config.hostport = 6379; | |
1057 | config.hostsocket = NULL; | |
1058 | config.repeat = 1; | |
1059 | config.interval = 0; | |
1060 | config.dbnum = 0; | |
1061 | config.interactive = 0; | |
1062 | config.shutdown = 0; | |
1063 | config.monitor_mode = 0; | |
1064 | config.pubsub_mode = 0; | |
1065 | config.latency_mode = 0; | |
1066 | config.cluster_mode = 0; | |
1067 | config.slave_mode = 0; | |
1068 | config.bigkeys = 0; | |
1069 | config.stdinarg = 0; | |
1070 | config.auth = NULL; | |
1071 | config.eval = NULL; | |
1072 | if (!isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL)) | |
1073 | config.output = OUTPUT_RAW; | |
1074 | else | |
1075 | config.output = OUTPUT_STANDARD; | |
1076 | config.mb_delim = sdsnew("\n"); | |
1077 | cliInitHelp(); | |
1078 | ||
1079 | firstarg = parseOptions(argc,argv); | |
1080 | argc -= firstarg; | |
1081 | argv += firstarg; | |
1082 | ||
1083 | /* Start in latency mode if appropriate */ | |
1084 | if (config.latency_mode) { | |
1085 | cliConnect(0); | |
1086 | latencyMode(); | |
1087 | } | |
1088 | ||
1089 | /* Start in slave mode if appropriate */ | |
1090 | if (config.slave_mode) { | |
1091 | cliConnect(0); | |
1092 | slaveMode(); | |
1093 | } | |
1094 | ||
1095 | /* Find big keys */ | |
1096 | if (config.bigkeys) { | |
1097 | cliConnect(0); | |
1098 | findBigKeys(); | |
1099 | } | |
1100 | ||
1101 | /* Start interactive mode when no command is provided */ | |
1102 | if (argc == 0 && !config.eval) { | |
1103 | /* Note that in repl mode we don't abort on connection error. | |
1104 | * A new attempt will be performed for every command send. */ | |
1105 | cliConnect(0); | |
1106 | repl(); | |
1107 | } | |
1108 | ||
1109 | /* Otherwise, we have some arguments to execute */ | |
1110 | if (cliConnect(0) != REDIS_OK) exit(1); | |
1111 | if (config.eval) { | |
1112 | return evalMode(argc,argv); | |
1113 | } else { | |
1114 | return noninteractive(argc,convertToSds(argc,argv)); | |
1115 | } | |
1116 | } |