]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
865f093135550fdd8b7c36fe4214e87e90af95cd
[redis.git] / src / redis-cli.c
1 /* Redis CLI (command line interface)
2 *
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * * Neither the name of Redis nor the names of its contributors may be used
15 * to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include "fmacros.h"
32 #include "version.h"
33
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <sys/stat.h>
41 #include <sys/time.h>
42
43 #include "hiredis.h"
44 #include "sds.h"
45 #include "zmalloc.h"
46 #include "linenoise.h"
47 #include "help.h"
48
49 #define REDIS_NOTUSED(V) ((void) V)
50
51 static redisContext *context;
52 static struct config {
53 char *hostip;
54 int hostport;
55 char *hostsocket;
56 long repeat;
57 int dbnum;
58 int interactive;
59 int shutdown;
60 int monitor_mode;
61 int pubsub_mode;
62 int raw_output; /* output mode per command */
63 int tty; /* flag for default output format */
64 int stdinarg; /* get last arg from stdin. (-x option) */
65 char mb_sep;
66 char *auth;
67 char *historyfile;
68 } config;
69
70 static void usage();
71 char *redisGitSHA1(void);
72
73 /*------------------------------------------------------------------------------
74 * Utility functions
75 *--------------------------------------------------------------------------- */
76
77 static long long mstime(void) {
78 struct timeval tv;
79 long long mst;
80
81 gettimeofday(&tv, NULL);
82 mst = ((long)tv.tv_sec)*1000;
83 mst += tv.tv_usec/1000;
84 return mst;
85 }
86
87 /*------------------------------------------------------------------------------
88 * Help functions
89 *--------------------------------------------------------------------------- */
90
91 /* Output command help to stdout. */
92 static void outputCommandHelp(struct commandHelp *help) {
93 printf("\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\n", help->name, help->params);
94 printf(" \x1b[33msummary:\x1b[0m %s\n", help->summary);
95 printf(" \x1b[33msince:\x1b[0m %s\n", help->since);
96 printf(" \x1b[33mgroup:\x1b[0m %s\n", commandGroups[help->group]);
97 }
98
99 /* Return command group type by name string. */
100 static int commandGroupIndex(const char *name) {
101 int i, len = sizeof(commandGroups)/sizeof(char*);
102 for (i = 0; i < len; i++)
103 if (strcasecmp(name, commandGroups[i]) == 0)
104 return i;
105 return -1;
106 }
107
108 /* Output group names. */
109 static void outputGroupHelp() {
110 int i, len = sizeof(commandGroups)/sizeof(char*);
111 for (i = 0; i < len; i++)
112 printf(" \x1b[90m-\x1b[0m %s\n", commandGroups[i]);
113 }
114
115 /* Output all command help, filtering by group or command name. */
116 static void outputHelp(int argc, char **argv) {
117 int i, len = sizeof(commandHelp) / sizeof(struct commandHelp);
118 int group;
119 struct commandHelp *help;
120
121 if (argc && strcasecmp("groups", argv[0]) == 0) {
122 outputGroupHelp();
123 return;
124 }
125
126 group = argc ? commandGroupIndex(argv[0]) : -1;
127 for (i = 0; i < len; i++) {
128 help = &commandHelp[i];
129 if (group == -1) {
130 if (argc) {
131 if (strcasecmp(help->name, argv[0]) == 0) {
132 outputCommandHelp(help);
133 }
134 } else {
135 outputCommandHelp(help);
136 }
137 } else {
138 if (group == help->group) {
139 outputCommandHelp(help);
140 }
141 }
142 }
143 puts("");
144 }
145
146 /*------------------------------------------------------------------------------
147 * Networking / parsing
148 *--------------------------------------------------------------------------- */
149
150 /* Send AUTH command to the server */
151 static int cliAuth() {
152 redisReply *reply;
153 if (config.auth == NULL) return REDIS_OK;
154
155 reply = redisCommand(context,"AUTH %s",config.auth);
156 if (reply != NULL) {
157 freeReplyObject(reply);
158 return REDIS_OK;
159 }
160 return REDIS_ERR;
161 }
162
163 /* Send SELECT dbnum to the server */
164 static int cliSelect() {
165 redisReply *reply;
166 char dbnum[16];
167 if (config.dbnum == 0) return REDIS_OK;
168
169 snprintf(dbnum,sizeof(dbnum),"%d",config.dbnum);
170 reply = redisCommand(context,"SELECT %s",dbnum);
171 if (reply != NULL) {
172 freeReplyObject(reply);
173 return REDIS_OK;
174 }
175 return REDIS_ERR;
176 }
177
178 /* Connect to the client. If force is not zero the connection is performed
179 * even if there is already a connected socket. */
180 static int cliConnect(int force) {
181 if (context == NULL || force) {
182 if (context != NULL)
183 redisFree(context);
184
185 if (config.hostsocket == NULL) {
186 context = redisConnect(config.hostip,config.hostport);
187 } else {
188 context = redisConnectUnix(config.hostsocket);
189 }
190
191 if (context->err) {
192 fprintf(stderr,"Could not connect to Redis at ");
193 if (config.hostsocket == NULL)
194 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
195 else
196 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
197 redisFree(context);
198 context = NULL;
199 return REDIS_ERR;
200 }
201
202 /* Do AUTH and select the right DB. */
203 if (cliAuth() != REDIS_OK)
204 return REDIS_ERR;
205 if (cliSelect() != REDIS_OK)
206 return REDIS_ERR;
207 }
208 return REDIS_OK;
209 }
210
211 static void cliPrintContextErrorAndExit() {
212 if (context == NULL) return;
213 fprintf(stderr,"Error: %s\n",context->errstr);
214 exit(1);
215 }
216
217 static sds cliFormatReply(redisReply *r, char *prefix) {
218 sds out = sdsempty();
219 switch (r->type) {
220 case REDIS_REPLY_ERROR:
221 if (config.tty) out = sdscat(out,"(error) ");
222 out = sdscatprintf(out,"%s\n", r->str);
223 break;
224 case REDIS_REPLY_STATUS:
225 out = sdscat(out,r->str);
226 out = sdscat(out,"\n");
227 break;
228 case REDIS_REPLY_INTEGER:
229 if (config.tty) out = sdscat(out,"(integer) ");
230 out = sdscatprintf(out,"%lld\n",r->integer);
231 break;
232 case REDIS_REPLY_STRING:
233 if (config.raw_output || !config.tty) {
234 out = sdscatlen(out,r->str,r->len);
235 } else {
236 /* If you are producing output for the standard output we want
237 * a more interesting output with quoted characters and so forth */
238 out = sdscatrepr(out,r->str,r->len);
239 out = sdscat(out,"\n");
240 }
241 break;
242 case REDIS_REPLY_NIL:
243 out = sdscat(out,"(nil)\n");
244 break;
245 case REDIS_REPLY_ARRAY:
246 if (r->elements == 0) {
247 out = sdscat(out,"(empty list or set)\n");
248 } else {
249 unsigned int i, idxlen = 0;
250 char _prefixlen[16];
251 char _prefixfmt[16];
252 sds _prefix;
253 sds tmp;
254
255 /* Calculate chars needed to represent the largest index */
256 i = r->elements;
257 do {
258 idxlen++;
259 i /= 10;
260 } while(i);
261
262 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
263 memset(_prefixlen,' ',idxlen+2);
264 _prefixlen[idxlen+2] = '\0';
265 _prefix = sdscat(sdsnew(prefix),_prefixlen);
266
267 /* Setup prefix format for every entry */
268 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
269
270 for (i = 0; i < r->elements; i++) {
271 /* Don't use the prefix for the first element, as the parent
272 * caller already prepended the index number. */
273 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
274
275 /* Format the multi bulk entry */
276 tmp = cliFormatReply(r->element[i],_prefix);
277 out = sdscatlen(out,tmp,sdslen(tmp));
278 sdsfree(tmp);
279 }
280 sdsfree(_prefix);
281 }
282 break;
283 default:
284 fprintf(stderr,"Unknown reply type: %d\n", r->type);
285 exit(1);
286 }
287 return out;
288 }
289
290 static int cliReadReply() {
291 redisReply *reply;
292 sds out;
293
294 if (redisGetReply(context,(void**)&reply) != REDIS_OK) {
295 if (config.shutdown)
296 return REDIS_OK;
297 if (config.interactive) {
298 /* Filter cases where we should reconnect */
299 if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
300 return REDIS_ERR;
301 if (context->err == REDIS_ERR_EOF)
302 return REDIS_ERR;
303 }
304 cliPrintContextErrorAndExit();
305 return REDIS_ERR; /* avoid compiler warning */
306 }
307
308 out = cliFormatReply(reply,"");
309 freeReplyObject(reply);
310 fwrite(out,sdslen(out),1,stdout);
311 sdsfree(out);
312 return REDIS_OK;
313 }
314
315 static int cliSendCommand(int argc, char **argv, int repeat) {
316 char *command = argv[0];
317 size_t *argvlen;
318 int j;
319
320 config.raw_output = !strcasecmp(command,"info");
321 if (!strcasecmp(command,"help")) {
322 outputHelp(--argc, ++argv);
323 return REDIS_OK;
324 }
325 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
326 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
327 if (!strcasecmp(command,"subscribe") ||
328 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
329
330 /* Setup argument length */
331 argvlen = malloc(argc*sizeof(size_t));
332 for (j = 0; j < argc; j++)
333 argvlen[j] = sdslen(argv[j]);
334
335 while(repeat--) {
336 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
337 while (config.monitor_mode) {
338 if (cliReadReply() != REDIS_OK) exit(1);
339 fflush(stdout);
340 }
341
342 if (config.pubsub_mode) {
343 printf("Reading messages... (press Ctrl-C to quit)\n");
344 while (1) {
345 if (cliReadReply() != REDIS_OK) exit(1);
346 }
347 }
348
349 if (cliReadReply() != REDIS_OK)
350 return REDIS_ERR;
351 }
352 return REDIS_OK;
353 }
354
355 /*------------------------------------------------------------------------------
356 * User interface
357 *--------------------------------------------------------------------------- */
358
359 static int parseOptions(int argc, char **argv) {
360 int i;
361
362 for (i = 1; i < argc; i++) {
363 int lastarg = i==argc-1;
364
365 if (!strcmp(argv[i],"-h") && !lastarg) {
366 config.hostip = argv[i+1];
367 i++;
368 } else if (!strcmp(argv[i],"-h") && lastarg) {
369 usage();
370 } else if (!strcmp(argv[i],"-x")) {
371 config.stdinarg = 1;
372 } else if (!strcmp(argv[i],"-p") && !lastarg) {
373 config.hostport = atoi(argv[i+1]);
374 i++;
375 } else if (!strcmp(argv[i],"-s") && !lastarg) {
376 config.hostsocket = argv[i+1];
377 i++;
378 } else if (!strcmp(argv[i],"-r") && !lastarg) {
379 config.repeat = strtoll(argv[i+1],NULL,10);
380 i++;
381 } else if (!strcmp(argv[i],"-n") && !lastarg) {
382 config.dbnum = atoi(argv[i+1]);
383 i++;
384 } else if (!strcmp(argv[i],"-a") && !lastarg) {
385 config.auth = argv[i+1];
386 i++;
387 } else if (!strcmp(argv[i],"-i")) {
388 fprintf(stderr,
389 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
390 "by default when redis-cli is executed without a command to execute.\n"
391 );
392 } else if (!strcmp(argv[i],"-c")) {
393 fprintf(stderr,
394 "Reading last argument from standard input using -c is deprecated.\n"
395 "When standard input is connected to a pipe or regular file, it is\n"
396 "automatically used as last argument.\n"
397 );
398 } else if (!strcmp(argv[i],"-v")) {
399 printf("redis-cli shipped with Redis version %s (%s)\n", REDIS_VERSION, redisGitSHA1());
400 exit(0);
401 } else {
402 break;
403 }
404 }
405 return i;
406 }
407
408 static sds readArgFromStdin(void) {
409 char buf[1024];
410 sds arg = sdsempty();
411
412 while(1) {
413 int nread = read(fileno(stdin),buf,1024);
414
415 if (nread == 0) break;
416 else if (nread == -1) {
417 perror("Reading from standard input");
418 exit(1);
419 }
420 arg = sdscatlen(arg,buf,nread);
421 }
422 return arg;
423 }
424
425 static void usage() {
426 fprintf(stderr, "usage: redis-cli [-iv] [-h host] [-p port] [-s /path/to/socket] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
427 fprintf(stderr, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
428 fprintf(stderr, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
429 fprintf(stderr, "example: redis-cli get my_passwd\n");
430 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
431 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
432 exit(1);
433 }
434
435 /* Turn the plain C strings into Sds strings */
436 static char **convertToSds(int count, char** args) {
437 int j;
438 char **sds = zmalloc(sizeof(char*)*count);
439
440 for(j = 0; j < count; j++)
441 sds[j] = sdsnew(args[j]);
442
443 return sds;
444 }
445
446 #define LINE_BUFLEN 4096
447 static void repl() {
448 int argc, j;
449 char *line;
450 sds *argv;
451
452 config.interactive = 1;
453 while((line = linenoise("redis> ")) != NULL) {
454 if (line[0] != '\0') {
455 argv = sdssplitargs(line,&argc);
456 linenoiseHistoryAdd(line);
457 if (config.historyfile) linenoiseHistorySave(config.historyfile);
458 if (argv == NULL) {
459 printf("Invalid argument(s)\n");
460 continue;
461 } else if (argc > 0) {
462 if (strcasecmp(argv[0],"quit") == 0 ||
463 strcasecmp(argv[0],"exit") == 0)
464 {
465 exit(0);
466 } else {
467 long long start_time = mstime(), elapsed;
468
469 if (cliSendCommand(argc,argv,1) != REDIS_OK) {
470 printf("Reconnecting... ");
471 fflush(stdout);
472 if (cliConnect(1) != REDIS_OK) exit(1);
473 printf("OK\n");
474
475 /* If we still cannot send the command,
476 * print error and abort. */
477 if (cliSendCommand(argc,argv,1) != REDIS_OK)
478 cliPrintContextErrorAndExit();
479 }
480 elapsed = mstime()-start_time;
481 if (elapsed >= 500) {
482 printf("(%.2fs)\n",(double)elapsed/1000);
483 }
484 }
485 }
486 /* Free the argument vector */
487 for (j = 0; j < argc; j++)
488 sdsfree(argv[j]);
489 zfree(argv);
490 }
491 /* linenoise() returns malloc-ed lines like readline() */
492 free(line);
493 }
494 exit(0);
495 }
496
497 static int noninteractive(int argc, char **argv) {
498 int retval = 0;
499 if (config.stdinarg) {
500 argv = zrealloc(argv, (argc+1)*sizeof(char*));
501 argv[argc] = readArgFromStdin();
502 retval = cliSendCommand(argc+1, argv, config.repeat);
503 } else {
504 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
505 retval = cliSendCommand(argc, argv, config.repeat);
506 }
507 return retval;
508 }
509
510 int main(int argc, char **argv) {
511 int firstarg;
512
513 config.hostip = "127.0.0.1";
514 config.hostport = 6379;
515 config.hostsocket = NULL;
516 config.repeat = 1;
517 config.dbnum = 0;
518 config.interactive = 0;
519 config.shutdown = 0;
520 config.monitor_mode = 0;
521 config.pubsub_mode = 0;
522 config.raw_output = 0;
523 config.stdinarg = 0;
524 config.auth = NULL;
525 config.historyfile = NULL;
526 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
527 config.mb_sep = '\n';
528
529 if (getenv("HOME") != NULL) {
530 config.historyfile = malloc(256);
531 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
532 linenoiseHistoryLoad(config.historyfile);
533 }
534
535 firstarg = parseOptions(argc,argv);
536 argc -= firstarg;
537 argv += firstarg;
538
539 /* Try to connect */
540 if (cliConnect(0) != REDIS_OK) exit(1);
541
542 /* Start interactive mode when no command is provided */
543 if (argc == 0) repl();
544 /* Otherwise, we have some arguments to execute */
545 return noninteractive(argc,convertToSds(argc,argv));
546 }