]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
redis-cli now supports automatically reconnection in interactive mode
[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
41 #include "anet.h"
42 #include "sds.h"
43 #include "adlist.h"
44 #include "zmalloc.h"
45 #include "linenoise.h"
46
47 #define REDIS_CMD_INLINE 1
48 #define REDIS_CMD_BULK 2
49 #define REDIS_CMD_MULTIBULK 4
50
51 #define REDIS_NOTUSED(V) ((void) V)
52
53 static struct config {
54 char *hostip;
55 int hostport;
56 long repeat;
57 int dbnum;
58 int argn_from_stdin;
59 int interactive;
60 int shutdown;
61 int monitor_mode;
62 int pubsub_mode;
63 int raw_output;
64 char *auth;
65 char *historyfile;
66 } config;
67
68 static int cliReadReply(int fd);
69 static void usage();
70
71 /* Connect to the client. If force is not zero the connection is performed
72 * even if there is already a connected socket. */
73 static int cliConnect(int force) {
74 char err[ANET_ERR_LEN];
75 static int fd = ANET_ERR;
76
77 if (fd == ANET_ERR || force) {
78 if (force) close(fd);
79 fd = anetTcpConnect(err,config.hostip,config.hostport);
80 if (fd == ANET_ERR) {
81 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
82 return -1;
83 }
84 anetTcpNoDelay(NULL,fd);
85 }
86 return fd;
87 }
88
89 static sds cliReadLine(int fd) {
90 sds line = sdsempty();
91
92 while(1) {
93 char c;
94 ssize_t ret;
95
96 ret = read(fd,&c,1);
97 if (ret == -1) {
98 sdsfree(line);
99 return NULL;
100 } else if ((ret == 0) || (c == '\n')) {
101 break;
102 } else {
103 line = sdscatlen(line,&c,1);
104 }
105 }
106 return sdstrim(line,"\r\n");
107 }
108
109 static int cliReadSingleLineReply(int fd, int quiet) {
110 sds reply = cliReadLine(fd);
111
112 if (reply == NULL) return 1;
113 if (!quiet)
114 printf("%s\n", reply);
115 sdsfree(reply);
116 return 0;
117 }
118
119 static void printStringRepr(char *s, int len) {
120 printf("\"");
121 while(len--) {
122 switch(*s) {
123 case '\\':
124 case '"':
125 printf("\\%c",*s);
126 break;
127 case '\n': printf("\\n"); break;
128 case '\r': printf("\\r"); break;
129 case '\t': printf("\\t"); break;
130 case '\a': printf("\\a"); break;
131 case '\b': printf("\\b"); break;
132 default:
133 if (isprint(*s))
134 printf("%c",*s);
135 else
136 printf("\\x%02x",(unsigned char)*s);
137 break;
138 }
139 s++;
140 }
141 printf("\"\n");
142 }
143
144 static int cliReadBulkReply(int fd) {
145 sds replylen = cliReadLine(fd);
146 char *reply, crlf[2];
147 int bulklen;
148
149 if (replylen == NULL) return 1;
150 bulklen = atoi(replylen);
151 if (bulklen == -1) {
152 sdsfree(replylen);
153 printf("(nil)\n");
154 return 0;
155 }
156 reply = zmalloc(bulklen);
157 anetRead(fd,reply,bulklen);
158 anetRead(fd,crlf,2);
159 if (config.raw_output || !isatty(fileno(stdout))) {
160 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
161 zfree(reply);
162 return 1;
163 }
164 } else {
165 /* If you are producing output for the standard output we want
166 * a more interesting output with quoted characters and so forth */
167 printStringRepr(reply,bulklen);
168 }
169 zfree(reply);
170 return 0;
171 }
172
173 static int cliReadMultiBulkReply(int fd) {
174 sds replylen = cliReadLine(fd);
175 int elements, c = 1;
176 int retval = 0;
177
178 if (replylen == NULL) return 1;
179 elements = atoi(replylen);
180 if (elements == -1) {
181 sdsfree(replylen);
182 printf("(nil)\n");
183 return 0;
184 }
185 if (elements == 0) {
186 printf("(empty list or set)\n");
187 }
188 while(elements--) {
189 printf("%d. ", c);
190 if (cliReadReply(fd)) retval = 1;
191 c++;
192 }
193 return retval;
194 }
195
196 static int cliReadReply(int fd) {
197 char type;
198 int nread;
199
200 if ((nread = anetRead(fd,&type,1)) <= 0) {
201 if (config.shutdown) return 0;
202 if (config.interactive &&
203 (nread == 0 || (nread == -1 && errno == ECONNRESET)))
204 {
205 return ECONNRESET;
206 } else {
207 printf("I/O error while reading from socket: %s",strerror(errno));
208 exit(1);
209 }
210 }
211 switch(type) {
212 case '-':
213 printf("(error) ");
214 cliReadSingleLineReply(fd,0);
215 return 1;
216 case '+':
217 return cliReadSingleLineReply(fd,0);
218 case ':':
219 printf("(integer) ");
220 return cliReadSingleLineReply(fd,0);
221 case '$':
222 return cliReadBulkReply(fd);
223 case '*':
224 return cliReadMultiBulkReply(fd);
225 default:
226 printf("protocol error, got '%c' as reply type byte\n", type);
227 return 1;
228 }
229 }
230
231 static int selectDb(int fd) {
232 int retval;
233 sds cmd;
234 char type;
235
236 if (config.dbnum == 0)
237 return 0;
238
239 cmd = sdsempty();
240 cmd = sdscatprintf(cmd,"SELECT %d\r\n",config.dbnum);
241 anetWrite(fd,cmd,sdslen(cmd));
242 anetRead(fd,&type,1);
243 if (type <= 0 || type != '+') return 1;
244 retval = cliReadSingleLineReply(fd,1);
245 if (retval) {
246 return retval;
247 }
248 return 0;
249 }
250
251 static int cliSendCommand(int argc, char **argv, int repeat) {
252 char *command = argv[0];
253 int fd, j, retval = 0;
254 sds cmd;
255
256 config.raw_output = !strcasecmp(command,"info");
257 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
258 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
259 if (!strcasecmp(command,"subscribe") ||
260 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
261 if ((fd = cliConnect(0)) == -1) return 1;
262
263 /* Select db number */
264 retval = selectDb(fd);
265 if (retval) {
266 fprintf(stderr,"Error setting DB num\n");
267 return 1;
268 }
269
270 /* Build the command to send */
271 cmd = sdscatprintf(sdsempty(),"*%d\r\n",argc);
272 for (j = 0; j < argc; j++) {
273 cmd = sdscatprintf(cmd,"$%lu\r\n",
274 (unsigned long)sdslen(argv[j]));
275 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
276 cmd = sdscatlen(cmd,"\r\n",2);
277 }
278
279 while(repeat--) {
280 anetWrite(fd,cmd,sdslen(cmd));
281 while (config.monitor_mode) {
282 cliReadSingleLineReply(fd,0);
283 }
284
285 if (config.pubsub_mode) {
286 printf("Reading messages... (press Ctrl-c to quit)\n");
287 while (1) {
288 cliReadReply(fd);
289 printf("\n");
290 }
291 }
292
293 retval = cliReadReply(fd);
294 if (retval) {
295 return retval;
296 }
297 }
298 return 0;
299 }
300
301 static int parseOptions(int argc, char **argv) {
302 int i;
303
304 for (i = 1; i < argc; i++) {
305 int lastarg = i==argc-1;
306
307 if (!strcmp(argv[i],"-h") && !lastarg) {
308 char *ip = zmalloc(32);
309 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
310 printf("Can't resolve %s\n", argv[i]);
311 exit(1);
312 }
313 config.hostip = ip;
314 i++;
315 } else if (!strcmp(argv[i],"-h") && lastarg) {
316 usage();
317 } else if (!strcmp(argv[i],"-p") && !lastarg) {
318 config.hostport = atoi(argv[i+1]);
319 i++;
320 } else if (!strcmp(argv[i],"-r") && !lastarg) {
321 config.repeat = strtoll(argv[i+1],NULL,10);
322 i++;
323 } else if (!strcmp(argv[i],"-n") && !lastarg) {
324 config.dbnum = atoi(argv[i+1]);
325 i++;
326 } else if (!strcmp(argv[i],"-a") && !lastarg) {
327 config.auth = argv[i+1];
328 i++;
329 } else if (!strcmp(argv[i],"-i")) {
330 config.interactive = 1;
331 } else if (!strcmp(argv[i],"-c")) {
332 config.argn_from_stdin = 1;
333 } else if (!strcmp(argv[i],"-v")) {
334 printf("redis-cli shipped with Redis verison %s\n", REDIS_VERSION);
335 exit(0);
336 } else {
337 break;
338 }
339 }
340 return i;
341 }
342
343 static sds readArgFromStdin(void) {
344 char buf[1024];
345 sds arg = sdsempty();
346
347 while(1) {
348 int nread = read(fileno(stdin),buf,1024);
349
350 if (nread == 0) break;
351 else if (nread == -1) {
352 perror("Reading from standard input");
353 exit(1);
354 }
355 arg = sdscatlen(arg,buf,nread);
356 }
357 return arg;
358 }
359
360 static void usage() {
361 fprintf(stderr, "usage: redis-cli [-iv] [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
362 fprintf(stderr, "usage: echo \"argN\" | redis-cli -c [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
363 fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
364 fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
365 fprintf(stderr, "example: redis-cli get my_passwd\n");
366 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
367 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
368 exit(1);
369 }
370
371 /* Turn the plain C strings into Sds strings */
372 static char **convertToSds(int count, char** args) {
373 int j;
374 char **sds = zmalloc(sizeof(char*)*count);
375
376 for(j = 0; j < count; j++)
377 sds[j] = sdsnew(args[j]);
378
379 return sds;
380 }
381
382 #define LINE_BUFLEN 4096
383 static void repl() {
384 int argc, j;
385 char *line;
386 sds *argv;
387
388 while((line = linenoise("redis> ")) != NULL) {
389 if (line[0] != '\0') {
390 argv = sdssplitargs(line,&argc);
391 linenoiseHistoryAdd(line);
392 if (config.historyfile) linenoiseHistorySave(config.historyfile);
393 if (argc > 0) {
394 if (strcasecmp(argv[0],"quit") == 0 ||
395 strcasecmp(argv[0],"exit") == 0)
396 {
397 exit(0);
398 } else {
399 int err;
400
401 if ((err = cliSendCommand(argc, argv, 1)) != 0) {
402 if (err == ECONNRESET) {
403 printf("Reconnecting... ");
404 fflush(stdout);
405 if (cliConnect(1) == -1) exit(1);
406 printf("OK\n");
407 cliSendCommand(argc,argv,1);
408 }
409 }
410 }
411 }
412 /* Free the argument vector */
413 for (j = 0; j < argc; j++)
414 sdsfree(argv[j]);
415 zfree(argv);
416 }
417 /* linenoise() returns malloc-ed lines like readline() */
418 free(line);
419 }
420 exit(0);
421 }
422
423 int main(int argc, char **argv) {
424 int firstarg;
425 char **argvcopy;
426
427 config.hostip = "127.0.0.1";
428 config.hostport = 6379;
429 config.repeat = 1;
430 config.dbnum = 0;
431 config.argn_from_stdin = 0;
432 config.shutdown = 0;
433 config.interactive = 0;
434 config.monitor_mode = 0;
435 config.pubsub_mode = 0;
436 config.raw_output = 0;
437 config.auth = NULL;
438 config.historyfile = NULL;
439
440 if (getenv("HOME") != NULL) {
441 config.historyfile = malloc(256);
442 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
443 linenoiseHistoryLoad(config.historyfile);
444 }
445
446 firstarg = parseOptions(argc,argv);
447 argc -= firstarg;
448 argv += firstarg;
449
450 if (config.auth != NULL) {
451 char *authargv[2];
452
453 authargv[0] = "AUTH";
454 authargv[1] = config.auth;
455 cliSendCommand(2, convertToSds(2, authargv), 1);
456 }
457
458 if (argc == 0) config.interactive = 1;
459 if (config.interactive) repl();
460
461 argvcopy = convertToSds(argc+1, argv);
462 if (config.argn_from_stdin) {
463 sds lastarg = readArgFromStdin();
464 argvcopy[argc] = lastarg;
465 argc++;
466 }
467 return cliSendCommand(argc, argvcopy, config.repeat);
468 }