]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
RSS information in INFO output
[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 "anet.h"
44 #include "sds.h"
45 #include "adlist.h"
46 #include "zmalloc.h"
47 #include "linenoise.h"
48
49 #define REDIS_NOTUSED(V) ((void) V)
50
51 static struct config {
52 char *hostip;
53 int hostport;
54 long repeat;
55 int dbnum;
56 int interactive;
57 int shutdown;
58 int monitor_mode;
59 int pubsub_mode;
60 int raw_output; /* output mode per command */
61 int tty; /* flag for default output format */
62 int stdinarg; /* get last arg from stdin. (-x option) */
63 char mb_sep;
64 char *auth;
65 char *historyfile;
66 } config;
67
68 static int cliReadReply(int fd);
69 static void usage();
70
71 /*------------------------------------------------------------------------------
72 * Utility functions
73 *--------------------------------------------------------------------------- */
74
75 static long long mstime(void) {
76 struct timeval tv;
77 long long mst;
78
79 gettimeofday(&tv, NULL);
80 mst = ((long)tv.tv_sec)*1000;
81 mst += tv.tv_usec/1000;
82 return mst;
83 }
84
85 static void printStringRepr(char *s, int len) {
86 printf("\"");
87 while(len--) {
88 switch(*s) {
89 case '\\':
90 case '"':
91 printf("\\%c",*s);
92 break;
93 case '\n': printf("\\n"); break;
94 case '\r': printf("\\r"); break;
95 case '\t': printf("\\t"); break;
96 case '\a': printf("\\a"); break;
97 case '\b': printf("\\b"); break;
98 default:
99 if (isprint(*s))
100 printf("%c",*s);
101 else
102 printf("\\x%02x",(unsigned char)*s);
103 break;
104 }
105 s++;
106 }
107 printf("\"");
108 }
109
110 /*------------------------------------------------------------------------------
111 * Networking / parsing
112 *--------------------------------------------------------------------------- */
113
114 /* Connect to the client. If force is not zero the connection is performed
115 * even if there is already a connected socket. */
116 static int cliConnect(int force) {
117 char err[ANET_ERR_LEN];
118 static int fd = ANET_ERR;
119
120 if (fd == ANET_ERR || force) {
121 if (force) close(fd);
122 fd = anetTcpConnect(err,config.hostip,config.hostport);
123 if (fd == ANET_ERR) {
124 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
125 return -1;
126 }
127 anetTcpNoDelay(NULL,fd);
128 }
129 return fd;
130 }
131
132 static sds cliReadLine(int fd) {
133 sds line = sdsempty();
134
135 while(1) {
136 char c;
137 ssize_t ret;
138
139 ret = read(fd,&c,1);
140 if (ret <= 0) {
141 sdsfree(line);
142 return NULL;
143 } else if ((ret == 0) || (c == '\n')) {
144 break;
145 } else {
146 line = sdscatlen(line,&c,1);
147 }
148 }
149 return sdstrim(line,"\r\n");
150 }
151
152 static int cliReadSingleLineReply(int fd, int quiet) {
153 sds reply = cliReadLine(fd);
154
155 if (reply == NULL) return 1;
156 if (!quiet)
157 printf("%s", reply);
158 sdsfree(reply);
159 return 0;
160 }
161
162 static int cliReadBulkReply(int fd) {
163 sds replylen = cliReadLine(fd);
164 char *reply, crlf[2];
165 int bulklen;
166
167 if (replylen == NULL) return 1;
168 bulklen = atoi(replylen);
169 if (bulklen == -1) {
170 sdsfree(replylen);
171 printf("(nil)\n");
172 return 0;
173 }
174 reply = zmalloc(bulklen);
175 anetRead(fd,reply,bulklen);
176 anetRead(fd,crlf,2);
177 if (config.raw_output || !config.tty) {
178 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
179 zfree(reply);
180 return 1;
181 }
182 } else {
183 /* If you are producing output for the standard output we want
184 * a more interesting output with quoted characters and so forth */
185 printStringRepr(reply,bulklen);
186 }
187 zfree(reply);
188 return 0;
189 }
190
191 static int cliReadMultiBulkReply(int fd) {
192 sds replylen = cliReadLine(fd);
193 int elements, c = 1;
194 int retval = 0;
195
196 if (replylen == NULL) return 1;
197 elements = atoi(replylen);
198 if (elements == -1) {
199 sdsfree(replylen);
200 printf("(nil)\n");
201 return 0;
202 }
203 if (elements == 0) {
204 printf("(empty list or set)\n");
205 }
206 while(elements--) {
207 if (config.tty) printf("%d. ", c);
208 if (cliReadReply(fd)) retval = 1;
209 if (elements) printf("%c",config.mb_sep);
210 c++;
211 }
212 return retval;
213 }
214
215 static int cliReadReply(int fd) {
216 char type;
217 int nread;
218
219 if ((nread = anetRead(fd,&type,1)) <= 0) {
220 if (config.shutdown) return 0;
221 if (config.interactive &&
222 (nread == 0 || (nread == -1 && errno == ECONNRESET)))
223 {
224 return ECONNRESET;
225 } else {
226 printf("I/O error while reading from socket: %s",strerror(errno));
227 exit(1);
228 }
229 }
230 switch(type) {
231 case '-':
232 if (config.tty) printf("(error) ");
233 cliReadSingleLineReply(fd,0);
234 return 1;
235 case '+':
236 return cliReadSingleLineReply(fd,0);
237 case ':':
238 if (config.tty) printf("(integer) ");
239 return cliReadSingleLineReply(fd,0);
240 case '$':
241 return cliReadBulkReply(fd);
242 case '*':
243 return cliReadMultiBulkReply(fd);
244 default:
245 printf("protocol error, got '%c' as reply type byte", type);
246 return 1;
247 }
248 }
249
250 static int selectDb(int fd) {
251 int retval;
252 sds cmd;
253 char type;
254
255 if (config.dbnum == 0)
256 return 0;
257
258 cmd = sdsempty();
259 cmd = sdscatprintf(cmd,"SELECT %d\r\n",config.dbnum);
260 anetWrite(fd,cmd,sdslen(cmd));
261 anetRead(fd,&type,1);
262 if (type <= 0 || type != '+') return 1;
263 retval = cliReadSingleLineReply(fd,1);
264 if (retval) {
265 return retval;
266 }
267 return 0;
268 }
269
270 static void showInteractiveHelp(void) {
271 printf(
272 "\n"
273 "Welcome to redis-cli " REDIS_VERSION "!\n"
274 "Just type any valid Redis command to see a pretty printed output.\n"
275 "\n"
276 "It is possible to quote strings, like in:\n"
277 " set \"my key\" \"some string \\xff\\n\"\n"
278 "\n"
279 "You can find a list of valid Redis commands at\n"
280 " http://code.google.com/p/redis/wiki/CommandReference\n"
281 "\n"
282 "Note: redis-cli supports line editing, use up/down arrows for history."
283 "\n\n");
284 }
285
286 static int cliSendCommand(int argc, char **argv, int repeat) {
287 char *command = argv[0];
288 int fd, j, retval = 0;
289 sds cmd;
290
291 config.raw_output = !strcasecmp(command,"info");
292 if (!strcasecmp(command,"help")) {
293 showInteractiveHelp();
294 return 0;
295 }
296 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
297 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
298 if (!strcasecmp(command,"subscribe") ||
299 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
300 if ((fd = cliConnect(0)) == -1) return 1;
301
302 /* Select db number */
303 retval = selectDb(fd);
304 if (retval) {
305 fprintf(stderr,"Error setting DB num\n");
306 return 1;
307 }
308
309 /* Build the command to send */
310 cmd = sdscatprintf(sdsempty(),"*%d\r\n",argc);
311 for (j = 0; j < argc; j++) {
312 cmd = sdscatprintf(cmd,"$%lu\r\n",
313 (unsigned long)sdslen(argv[j]));
314 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
315 cmd = sdscatlen(cmd,"\r\n",2);
316 }
317
318 while(repeat--) {
319 anetWrite(fd,cmd,sdslen(cmd));
320 while (config.monitor_mode) {
321 if (cliReadSingleLineReply(fd,0)) exit(1);
322 printf("\n");
323 }
324
325 if (config.pubsub_mode) {
326 printf("Reading messages... (press Ctrl-c to quit)\n");
327 while (1) {
328 cliReadReply(fd);
329 printf("\n\n");
330 }
331 }
332
333 retval = cliReadReply(fd);
334 if (!config.raw_output && config.tty) printf("\n");
335 if (retval) return retval;
336 }
337 return 0;
338 }
339
340 /*------------------------------------------------------------------------------
341 * User interface
342 *--------------------------------------------------------------------------- */
343
344 static int parseOptions(int argc, char **argv) {
345 int i;
346
347 for (i = 1; i < argc; i++) {
348 int lastarg = i==argc-1;
349
350 if (!strcmp(argv[i],"-h") && !lastarg) {
351 char *ip = zmalloc(32);
352 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
353 printf("Can't resolve %s\n", argv[i]);
354 exit(1);
355 }
356 config.hostip = ip;
357 i++;
358 } else if (!strcmp(argv[i],"-h") && lastarg) {
359 usage();
360 } else if (!strcmp(argv[i],"-x")) {
361 config.stdinarg = 1;
362 } else if (!strcmp(argv[i],"-p") && !lastarg) {
363 config.hostport = atoi(argv[i+1]);
364 i++;
365 } else if (!strcmp(argv[i],"-r") && !lastarg) {
366 config.repeat = strtoll(argv[i+1],NULL,10);
367 i++;
368 } else if (!strcmp(argv[i],"-n") && !lastarg) {
369 config.dbnum = atoi(argv[i+1]);
370 i++;
371 } else if (!strcmp(argv[i],"-a") && !lastarg) {
372 config.auth = argv[i+1];
373 i++;
374 } else if (!strcmp(argv[i],"-i")) {
375 fprintf(stderr,
376 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
377 "by default when redis-cli is executed without a command to execute.\n"
378 );
379 } else if (!strcmp(argv[i],"-c")) {
380 fprintf(stderr,
381 "Reading last argument from standard input using -c is deprecated.\n"
382 "When standard input is connected to a pipe or regular file, it is\n"
383 "automatically used as last argument.\n"
384 );
385 } else if (!strcmp(argv[i],"-v")) {
386 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION);
387 exit(0);
388 } else {
389 break;
390 }
391 }
392 return i;
393 }
394
395 static sds readArgFromStdin(void) {
396 char buf[1024];
397 sds arg = sdsempty();
398
399 while(1) {
400 int nread = read(fileno(stdin),buf,1024);
401
402 if (nread == 0) break;
403 else if (nread == -1) {
404 perror("Reading from standard input");
405 exit(1);
406 }
407 arg = sdscatlen(arg,buf,nread);
408 }
409 return arg;
410 }
411
412 static void usage() {
413 fprintf(stderr, "usage: redis-cli [-iv] [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
414 fprintf(stderr, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
415 fprintf(stderr, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
416 fprintf(stderr, "example: redis-cli get my_passwd\n");
417 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
418 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
419 exit(1);
420 }
421
422 /* Turn the plain C strings into Sds strings */
423 static char **convertToSds(int count, char** args) {
424 int j;
425 char **sds = zmalloc(sizeof(char*)*count);
426
427 for(j = 0; j < count; j++)
428 sds[j] = sdsnew(args[j]);
429
430 return sds;
431 }
432
433 #define LINE_BUFLEN 4096
434 static void repl() {
435 int argc, j;
436 char *line;
437 sds *argv;
438
439 config.interactive = 1;
440 while((line = linenoise("redis> ")) != NULL) {
441 if (line[0] != '\0') {
442 argv = sdssplitargs(line,&argc);
443 linenoiseHistoryAdd(line);
444 if (config.historyfile) linenoiseHistorySave(config.historyfile);
445 if (argv == NULL) {
446 printf("Invalid argument(s)\n");
447 continue;
448 } else if (argc > 0) {
449 if (strcasecmp(argv[0],"quit") == 0 ||
450 strcasecmp(argv[0],"exit") == 0)
451 {
452 exit(0);
453 } else {
454 int err;
455 long long start_time = mstime(), elapsed;
456
457 if ((err = cliSendCommand(argc, argv, 1)) != 0) {
458 if (err == ECONNRESET) {
459 printf("Reconnecting... ");
460 fflush(stdout);
461 if (cliConnect(1) == -1) exit(1);
462 printf("OK\n");
463 cliSendCommand(argc,argv,1);
464 }
465 }
466 elapsed = mstime()-start_time;
467 if (elapsed > 500) printf("%.2f seconds\n",
468 (double)elapsed/1000);
469 }
470 }
471 /* Free the argument vector */
472 for (j = 0; j < argc; j++)
473 sdsfree(argv[j]);
474 zfree(argv);
475 }
476 /* linenoise() returns malloc-ed lines like readline() */
477 free(line);
478 }
479 exit(0);
480 }
481
482 static int noninteractive(int argc, char **argv) {
483 int retval = 0;
484 if (config.stdinarg) {
485 argv = zrealloc(argv, (argc+1)*sizeof(char*));
486 argv[argc] = readArgFromStdin();
487 retval = cliSendCommand(argc+1, argv, config.repeat);
488 } else {
489 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
490 retval = cliSendCommand(argc, argv, config.repeat);
491 }
492 return retval;
493 }
494
495 int main(int argc, char **argv) {
496 int firstarg;
497
498 config.hostip = "127.0.0.1";
499 config.hostport = 6379;
500 config.repeat = 1;
501 config.dbnum = 0;
502 config.interactive = 0;
503 config.shutdown = 0;
504 config.monitor_mode = 0;
505 config.pubsub_mode = 0;
506 config.raw_output = 0;
507 config.stdinarg = 0;
508 config.auth = NULL;
509 config.historyfile = NULL;
510 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
511 config.mb_sep = '\n';
512
513 if (getenv("HOME") != NULL) {
514 config.historyfile = malloc(256);
515 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
516 linenoiseHistoryLoad(config.historyfile);
517 }
518
519 firstarg = parseOptions(argc,argv);
520 argc -= firstarg;
521 argv += firstarg;
522
523 if (config.auth != NULL) {
524 char *authargv[2];
525 int dbnum = config.dbnum;
526
527 /* We need to save the real configured database number and set it to
528 * zero here, otherwise cliSendCommand() will try to perform the
529 * SELECT command before the authentication, and it will fail. */
530 config.dbnum = 0;
531 authargv[0] = "AUTH";
532 authargv[1] = config.auth;
533 cliSendCommand(2, convertToSds(2, authargv), 1);
534 config.dbnum = dbnum; /* restore the right DB number */
535 }
536
537 /* Start interactive mode when no command is provided */
538 if (argc == 0) repl();
539 /* Otherwise, we have some arguments to execute */
540 return noninteractive(argc,convertToSds(argc,argv));
541 }