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