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