]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
Spurious debugging printf removed.
[redis.git] / src / redis-cli.c
CommitLineData
ed9b544e 1/* Redis CLI (command line interface)
2 *
12d090d2 3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
ed9b544e 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
23d4709d 31#include "fmacros.h"
185cabda 32#include "version.h"
23d4709d 33
ed9b544e 34#include <stdio.h>
35#include <string.h>
36#include <stdlib.h>
37#include <unistd.h>
a88a2af6 38#include <ctype.h>
c0b3d423 39#include <errno.h>
b4b62c34 40#include <sys/stat.h>
3ce014c7 41#include <sys/time.h>
41945ba6 42#include <assert.h>
ed9b544e 43
7fc4ce13 44#include "hiredis.h"
ed9b544e 45#include "sds.h"
ed9b544e 46#include "zmalloc.h"
cf87ebf2 47#include "linenoise.h"
5397f2b5 48#include "help.h"
ed9b544e 49
ed9b544e 50#define REDIS_NOTUSED(V) ((void) V)
51
60893c6c 52#define OUTPUT_STANDARD 0
53#define OUTPUT_RAW 1
54#define OUTPUT_CSV 2
55
7fc4ce13 56static redisContext *context;
ed9b544e 57static struct config {
58 char *hostip;
59 int hostport;
7e91f971 60 char *hostsocket;
5762b7f0 61 long repeat;
18f63d8d 62 long interval;
62e920df 63 int dbnum;
5d15b520 64 int interactive;
36e5db6d 65 int shutdown;
249c3a7d 66 int monitor_mode;
67 int pubsub_mode;
43071993 68 int latency_mode;
623131d4 69 int cluster_mode;
70 int cluster_reissue_command;
b8283ab2 71 int slave_mode;
e1076851 72 int bigkeys;
bc63407b 73 int stdinarg; /* get last arg from stdin. (-x option) */
288799e0 74 char *auth;
60893c6c 75 int output; /* output mode, see OUTPUT_* defines */
65add0a3 76 sds mb_delim;
a5bd0848 77 char prompt[128];
e2f31389 78 char *eval;
ed9b544e 79} config;
80
a9158272 81static void usage();
11fd0c42 82char *redisGitSHA1(void);
c392edf5 83char *redisGitDirty(void);
c937aa89 84
3ce014c7 85/*------------------------------------------------------------------------------
86 * Utility functions
87 *--------------------------------------------------------------------------- */
88
89static 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
3f4eef21 99static void cliRefreshPrompt(void) {
a5bd0848 100 int len;
101
102 if (config.hostsocket != NULL)
103 len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
104 config.hostsocket);
3f4eef21 105 else
a5bd0848 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,"> ");
3f4eef21
PN
113}
114
a2a69d58
PN
115/*------------------------------------------------------------------------------
116 * Help functions
117 *--------------------------------------------------------------------------- */
118
b2cc45bf
PN
119#define CLI_HELP_COMMAND 1
120#define CLI_HELP_GROUP 2
121
122typedef 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
132static helpEntry *helpEntries;
133static int helpEntriesLen;
134
c392edf5
PN
135static 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
b2cc45bf
PN
149static 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
a2a69d58 177/* Output command help to stdout. */
41945ba6
PN
178static 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 }
a2a69d58
PN
185}
186
41945ba6
PN
187/* Print generic help. */
188static void cliOutputGenericHelp() {
c392edf5 189 sds version = cliVersion();
41945ba6
PN
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",
c392edf5 196 version
41945ba6 197 );
c392edf5 198 sdsfree(version);
a2a69d58
PN
199}
200
201/* Output all command help, filtering by group or command name. */
41945ba6 202static void cliOutputHelp(int argc, char **argv) {
b2cc45bf 203 int i, j, len;
41945ba6 204 int group = -1;
b2cc45bf
PN
205 helpEntry *entry;
206 struct commandHelp *help;
a2a69d58 207
41945ba6
PN
208 if (argc == 0) {
209 cliOutputGenericHelp();
a2a69d58 210 return;
41945ba6
PN
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 }
a2a69d58
PN
219 }
220
41945ba6 221 assert(argc > 0);
b2cc45bf
PN
222 for (i = 0; i < helpEntriesLen; i++) {
223 entry = &helpEntries[i];
224 if (entry->type != CLI_HELP_COMMAND) continue;
225
226 help = entry->org;
a2a69d58 227 if (group == -1) {
b2cc45bf
PN
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 }
a2a69d58
PN
236 }
237 } else {
238 if (group == help->group) {
41945ba6 239 cliOutputCommandHelp(help,0);
a2a69d58
PN
240 }
241 }
242 }
41945ba6
PN
243 printf("\r\n");
244}
245
41945ba6
PN
246static void completionCallback(const char *buf, linenoiseCompletions *lc) {
247 size_t startpos = 0;
248 int mask;
249 int i;
250 size_t matchlen;
b2cc45bf 251 sds tmp;
41945ba6
PN
252
253 if (strncasecmp(buf,"help ",5) == 0) {
254 startpos = 5;
255 while (isspace(buf[startpos])) startpos++;
b2cc45bf 256 mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
41945ba6 257 } else {
b2cc45bf 258 mask = CLI_HELP_COMMAND;
41945ba6
PN
259 }
260
b2cc45bf
PN
261 for (i = 0; i < helpEntriesLen; i++) {
262 if (!(helpEntries[i].type & mask)) continue;
41945ba6
PN
263
264 matchlen = strlen(buf+startpos);
b2cc45bf
PN
265 if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) {
266 tmp = sdsnewlen(buf,startpos);
267 tmp = sdscat(tmp,helpEntries[i].full);
41945ba6 268 linenoiseAddCompletion(lc,tmp);
b2cc45bf 269 sdsfree(tmp);
41945ba6
PN
270 }
271 }
a2a69d58
PN
272}
273
3ce014c7 274/*------------------------------------------------------------------------------
275 * Networking / parsing
276 *--------------------------------------------------------------------------- */
277
7fc4ce13
PN
278/* Send AUTH command to the server */
279static 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 */
292static int cliSelect() {
293 redisReply *reply;
7fc4ce13
PN
294 if (config.dbnum == 0) return REDIS_OK;
295
96e34b3c 296 reply = redisCommand(context,"SELECT %d",config.dbnum);
7fc4ce13
PN
297 if (reply != NULL) {
298 freeReplyObject(reply);
299 return REDIS_OK;
300 }
301 return REDIS_ERR;
302}
303
c0b3d423 304/* Connect to the client. If force is not zero the connection is performed
305 * even if there is already a connected socket. */
306static int cliConnect(int force) {
7fc4ce13
PN
307 if (context == NULL || force) {
308 if (context != NULL)
309 redisFree(context);
ed9b544e 310
7e91f971 311 if (config.hostsocket == NULL) {
7fc4ce13 312 context = redisConnect(config.hostip,config.hostport);
7e91f971 313 } else {
7fc4ce13 314 context = redisConnectUnix(config.hostsocket);
7e91f971 315 }
7fc4ce13
PN
316
317 if (context->err) {
7e91f971
PN
318 fprintf(stderr,"Could not connect to Redis at ");
319 if (config.hostsocket == NULL)
7fc4ce13 320 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
7e91f971 321 else
7fc4ce13
PN
322 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
323 redisFree(context);
324 context = NULL;
325 return REDIS_ERR;
6fa24622 326 }
ed9b544e 327
7fc4ce13
PN
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;
ed9b544e 333 }
7fc4ce13 334 return REDIS_OK;
ed9b544e 335}
336
a45f9a1a 337static void cliPrintContextError() {
7fc4ce13
PN
338 if (context == NULL) return;
339 fprintf(stderr,"Error: %s\n",context->errstr);
ed9b544e 340}
341
65add0a3 342static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
7fc4ce13
PN
343 sds out = sdsempty();
344 switch (r->type) {
345 case REDIS_REPLY_ERROR:
65add0a3 346 out = sdscatprintf(out,"(error) %s\n", r->str);
7fc4ce13
PN
347 break;
348 case REDIS_REPLY_STATUS:
7fc4ce13
PN
349 out = sdscat(out,r->str);
350 out = sdscat(out,"\n");
351 break;
352 case REDIS_REPLY_INTEGER:
65add0a3 353 out = sdscatprintf(out,"(integer) %lld\n",r->integer);
7fc4ce13
PN
354 break;
355 case REDIS_REPLY_STRING:
65add0a3
PN
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");
7fc4ce13
PN
360 break;
361 case REDIS_REPLY_NIL:
7fc4ce13
PN
362 out = sdscat(out,"(nil)\n");
363 break;
364 case REDIS_REPLY_ARRAY:
365 if (r->elements == 0) {
7fc4ce13 366 out = sdscat(out,"(empty list or set)\n");
c0b3d423 367 } else {
cfcd5d6d
PN
368 unsigned int i, idxlen = 0;
369 char _prefixlen[16];
370 char _prefixfmt[16];
371 sds _prefix;
7fc4ce13
PN
372 sds tmp;
373
cfcd5d6d
PN
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
7fc4ce13 389 for (i = 0; i < r->elements; i++) {
cfcd5d6d
PN
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 */
65add0a3 395 tmp = cliFormatReplyTTY(r->element[i],_prefix);
7fc4ce13
PN
396 out = sdscatlen(out,tmp,sdslen(tmp));
397 sdsfree(tmp);
398 }
cfcd5d6d 399 sdsfree(_prefix);
c0b3d423 400 }
7fc4ce13 401 break;
c937aa89 402 default:
7fc4ce13
PN
403 fprintf(stderr,"Unknown reply type: %d\n", r->type);
404 exit(1);
c937aa89 405 }
7fc4ce13 406 return out;
c937aa89 407}
408
65add0a3
PN
409static 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... */
ecc91094 416 break;
65add0a3 417 case REDIS_REPLY_ERROR:
ecc91094 418 out = sdscatlen(out,r->str,r->len);
419 out = sdscatlen(out,"\n",1);
420 break;
65add0a3
PN
421 case REDIS_REPLY_STATUS:
422 case REDIS_REPLY_STRING:
423 out = sdscatlen(out,r->str,r->len);
ecc91094 424 break;
65add0a3
PN
425 case REDIS_REPLY_INTEGER:
426 out = sdscatprintf(out,"%lld",r->integer);
ecc91094 427 break;
65add0a3
PN
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 }
ecc91094 435 break;
65add0a3
PN
436 default:
437 fprintf(stderr,"Unknown reply type: %d\n", r->type);
438 exit(1);
439 }
440 return out;
441}
442
60893c6c 443static 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
65add0a3 479static int cliReadReply(int output_raw_strings) {
8ce39260 480 void *_reply;
7fc4ce13 481 redisReply *reply;
24b09422 482 sds out = NULL;
623131d4 483 int output = 1;
7fc4ce13 484
8ce39260 485 if (redisGetReply(context,&_reply) != REDIS_OK) {
7fc4ce13
PN
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 }
a45f9a1a 495 cliPrintContextError();
496 exit(1);
7fc4ce13 497 return REDIS_ERR; /* avoid compiler warning */
62e920df 498 }
7fc4ce13 499
8ce39260 500 reply = (redisReply*)_reply;
623131d4 501
24b09422 502 /* Check if we need to connect to a different node and reissue the
503 * request. */
623131d4 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) {
65add0a3 533 out = cliFormatReplyRaw(reply);
65add0a3 534 } else {
60893c6c 535 if (config.output == OUTPUT_RAW) {
623131d4 536 out = cliFormatReplyRaw(reply);
537 out = sdscat(out,"\n");
60893c6c 538 } else if (config.output == OUTPUT_STANDARD) {
623131d4 539 out = cliFormatReplyTTY(reply,"");
60893c6c 540 } else if (config.output == OUTPUT_CSV) {
541 out = cliFormatReplyCSV(reply);
542 out = sdscat(out,"\n");
623131d4 543 }
65add0a3 544 }
623131d4 545 fwrite(out,sdslen(out),1,stdout);
546 sdsfree(out);
65add0a3 547 }
65add0a3 548 freeReplyObject(reply);
7fc4ce13 549 return REDIS_OK;
62e920df 550}
551
aab055ae 552static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 553 char *command = argv[0];
7fc4ce13 554 size_t *argvlen;
65add0a3 555 int j, output_raw;
ed9b544e 556
4eb3b3e9 557 if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
558 cliOutputHelp(--argc, ++argv);
559 return REDIS_OK;
560 }
561
a45f9a1a 562 if (context == NULL) return REDIS_ERR;
efcf948c 563
ecc91094 564 output_raw = 0;
565 if (!strcasecmp(command,"info") ||
566 (argc == 2 && !strcasecmp(command,"cluster") &&
567 (!strcasecmp(argv[1],"nodes") ||
3cd12b56 568 !strcasecmp(argv[1],"info"))) ||
569 (argc == 2 && !strcasecmp(command,"client") &&
570 !strcasecmp(argv[1],"list")))
571
ecc91094 572 {
573 output_raw = 1;
574 }
575
37dc9e5a
PN
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;
ed9b544e 580
7fc4ce13
PN
581 /* Setup argument length */
582 argvlen = malloc(argc*sizeof(size_t));
583 for (j = 0; j < argc; j++)
584 argvlen[j] = sdslen(argv[j]);
a2f4f871 585
aab055ae 586 while(repeat--) {
7fc4ce13 587 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
249c3a7d 588 while (config.monitor_mode) {
65add0a3 589 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
d9d8ccab 590 fflush(stdout);
621d5c19 591 }
592
249c3a7d 593 if (config.pubsub_mode) {
60893c6c 594 if (config.output != OUTPUT_RAW)
65add0a3 595 printf("Reading messages... (press Ctrl-C to quit)\n");
249c3a7d 596 while (1) {
65add0a3 597 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
249c3a7d 598 }
599 }
600
33753a73
PN
601 if (cliReadReply(output_raw) != REDIS_OK) {
602 free(argvlen);
7fc4ce13 603 return REDIS_ERR;
96e34b3c
PN
604 } else {
605 /* Store database number when SELECT was successfully executed. */
3f4eef21 606 if (!strcasecmp(command,"select") && argc == 2) {
96e34b3c 607 config.dbnum = atoi(argv[1]);
3f4eef21
PN
608 cliRefreshPrompt();
609 }
33753a73 610 }
18f63d8d 611 if (config.interval) usleep(config.interval);
612 fflush(stdout); /* Make it grep friendly */
ed9b544e 613 }
33753a73
PN
614
615 free(argvlen);
7fc4ce13 616 return REDIS_OK;
ed9b544e 617}
618
3ce014c7 619/*------------------------------------------------------------------------------
620 * User interface
621 *--------------------------------------------------------------------------- */
622
ed9b544e 623static int parseOptions(int argc, char **argv) {
624 int i;
625
626 for (i = 1; i < argc; i++) {
627 int lastarg = i==argc-1;
6cf5882c 628
ed9b544e 629 if (!strcmp(argv[i],"-h") && !lastarg) {
efcf948c 630 sdsfree(config.hostip);
e2f31389 631 config.hostip = sdsnew(argv[++i]);
a9158272 632 } else if (!strcmp(argv[i],"-h") && lastarg) {
633 usage();
f18e059e
PN
634 } else if (!strcmp(argv[i],"--help")) {
635 usage();
bc63407b 636 } else if (!strcmp(argv[i],"-x")) {
637 config.stdinarg = 1;
ed9b544e 638 } else if (!strcmp(argv[i],"-p") && !lastarg) {
e2f31389 639 config.hostport = atoi(argv[++i]);
7e91f971 640 } else if (!strcmp(argv[i],"-s") && !lastarg) {
e2f31389 641 config.hostsocket = argv[++i];
5762b7f0 642 } else if (!strcmp(argv[i],"-r") && !lastarg) {
e2f31389 643 config.repeat = strtoll(argv[++i],NULL,10);
18f63d8d 644 } else if (!strcmp(argv[i],"-i") && !lastarg) {
e2f31389 645 double seconds = atof(argv[++i]);
18f63d8d 646 config.interval = seconds*1000000;
62e920df 647 } else if (!strcmp(argv[i],"-n") && !lastarg) {
e2f31389 648 config.dbnum = atoi(argv[++i]);
fdfdae0f 649 } else if (!strcmp(argv[i],"-a") && !lastarg) {
e2f31389 650 config.auth = argv[++i];
65add0a3 651 } else if (!strcmp(argv[i],"--raw")) {
60893c6c 652 config.output = OUTPUT_RAW;
653 } else if (!strcmp(argv[i],"--csv")) {
654 config.output = OUTPUT_CSV;
43071993 655 } else if (!strcmp(argv[i],"--latency")) {
656 config.latency_mode = 1;
b8283ab2 657 } else if (!strcmp(argv[i],"--slave")) {
658 config.slave_mode = 1;
e1076851 659 } else if (!strcmp(argv[i],"--bigkeys")) {
660 config.bigkeys = 1;
e2f31389 661 } else if (!strcmp(argv[i],"--eval") && !lastarg) {
662 config.eval = argv[++i];
623131d4 663 } else if (!strcmp(argv[i],"-c")) {
664 config.cluster_mode = 1;
28c07c7b
PN
665 } else if (!strcmp(argv[i],"-d") && !lastarg) {
666 sdsfree(config.mb_delim);
e2f31389 667 config.mb_delim = sdsnew(argv[++i]);
f18e059e
PN
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);
185cabda 672 exit(0);
ed9b544e 673 } else {
674 break;
675 }
676 }
677 return i;
678}
679
680static 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
a9158272 697static void usage() {
f18e059e
PN
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"
18f63d8d 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"
f18e059e
PN
710" -n <db> Database number\n"
711" -x Read last argument from STDIN\n"
28c07c7b 712" -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
623131d4 713" -c Enable cluster mode (follow -ASK and -MOVED redirections)\n"
65add0a3 714" --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
43071993 715" --latency Enter a special mode continuously sampling latency.\n"
b8283ab2 716" --slave Simulate a slave showing commands received from the master.\n"
e1076851 717" --bigkeys Sample Redis keys looking for big keys.\n"
e2f31389 718" --eval <file> Send an EVAL command using the Lua script at <file>.\n"
f18e059e
PN
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"
18f63d8d 726" redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
e2f31389 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"
f18e059e
PN
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);
a9158272 735 exit(1);
736}
737
6cf5882c
MMDJ
738/* Turn the plain C strings into Sds strings */
739static char **convertToSds(int count, char** args) {
740 int j;
37dc9e5a 741 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
742
743 for(j = 0; j < count; j++)
744 sds[j] = sdsnew(args[j]);
745
746 return sds;
747}
748
a88a2af6 749#define LINE_BUFLEN 4096
6cf5882c 750static void repl() {
ca36b4ab
PN
751 sds historyfile = NULL;
752 int history = 0;
cbce5171 753 char *line;
ca36b4ab 754 int argc;
cbce5171 755 sds *argv;
6cf5882c 756
5d15b520 757 config.interactive = 1;
41945ba6 758 linenoiseSetCompletionCallback(completionCallback);
ce260f73 759
ca36b4ab
PN
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
3f4eef21
PN
770 cliRefreshPrompt();
771 while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
cf87ebf2 772 if (line[0] != '\0') {
cbce5171 773 argv = sdssplitargs(line,&argc);
ca36b4ab
PN
774 if (history) linenoiseHistoryAdd(line);
775 if (historyfile) linenoiseHistorySave(historyfile);
776
0439d792
PN
777 if (argv == NULL) {
778 printf("Invalid argument(s)\n");
db6a2e7f 779 free(line);
0439d792
PN
780 continue;
781 } else if (argc > 0) {
a88a2af6 782 if (strcasecmp(argv[0],"quit") == 0 ||
783 strcasecmp(argv[0],"exit") == 0)
c0b3d423 784 {
785 exit(0);
efcf948c 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);
bbac56c2 791 } else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
792 linenoiseClearScreen();
c0b3d423 793 } else {
3ce014c7 794 long long start_time = mstime(), elapsed;
4d19e344 795 int repeat, skipargs = 0;
c0b3d423 796
4d19e344 797 repeat = atoi(argv[0]);
aee7f997 798 if (argc > 1 && repeat) {
4d19e344 799 skipargs = 1;
800 } else {
801 repeat = 1;
802 }
803
623131d4 804 while (1) {
805 config.cluster_reissue_command = 0;
442c748d 806 if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
807 != REDIS_OK)
623131d4 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 }
c0b3d423 823 }
3ce014c7 824 elapsed = mstime()-start_time;
339b9dc2
PN
825 if (elapsed >= 500) {
826 printf("(%.2fs)\n",(double)elapsed/1000);
827 }
c0b3d423 828 }
a88a2af6 829 }
830 /* Free the argument vector */
ca36b4ab 831 while(argc--) sdsfree(argv[argc]);
8ff6a48b 832 zfree(argv);
6cf5882c 833 }
a88a2af6 834 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 835 free(line);
6cf5882c 836 }
6cf5882c
MMDJ
837 exit(0);
838}
839
b4b62c34
PN
840static int noninteractive(int argc, char **argv) {
841 int retval = 0;
bc63407b 842 if (config.stdinarg) {
b4b62c34
PN
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
e2f31389 853static 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
43071993 891static void latencyMode(void) {
892 redisReply *reply;
9de5d460 893 long long start, latency, min = 0, max = 0, tot = 0, count = 0;
43071993 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;
96674b6d 913 tot += latency;
43071993 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
b8283ab2 923static 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. */
24b09422 934 if (write(fd,"SYNC\r\n",6) != 6) {
935 fprintf(stderr,"Error writing to master\n");
936 exit(1);
937 }
b8283ab2 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);
60893c6c 952 fprintf(stderr,"SYNC with master, discarding %lld bytes of bulk tranfer...\n",
b8283ab2 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 }
60893c6c 964 fprintf(stderr,"SYNC done. Logging commands from master.\n");
b8283ab2 965
966 /* Now we can use the hiredis to read the incoming protocol. */
60893c6c 967 config.output = OUTPUT_CSV;
968 while (cliReadReply(0) == REDIS_OK);
b8283ab2 969}
970
e1076851 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
977static void findBigKeys(void) {
978 unsigned long long biggest[5] = {0,0,0,0,0};
979 unsigned long long samples = 0;
9de5d460 980 redisReply *reply1, *reply2, *reply3 = NULL;
e1076851 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) {
0122cc4f 1033 printf("[%6s] %s | biggest so far with size %llu\n",
e1076851 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
ed9b544e 1052int main(int argc, char **argv) {
6cf5882c 1053 int firstarg;
ed9b544e 1054
efcf948c 1055 config.hostip = sdsnew("127.0.0.1");
ed9b544e 1056 config.hostport = 6379;
7e91f971 1057 config.hostsocket = NULL;
5762b7f0 1058 config.repeat = 1;
18f63d8d 1059 config.interval = 0;
62e920df 1060 config.dbnum = 0;
5d15b520 1061 config.interactive = 0;
36e5db6d 1062 config.shutdown = 0;
249c3a7d 1063 config.monitor_mode = 0;
1064 config.pubsub_mode = 0;
43071993 1065 config.latency_mode = 0;
623131d4 1066 config.cluster_mode = 0;
e1076851 1067 config.slave_mode = 0;
1068 config.bigkeys = 0;
bc63407b 1069 config.stdinarg = 0;
288799e0 1070 config.auth = NULL;
e2f31389 1071 config.eval = NULL;
60893c6c 1072 if (!isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL))
1073 config.output = OUTPUT_RAW;
1074 else
1075 config.output = OUTPUT_STANDARD;
65add0a3 1076 config.mb_delim = sdsnew("\n");
41945ba6 1077 cliInitHelp();
99628c1a 1078
ed9b544e 1079 firstarg = parseOptions(argc,argv);
1080 argc -= firstarg;
1081 argv += firstarg;
ed9b544e 1082
43071993 1083 /* Start in latency mode if appropriate */
1084 if (config.latency_mode) {
1085 cliConnect(0);
1086 latencyMode();
1087 }
1088
b8283ab2 1089 /* Start in slave mode if appropriate */
1090 if (config.slave_mode) {
1091 cliConnect(0);
1092 slaveMode();
1093 }
1094
e1076851 1095 /* Find big keys */
1096 if (config.bigkeys) {
1097 cliConnect(0);
1098 findBigKeys();
1099 }
1100
abb731e5 1101 /* Start interactive mode when no command is provided */
e2f31389 1102 if (argc == 0 && !config.eval) {
a45f9a1a 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
b4b62c34 1109 /* Otherwise, we have some arguments to execute */
a45f9a1a 1110 if (cliConnect(0) != REDIS_OK) exit(1);
e2f31389 1111 if (config.eval) {
1112 return evalMode(argc,argv);
1113 } else {
1114 return noninteractive(argc,convertToSds(argc,argv));
1115 }
ed9b544e 1116}