]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
The universe is 80 columns wide, accept it.
[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
7fc4ce13 52static redisContext *context;
ed9b544e 53static struct config {
54 char *hostip;
55 int hostport;
7e91f971 56 char *hostsocket;
5762b7f0 57 long repeat;
18f63d8d 58 long interval;
62e920df 59 int dbnum;
5d15b520 60 int interactive;
36e5db6d 61 int shutdown;
249c3a7d 62 int monitor_mode;
63 int pubsub_mode;
43071993 64 int latency_mode;
623131d4 65 int cluster_mode;
66 int cluster_reissue_command;
bc63407b 67 int stdinarg; /* get last arg from stdin. (-x option) */
288799e0 68 char *auth;
65add0a3
PN
69 int raw_output; /* output mode per command */
70 sds mb_delim;
a5bd0848 71 char prompt[128];
e2f31389 72 char *eval;
ed9b544e 73} config;
74
a9158272 75static void usage();
11fd0c42 76char *redisGitSHA1(void);
c392edf5 77char *redisGitDirty(void);
c937aa89 78
3ce014c7 79/*------------------------------------------------------------------------------
80 * Utility functions
81 *--------------------------------------------------------------------------- */
82
83static long long mstime(void) {
84 struct timeval tv;
85 long long mst;
86
87 gettimeofday(&tv, NULL);
88 mst = ((long)tv.tv_sec)*1000;
89 mst += tv.tv_usec/1000;
90 return mst;
91}
92
3f4eef21 93static void cliRefreshPrompt(void) {
a5bd0848 94 int len;
95
96 if (config.hostsocket != NULL)
97 len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
98 config.hostsocket);
3f4eef21 99 else
a5bd0848 100 len = snprintf(config.prompt,sizeof(config.prompt),"redis %s:%d",
101 config.hostip, config.hostport);
102 /* Add [dbnum] if needed */
103 if (config.dbnum != 0)
104 len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
105 config.dbnum);
106 snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
3f4eef21
PN
107}
108
a2a69d58
PN
109/*------------------------------------------------------------------------------
110 * Help functions
111 *--------------------------------------------------------------------------- */
112
b2cc45bf
PN
113#define CLI_HELP_COMMAND 1
114#define CLI_HELP_GROUP 2
115
116typedef struct {
117 int type;
118 int argc;
119 sds *argv;
120 sds full;
121
122 /* Only used for help on commands */
123 struct commandHelp *org;
124} helpEntry;
125
126static helpEntry *helpEntries;
127static int helpEntriesLen;
128
c392edf5
PN
129static sds cliVersion() {
130 sds version;
131 version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);
132
133 /* Add git commit and working tree status when available */
134 if (strtoll(redisGitSHA1(),NULL,16)) {
135 version = sdscatprintf(version, " (git:%s", redisGitSHA1());
136 if (strtoll(redisGitDirty(),NULL,10))
137 version = sdscatprintf(version, "-dirty");
138 version = sdscat(version, ")");
139 }
140 return version;
141}
142
b2cc45bf
PN
143static void cliInitHelp() {
144 int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
145 int groupslen = sizeof(commandGroups)/sizeof(char*);
146 int i, len, pos = 0;
147 helpEntry tmp;
148
149 helpEntriesLen = len = commandslen+groupslen;
150 helpEntries = malloc(sizeof(helpEntry)*len);
151
152 for (i = 0; i < groupslen; i++) {
153 tmp.argc = 1;
154 tmp.argv = malloc(sizeof(sds));
155 tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]);
156 tmp.full = tmp.argv[0];
157 tmp.type = CLI_HELP_GROUP;
158 tmp.org = NULL;
159 helpEntries[pos++] = tmp;
160 }
161
162 for (i = 0; i < commandslen; i++) {
163 tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc);
164 tmp.full = sdsnew(commandHelp[i].name);
165 tmp.type = CLI_HELP_COMMAND;
166 tmp.org = &commandHelp[i];
167 helpEntries[pos++] = tmp;
168 }
169}
170
a2a69d58 171/* Output command help to stdout. */
41945ba6
PN
172static void cliOutputCommandHelp(struct commandHelp *help, int group) {
173 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
174 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
175 printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since);
176 if (group) {
177 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
178 }
a2a69d58
PN
179}
180
41945ba6
PN
181/* Print generic help. */
182static void cliOutputGenericHelp() {
c392edf5 183 sds version = cliVersion();
41945ba6
PN
184 printf(
185 "redis-cli %s\r\n"
186 "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
187 " \"help <command>\" for help on <command>\r\n"
188 " \"help <tab>\" to get a list of possible help topics\r\n"
189 " \"quit\" to exit\r\n",
c392edf5 190 version
41945ba6 191 );
c392edf5 192 sdsfree(version);
a2a69d58
PN
193}
194
195/* Output all command help, filtering by group or command name. */
41945ba6 196static void cliOutputHelp(int argc, char **argv) {
b2cc45bf 197 int i, j, len;
41945ba6 198 int group = -1;
b2cc45bf
PN
199 helpEntry *entry;
200 struct commandHelp *help;
a2a69d58 201
41945ba6
PN
202 if (argc == 0) {
203 cliOutputGenericHelp();
a2a69d58 204 return;
41945ba6
PN
205 } else if (argc > 0 && argv[0][0] == '@') {
206 len = sizeof(commandGroups)/sizeof(char*);
207 for (i = 0; i < len; i++) {
208 if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) {
209 group = i;
210 break;
211 }
212 }
a2a69d58
PN
213 }
214
41945ba6 215 assert(argc > 0);
b2cc45bf
PN
216 for (i = 0; i < helpEntriesLen; i++) {
217 entry = &helpEntries[i];
218 if (entry->type != CLI_HELP_COMMAND) continue;
219
220 help = entry->org;
a2a69d58 221 if (group == -1) {
b2cc45bf
PN
222 /* Compare all arguments */
223 if (argc == entry->argc) {
224 for (j = 0; j < argc; j++) {
225 if (strcasecmp(argv[j],entry->argv[j]) != 0) break;
226 }
227 if (j == argc) {
228 cliOutputCommandHelp(help,1);
229 }
a2a69d58
PN
230 }
231 } else {
232 if (group == help->group) {
41945ba6 233 cliOutputCommandHelp(help,0);
a2a69d58
PN
234 }
235 }
236 }
41945ba6
PN
237 printf("\r\n");
238}
239
41945ba6
PN
240static void completionCallback(const char *buf, linenoiseCompletions *lc) {
241 size_t startpos = 0;
242 int mask;
243 int i;
244 size_t matchlen;
b2cc45bf 245 sds tmp;
41945ba6
PN
246
247 if (strncasecmp(buf,"help ",5) == 0) {
248 startpos = 5;
249 while (isspace(buf[startpos])) startpos++;
b2cc45bf 250 mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
41945ba6 251 } else {
b2cc45bf 252 mask = CLI_HELP_COMMAND;
41945ba6
PN
253 }
254
b2cc45bf
PN
255 for (i = 0; i < helpEntriesLen; i++) {
256 if (!(helpEntries[i].type & mask)) continue;
41945ba6
PN
257
258 matchlen = strlen(buf+startpos);
b2cc45bf
PN
259 if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) {
260 tmp = sdsnewlen(buf,startpos);
261 tmp = sdscat(tmp,helpEntries[i].full);
41945ba6 262 linenoiseAddCompletion(lc,tmp);
b2cc45bf 263 sdsfree(tmp);
41945ba6
PN
264 }
265 }
a2a69d58
PN
266}
267
3ce014c7 268/*------------------------------------------------------------------------------
269 * Networking / parsing
270 *--------------------------------------------------------------------------- */
271
7fc4ce13
PN
272/* Send AUTH command to the server */
273static int cliAuth() {
274 redisReply *reply;
275 if (config.auth == NULL) return REDIS_OK;
276
277 reply = redisCommand(context,"AUTH %s",config.auth);
278 if (reply != NULL) {
279 freeReplyObject(reply);
280 return REDIS_OK;
281 }
282 return REDIS_ERR;
283}
284
285/* Send SELECT dbnum to the server */
286static int cliSelect() {
287 redisReply *reply;
7fc4ce13
PN
288 if (config.dbnum == 0) return REDIS_OK;
289
96e34b3c 290 reply = redisCommand(context,"SELECT %d",config.dbnum);
7fc4ce13
PN
291 if (reply != NULL) {
292 freeReplyObject(reply);
293 return REDIS_OK;
294 }
295 return REDIS_ERR;
296}
297
c0b3d423 298/* Connect to the client. If force is not zero the connection is performed
299 * even if there is already a connected socket. */
300static int cliConnect(int force) {
7fc4ce13
PN
301 if (context == NULL || force) {
302 if (context != NULL)
303 redisFree(context);
ed9b544e 304
7e91f971 305 if (config.hostsocket == NULL) {
7fc4ce13 306 context = redisConnect(config.hostip,config.hostport);
7e91f971 307 } else {
7fc4ce13 308 context = redisConnectUnix(config.hostsocket);
7e91f971 309 }
7fc4ce13
PN
310
311 if (context->err) {
7e91f971
PN
312 fprintf(stderr,"Could not connect to Redis at ");
313 if (config.hostsocket == NULL)
7fc4ce13 314 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
7e91f971 315 else
7fc4ce13
PN
316 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
317 redisFree(context);
318 context = NULL;
319 return REDIS_ERR;
6fa24622 320 }
ed9b544e 321
7fc4ce13
PN
322 /* Do AUTH and select the right DB. */
323 if (cliAuth() != REDIS_OK)
324 return REDIS_ERR;
325 if (cliSelect() != REDIS_OK)
326 return REDIS_ERR;
ed9b544e 327 }
7fc4ce13 328 return REDIS_OK;
ed9b544e 329}
330
a45f9a1a 331static void cliPrintContextError() {
7fc4ce13
PN
332 if (context == NULL) return;
333 fprintf(stderr,"Error: %s\n",context->errstr);
ed9b544e 334}
335
65add0a3 336static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
7fc4ce13
PN
337 sds out = sdsempty();
338 switch (r->type) {
339 case REDIS_REPLY_ERROR:
65add0a3 340 out = sdscatprintf(out,"(error) %s\n", r->str);
7fc4ce13
PN
341 break;
342 case REDIS_REPLY_STATUS:
7fc4ce13
PN
343 out = sdscat(out,r->str);
344 out = sdscat(out,"\n");
345 break;
346 case REDIS_REPLY_INTEGER:
65add0a3 347 out = sdscatprintf(out,"(integer) %lld\n",r->integer);
7fc4ce13
PN
348 break;
349 case REDIS_REPLY_STRING:
65add0a3
PN
350 /* If you are producing output for the standard output we want
351 * a more interesting output with quoted characters and so forth */
352 out = sdscatrepr(out,r->str,r->len);
353 out = sdscat(out,"\n");
7fc4ce13
PN
354 break;
355 case REDIS_REPLY_NIL:
7fc4ce13
PN
356 out = sdscat(out,"(nil)\n");
357 break;
358 case REDIS_REPLY_ARRAY:
359 if (r->elements == 0) {
7fc4ce13 360 out = sdscat(out,"(empty list or set)\n");
c0b3d423 361 } else {
cfcd5d6d
PN
362 unsigned int i, idxlen = 0;
363 char _prefixlen[16];
364 char _prefixfmt[16];
365 sds _prefix;
7fc4ce13
PN
366 sds tmp;
367
cfcd5d6d
PN
368 /* Calculate chars needed to represent the largest index */
369 i = r->elements;
370 do {
371 idxlen++;
372 i /= 10;
373 } while(i);
374
375 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
376 memset(_prefixlen,' ',idxlen+2);
377 _prefixlen[idxlen+2] = '\0';
378 _prefix = sdscat(sdsnew(prefix),_prefixlen);
379
380 /* Setup prefix format for every entry */
381 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
382
7fc4ce13 383 for (i = 0; i < r->elements; i++) {
cfcd5d6d
PN
384 /* Don't use the prefix for the first element, as the parent
385 * caller already prepended the index number. */
386 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
387
388 /* Format the multi bulk entry */
65add0a3 389 tmp = cliFormatReplyTTY(r->element[i],_prefix);
7fc4ce13
PN
390 out = sdscatlen(out,tmp,sdslen(tmp));
391 sdsfree(tmp);
392 }
cfcd5d6d 393 sdsfree(_prefix);
c0b3d423 394 }
7fc4ce13 395 break;
c937aa89 396 default:
7fc4ce13
PN
397 fprintf(stderr,"Unknown reply type: %d\n", r->type);
398 exit(1);
c937aa89 399 }
7fc4ce13 400 return out;
c937aa89 401}
402
65add0a3
PN
403static sds cliFormatReplyRaw(redisReply *r) {
404 sds out = sdsempty(), tmp;
405 size_t i;
406
407 switch (r->type) {
408 case REDIS_REPLY_NIL:
409 /* Nothing... */
ecc91094 410 break;
65add0a3 411 case REDIS_REPLY_ERROR:
ecc91094 412 out = sdscatlen(out,r->str,r->len);
413 out = sdscatlen(out,"\n",1);
414 break;
65add0a3
PN
415 case REDIS_REPLY_STATUS:
416 case REDIS_REPLY_STRING:
417 out = sdscatlen(out,r->str,r->len);
ecc91094 418 break;
65add0a3
PN
419 case REDIS_REPLY_INTEGER:
420 out = sdscatprintf(out,"%lld",r->integer);
ecc91094 421 break;
65add0a3
PN
422 case REDIS_REPLY_ARRAY:
423 for (i = 0; i < r->elements; i++) {
424 if (i > 0) out = sdscat(out,config.mb_delim);
425 tmp = cliFormatReplyRaw(r->element[i]);
426 out = sdscatlen(out,tmp,sdslen(tmp));
427 sdsfree(tmp);
428 }
ecc91094 429 break;
65add0a3
PN
430 default:
431 fprintf(stderr,"Unknown reply type: %d\n", r->type);
432 exit(1);
433 }
434 return out;
435}
436
437static int cliReadReply(int output_raw_strings) {
8ce39260 438 void *_reply;
7fc4ce13
PN
439 redisReply *reply;
440 sds out;
623131d4 441 int output = 1;
7fc4ce13 442
8ce39260 443 if (redisGetReply(context,&_reply) != REDIS_OK) {
7fc4ce13
PN
444 if (config.shutdown)
445 return REDIS_OK;
446 if (config.interactive) {
447 /* Filter cases where we should reconnect */
448 if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
449 return REDIS_ERR;
450 if (context->err == REDIS_ERR_EOF)
451 return REDIS_ERR;
452 }
a45f9a1a 453 cliPrintContextError();
454 exit(1);
7fc4ce13 455 return REDIS_ERR; /* avoid compiler warning */
62e920df 456 }
7fc4ce13 457
8ce39260 458 reply = (redisReply*)_reply;
623131d4 459
460 /* Check if we need to connect to a different node and reissue the request. */
461 if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR &&
462 (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK")))
463 {
464 char *p = reply->str, *s;
465 int slot;
466
467 output = 0;
468 /* Comments show the position of the pointer as:
469 *
470 * [S] for pointer 's'
471 * [P] for pointer 'p'
472 */
473 s = strchr(p,' '); /* MOVED[S]3999 127.0.0.1:6381 */
474 p = strchr(s+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */
475 *p = '\0';
476 slot = atoi(s+1);
477 s = strchr(p+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */
478 *s = '\0';
479 sdsfree(config.hostip);
480 config.hostip = sdsnew(p+1);
481 config.hostport = atoi(s+1);
482 if (config.interactive)
483 printf("-> Redirected to slot [%d] located at %s:%d\n",
484 slot, config.hostip, config.hostport);
485 config.cluster_reissue_command = 1;
486 }
487
488 if (output) {
489 if (output_raw_strings) {
65add0a3 490 out = cliFormatReplyRaw(reply);
65add0a3 491 } else {
623131d4 492 if (config.raw_output) {
493 out = cliFormatReplyRaw(reply);
494 out = sdscat(out,"\n");
495 } else {
496 out = cliFormatReplyTTY(reply,"");
497 }
65add0a3 498 }
623131d4 499 fwrite(out,sdslen(out),1,stdout);
500 sdsfree(out);
65add0a3 501 }
65add0a3 502 freeReplyObject(reply);
7fc4ce13 503 return REDIS_OK;
62e920df 504}
505
aab055ae 506static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 507 char *command = argv[0];
7fc4ce13 508 size_t *argvlen;
65add0a3 509 int j, output_raw;
ed9b544e 510
4eb3b3e9 511 if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
512 cliOutputHelp(--argc, ++argv);
513 return REDIS_OK;
514 }
515
a45f9a1a 516 if (context == NULL) return REDIS_ERR;
efcf948c 517
ecc91094 518 output_raw = 0;
519 if (!strcasecmp(command,"info") ||
520 (argc == 2 && !strcasecmp(command,"cluster") &&
521 (!strcasecmp(argv[1],"nodes") ||
3cd12b56 522 !strcasecmp(argv[1],"info"))) ||
523 (argc == 2 && !strcasecmp(command,"client") &&
524 !strcasecmp(argv[1],"list")))
525
ecc91094 526 {
527 output_raw = 1;
528 }
529
37dc9e5a
PN
530 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
531 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
532 if (!strcasecmp(command,"subscribe") ||
533 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
ed9b544e 534
7fc4ce13
PN
535 /* Setup argument length */
536 argvlen = malloc(argc*sizeof(size_t));
537 for (j = 0; j < argc; j++)
538 argvlen[j] = sdslen(argv[j]);
a2f4f871 539
aab055ae 540 while(repeat--) {
7fc4ce13 541 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
249c3a7d 542 while (config.monitor_mode) {
65add0a3 543 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
d9d8ccab 544 fflush(stdout);
621d5c19 545 }
546
249c3a7d 547 if (config.pubsub_mode) {
65add0a3
PN
548 if (!config.raw_output)
549 printf("Reading messages... (press Ctrl-C to quit)\n");
249c3a7d 550 while (1) {
65add0a3 551 if (cliReadReply(output_raw) != REDIS_OK) exit(1);
249c3a7d 552 }
553 }
554
33753a73
PN
555 if (cliReadReply(output_raw) != REDIS_OK) {
556 free(argvlen);
7fc4ce13 557 return REDIS_ERR;
96e34b3c
PN
558 } else {
559 /* Store database number when SELECT was successfully executed. */
3f4eef21 560 if (!strcasecmp(command,"select") && argc == 2) {
96e34b3c 561 config.dbnum = atoi(argv[1]);
3f4eef21
PN
562 cliRefreshPrompt();
563 }
33753a73 564 }
18f63d8d 565 if (config.interval) usleep(config.interval);
566 fflush(stdout); /* Make it grep friendly */
ed9b544e 567 }
33753a73
PN
568
569 free(argvlen);
7fc4ce13 570 return REDIS_OK;
ed9b544e 571}
572
3ce014c7 573/*------------------------------------------------------------------------------
574 * User interface
575 *--------------------------------------------------------------------------- */
576
ed9b544e 577static int parseOptions(int argc, char **argv) {
578 int i;
579
580 for (i = 1; i < argc; i++) {
581 int lastarg = i==argc-1;
6cf5882c 582
ed9b544e 583 if (!strcmp(argv[i],"-h") && !lastarg) {
efcf948c 584 sdsfree(config.hostip);
e2f31389 585 config.hostip = sdsnew(argv[++i]);
a9158272 586 } else if (!strcmp(argv[i],"-h") && lastarg) {
587 usage();
f18e059e
PN
588 } else if (!strcmp(argv[i],"--help")) {
589 usage();
bc63407b 590 } else if (!strcmp(argv[i],"-x")) {
591 config.stdinarg = 1;
ed9b544e 592 } else if (!strcmp(argv[i],"-p") && !lastarg) {
e2f31389 593 config.hostport = atoi(argv[++i]);
7e91f971 594 } else if (!strcmp(argv[i],"-s") && !lastarg) {
e2f31389 595 config.hostsocket = argv[++i];
5762b7f0 596 } else if (!strcmp(argv[i],"-r") && !lastarg) {
e2f31389 597 config.repeat = strtoll(argv[++i],NULL,10);
18f63d8d 598 } else if (!strcmp(argv[i],"-i") && !lastarg) {
e2f31389 599 double seconds = atof(argv[++i]);
18f63d8d 600 config.interval = seconds*1000000;
62e920df 601 } else if (!strcmp(argv[i],"-n") && !lastarg) {
e2f31389 602 config.dbnum = atoi(argv[++i]);
fdfdae0f 603 } else if (!strcmp(argv[i],"-a") && !lastarg) {
e2f31389 604 config.auth = argv[++i];
65add0a3
PN
605 } else if (!strcmp(argv[i],"--raw")) {
606 config.raw_output = 1;
43071993 607 } else if (!strcmp(argv[i],"--latency")) {
608 config.latency_mode = 1;
e2f31389 609 } else if (!strcmp(argv[i],"--eval") && !lastarg) {
610 config.eval = argv[++i];
623131d4 611 } else if (!strcmp(argv[i],"-c")) {
612 config.cluster_mode = 1;
28c07c7b
PN
613 } else if (!strcmp(argv[i],"-d") && !lastarg) {
614 sdsfree(config.mb_delim);
e2f31389 615 config.mb_delim = sdsnew(argv[++i]);
f18e059e
PN
616 } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) {
617 sds version = cliVersion();
618 printf("redis-cli %s\n", version);
619 sdsfree(version);
185cabda 620 exit(0);
ed9b544e 621 } else {
622 break;
623 }
624 }
625 return i;
626}
627
628static sds readArgFromStdin(void) {
629 char buf[1024];
630 sds arg = sdsempty();
631
632 while(1) {
633 int nread = read(fileno(stdin),buf,1024);
634
635 if (nread == 0) break;
636 else if (nread == -1) {
637 perror("Reading from standard input");
638 exit(1);
639 }
640 arg = sdscatlen(arg,buf,nread);
641 }
642 return arg;
643}
644
a9158272 645static void usage() {
f18e059e
PN
646 sds version = cliVersion();
647 fprintf(stderr,
648"redis-cli %s\n"
649"\n"
650"Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
651" -h <hostname> Server hostname (default: 127.0.0.1)\n"
652" -p <port> Server port (default: 6379)\n"
653" -s <socket> Server socket (overrides hostname and port)\n"
654" -a <password> Password to use when connecting to the server\n"
655" -r <repeat> Execute specified command N times\n"
18f63d8d 656" -i <interval> When -r is used, waits <interval> seconds per command.\n"
657" It is possible to specify sub-second times like -i 0.1.\n"
f18e059e
PN
658" -n <db> Database number\n"
659" -x Read last argument from STDIN\n"
28c07c7b 660" -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n"
623131d4 661" -c Enable cluster mode (follow -ASK and -MOVED redirections)\n"
65add0a3 662" --raw Use raw formatting for replies (default when STDOUT is not a tty)\n"
43071993 663" --latency Enter a special mode continuously sampling latency.\n"
e2f31389 664" --eval <file> Send an EVAL command using the Lua script at <file>.\n"
f18e059e
PN
665" --help Output this help and exit\n"
666" --version Output version and exit\n"
667"\n"
668"Examples:\n"
669" cat /etc/passwd | redis-cli -x set mypasswd\n"
670" redis-cli get mypasswd\n"
671" redis-cli -r 100 lpush mylist x\n"
18f63d8d 672" redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
e2f31389 673" redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
674" (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
f18e059e
PN
675"\n"
676"When no command is given, redis-cli starts in interactive mode.\n"
677"Type \"help\" in interactive mode for information on available commands.\n"
678"\n",
679 version);
680 sdsfree(version);
a9158272 681 exit(1);
682}
683
6cf5882c
MMDJ
684/* Turn the plain C strings into Sds strings */
685static char **convertToSds(int count, char** args) {
686 int j;
37dc9e5a 687 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
688
689 for(j = 0; j < count; j++)
690 sds[j] = sdsnew(args[j]);
691
692 return sds;
693}
694
a88a2af6 695#define LINE_BUFLEN 4096
6cf5882c 696static void repl() {
ca36b4ab
PN
697 sds historyfile = NULL;
698 int history = 0;
cbce5171 699 char *line;
ca36b4ab 700 int argc;
cbce5171 701 sds *argv;
6cf5882c 702
5d15b520 703 config.interactive = 1;
41945ba6 704 linenoiseSetCompletionCallback(completionCallback);
ce260f73 705
ca36b4ab
PN
706 /* Only use history when stdin is a tty. */
707 if (isatty(fileno(stdin))) {
708 history = 1;
709
710 if (getenv("HOME") != NULL) {
711 historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
712 linenoiseHistoryLoad(historyfile);
713 }
714 }
715
3f4eef21
PN
716 cliRefreshPrompt();
717 while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
cf87ebf2 718 if (line[0] != '\0') {
cbce5171 719 argv = sdssplitargs(line,&argc);
ca36b4ab
PN
720 if (history) linenoiseHistoryAdd(line);
721 if (historyfile) linenoiseHistorySave(historyfile);
722
0439d792
PN
723 if (argv == NULL) {
724 printf("Invalid argument(s)\n");
db6a2e7f 725 free(line);
0439d792
PN
726 continue;
727 } else if (argc > 0) {
a88a2af6 728 if (strcasecmp(argv[0],"quit") == 0 ||
729 strcasecmp(argv[0],"exit") == 0)
c0b3d423 730 {
731 exit(0);
efcf948c 732 } else if (argc == 3 && !strcasecmp(argv[0],"connect")) {
733 sdsfree(config.hostip);
734 config.hostip = sdsnew(argv[1]);
735 config.hostport = atoi(argv[2]);
736 cliConnect(1);
bbac56c2 737 } else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
738 linenoiseClearScreen();
c0b3d423 739 } else {
3ce014c7 740 long long start_time = mstime(), elapsed;
4d19e344 741 int repeat, skipargs = 0;
c0b3d423 742
4d19e344 743 repeat = atoi(argv[0]);
aee7f997 744 if (argc > 1 && repeat) {
4d19e344 745 skipargs = 1;
746 } else {
747 repeat = 1;
748 }
749
623131d4 750 while (1) {
751 config.cluster_reissue_command = 0;
442c748d 752 if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
753 != REDIS_OK)
623131d4 754 {
755 cliConnect(1);
756
757 /* If we still cannot send the command print error.
758 * We'll try to reconnect the next time. */
759 if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
760 != REDIS_OK)
761 cliPrintContextError();
762 }
763 /* Issue the command again if we got redirected in cluster mode */
764 if (config.cluster_mode && config.cluster_reissue_command) {
765 cliConnect(1);
766 } else {
767 break;
768 }
c0b3d423 769 }
3ce014c7 770 elapsed = mstime()-start_time;
339b9dc2
PN
771 if (elapsed >= 500) {
772 printf("(%.2fs)\n",(double)elapsed/1000);
773 }
c0b3d423 774 }
a88a2af6 775 }
776 /* Free the argument vector */
ca36b4ab 777 while(argc--) sdsfree(argv[argc]);
8ff6a48b 778 zfree(argv);
6cf5882c 779 }
a88a2af6 780 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 781 free(line);
6cf5882c 782 }
6cf5882c
MMDJ
783 exit(0);
784}
785
b4b62c34
PN
786static int noninteractive(int argc, char **argv) {
787 int retval = 0;
bc63407b 788 if (config.stdinarg) {
b4b62c34
PN
789 argv = zrealloc(argv, (argc+1)*sizeof(char*));
790 argv[argc] = readArgFromStdin();
791 retval = cliSendCommand(argc+1, argv, config.repeat);
792 } else {
793 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
794 retval = cliSendCommand(argc, argv, config.repeat);
795 }
796 return retval;
797}
798
e2f31389 799static int evalMode(int argc, char **argv) {
800 sds script = sdsempty();
801 FILE *fp;
802 char buf[1024];
803 size_t nread;
804 char **argv2;
805 int j, got_comma = 0, keys = 0;
806
807 /* Load the script from the file, as an sds string. */
808 fp = fopen(config.eval,"r");
809 if (!fp) {
810 fprintf(stderr,
811 "Can't open file '%s': %s\n", config.eval, strerror(errno));
812 exit(1);
813 }
814 while((nread = fread(buf,1,sizeof(buf),fp)) != 0) {
815 script = sdscatlen(script,buf,nread);
816 }
817 fclose(fp);
818
819 /* Create our argument vector */
820 argv2 = zmalloc(sizeof(sds)*(argc+3));
821 argv2[0] = sdsnew("EVAL");
822 argv2[1] = script;
823 for (j = 0; j < argc; j++) {
824 if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) {
825 got_comma = 1;
826 continue;
827 }
828 argv2[j+3-got_comma] = sdsnew(argv[j]);
829 if (!got_comma) keys++;
830 }
831 argv2[2] = sdscatprintf(sdsempty(),"%d",keys);
832
833 /* Call it */
834 return cliSendCommand(argc+3-got_comma, argv2, config.repeat);
835}
836
43071993 837static void latencyMode(void) {
838 redisReply *reply;
839 long long start, latency, min, max, tot, count = 0;
840 double avg;
841
842 if (!context) exit(1);
843 while(1) {
844 start = mstime();
845 reply = redisCommand(context,"PING");
846 if (reply == NULL) {
847 fprintf(stderr,"\nI/O error\n");
848 exit(1);
849 }
850 latency = mstime()-start;
851 freeReplyObject(reply);
852 count++;
853 if (count == 1) {
854 min = max = tot = latency;
855 avg = (double) latency;
856 } else {
857 if (latency < min) min = latency;
858 if (latency > max) max = latency;
96674b6d 859 tot += latency;
43071993 860 avg = (double) tot/count;
861 }
862 printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
863 min, max, avg, count);
864 fflush(stdout);
865 usleep(10000);
866 }
867}
868
ed9b544e 869int main(int argc, char **argv) {
6cf5882c 870 int firstarg;
ed9b544e 871
efcf948c 872 config.hostip = sdsnew("127.0.0.1");
ed9b544e 873 config.hostport = 6379;
7e91f971 874 config.hostsocket = NULL;
5762b7f0 875 config.repeat = 1;
18f63d8d 876 config.interval = 0;
62e920df 877 config.dbnum = 0;
5d15b520 878 config.interactive = 0;
36e5db6d 879 config.shutdown = 0;
249c3a7d 880 config.monitor_mode = 0;
881 config.pubsub_mode = 0;
43071993 882 config.latency_mode = 0;
623131d4 883 config.cluster_mode = 0;
bc63407b 884 config.stdinarg = 0;
288799e0 885 config.auth = NULL;
e2f31389 886 config.eval = NULL;
65add0a3
PN
887 config.raw_output = !isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL);
888 config.mb_delim = sdsnew("\n");
41945ba6 889 cliInitHelp();
99628c1a 890
ed9b544e 891 firstarg = parseOptions(argc,argv);
892 argc -= firstarg;
893 argv += firstarg;
ed9b544e 894
43071993 895 /* Start in latency mode if appropriate */
896 if (config.latency_mode) {
897 cliConnect(0);
898 latencyMode();
899 }
900
abb731e5 901 /* Start interactive mode when no command is provided */
e2f31389 902 if (argc == 0 && !config.eval) {
a45f9a1a 903 /* Note that in repl mode we don't abort on connection error.
904 * A new attempt will be performed for every command send. */
905 cliConnect(0);
906 repl();
907 }
908
b4b62c34 909 /* Otherwise, we have some arguments to execute */
a45f9a1a 910 if (cliConnect(0) != REDIS_OK) exit(1);
e2f31389 911 if (config.eval) {
912 return evalMode(argc,argv);
913 } else {
914 return noninteractive(argc,convertToSds(argc,argv));
915 }
ed9b544e 916}