]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
redis-cli now supports automatically reconnection in interactive mode
[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>
ed9b544e 40
41#include "anet.h"
42#include "sds.h"
43#include "adlist.h"
44#include "zmalloc.h"
cf87ebf2 45#include "linenoise.h"
ed9b544e 46
47#define REDIS_CMD_INLINE 1
48#define REDIS_CMD_BULK 2
e17e0b05 49#define REDIS_CMD_MULTIBULK 4
ed9b544e 50
51#define REDIS_NOTUSED(V) ((void) V)
52
53static struct config {
54 char *hostip;
55 int hostport;
5762b7f0 56 long repeat;
62e920df 57 int dbnum;
37dc9e5a 58 int argn_from_stdin;
6cf5882c 59 int interactive;
36e5db6d 60 int shutdown;
249c3a7d 61 int monitor_mode;
62 int pubsub_mode;
f40b035d 63 int raw_output;
288799e0 64 char *auth;
99628c1a 65 char *historyfile;
ed9b544e 66} config;
67
c937aa89 68static int cliReadReply(int fd);
a9158272 69static void usage();
c937aa89 70
c0b3d423 71/* Connect to the client. If force is not zero the connection is performed
72 * even if there is already a connected socket. */
73static int cliConnect(int force) {
ed9b544e 74 char err[ANET_ERR_LEN];
6fa24622 75 static int fd = ANET_ERR;
ed9b544e 76
c0b3d423 77 if (fd == ANET_ERR || force) {
78 if (force) close(fd);
6fa24622
DJMM
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);
ed9b544e 85 }
ed9b544e 86 return fd;
87}
88
89static sds cliReadLine(int fd) {
90 sds line = sdsempty();
91
92 while(1) {
93 char c;
b91f03a4 94 ssize_t ret;
ed9b544e 95
b91f03a4
LH
96 ret = read(fd,&c,1);
97 if (ret == -1) {
ed9b544e 98 sdsfree(line);
99 return NULL;
b91f03a4 100 } else if ((ret == 0) || (c == '\n')) {
ed9b544e 101 break;
102 } else {
103 line = sdscatlen(line,&c,1);
104 }
105 }
106 return sdstrim(line,"\r\n");
107}
108
62e920df 109static int cliReadSingleLineReply(int fd, int quiet) {
ed9b544e 110 sds reply = cliReadLine(fd);
111
112 if (reply == NULL) return 1;
62e920df 113 if (!quiet)
114 printf("%s\n", reply);
621d5c19 115 sdsfree(reply);
ed9b544e 116 return 0;
117}
118
21cdc9f0 119static 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
c937aa89 144static int cliReadBulkReply(int fd) {
ed9b544e 145 sds replylen = cliReadLine(fd);
146 char *reply, crlf[2];
c937aa89 147 int bulklen;
ed9b544e 148
149 if (replylen == NULL) return 1;
ed9b544e 150 bulklen = atoi(replylen);
c937aa89 151 if (bulklen == -1) {
ed9b544e 152 sdsfree(replylen);
060f6be6 153 printf("(nil)\n");
ed9b544e 154 return 0;
155 }
ed9b544e 156 reply = zmalloc(bulklen);
157 anetRead(fd,reply,bulklen);
158 anetRead(fd,crlf,2);
f40b035d 159 if (config.raw_output || !isatty(fileno(stdout))) {
21cdc9f0 160 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
161 zfree(reply);
162 return 1;
163 }
21cdc9f0 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);
ed9b544e 168 }
ed9b544e 169 zfree(reply);
c937aa89 170 return 0;
ed9b544e 171}
172
173static int cliReadMultiBulkReply(int fd) {
174 sds replylen = cliReadLine(fd);
175 int elements, c = 1;
b37ca6ed 176 int retval = 0;
ed9b544e 177
178 if (replylen == NULL) return 1;
c937aa89 179 elements = atoi(replylen);
180 if (elements == -1) {
ed9b544e 181 sdsfree(replylen);
182 printf("(nil)\n");
183 return 0;
184 }
c937aa89 185 if (elements == 0) {
186 printf("(empty list or set)\n");
187 }
ed9b544e 188 while(elements--) {
189 printf("%d. ", c);
b37ca6ed 190 if (cliReadReply(fd)) retval = 1;
ed9b544e 191 c++;
192 }
b37ca6ed 193 return retval;
ed9b544e 194}
195
c937aa89 196static int cliReadReply(int fd) {
197 char type;
c0b3d423 198 int nread;
c937aa89 199
c0b3d423 200 if ((nread = anetRead(fd,&type,1)) <= 0) {
36e5db6d 201 if (config.shutdown) return 0;
c0b3d423 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 }
36e5db6d 210 }
c937aa89 211 switch(type) {
212 case '-':
213 printf("(error) ");
62e920df 214 cliReadSingleLineReply(fd,0);
c937aa89 215 return 1;
216 case '+':
62e920df 217 return cliReadSingleLineReply(fd,0);
c937aa89 218 case ':':
443c6409 219 printf("(integer) ");
62e920df 220 return cliReadSingleLineReply(fd,0);
c937aa89 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
6cf5882c 231static int selectDb(int fd) {
62e920df 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) {
6cf5882c 246 return retval;
62e920df 247 }
248 return 0;
249}
250
aab055ae 251static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 252 char *command = argv[0];
ed9b544e 253 int fd, j, retval = 0;
5762b7f0 254 sds cmd;
ed9b544e 255
37dc9e5a
PN
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;
c0b3d423 261 if ((fd = cliConnect(0)) == -1) return 1;
ed9b544e 262
62e920df 263 /* Select db number */
264 retval = selectDb(fd);
265 if (retval) {
266 fprintf(stderr,"Error setting DB num\n");
267 return 1;
268 }
6cf5882c 269
a2f4f871
PN
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
aab055ae 279 while(repeat--) {
5762b7f0 280 anetWrite(fd,cmd,sdslen(cmd));
249c3a7d 281 while (config.monitor_mode) {
621d5c19 282 cliReadSingleLineReply(fd,0);
283 }
284
249c3a7d 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
5762b7f0 293 retval = cliReadReply(fd);
294 if (retval) {
36e5db6d 295 return retval;
8165a5f2 296 }
ed9b544e 297 }
ed9b544e 298 return 0;
299}
300
301static int parseOptions(int argc, char **argv) {
302 int i;
303
304 for (i = 1; i < argc; i++) {
305 int lastarg = i==argc-1;
6cf5882c 306
ed9b544e 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++;
a9158272 315 } else if (!strcmp(argv[i],"-h") && lastarg) {
316 usage();
ed9b544e 317 } else if (!strcmp(argv[i],"-p") && !lastarg) {
318 config.hostport = atoi(argv[i+1]);
319 i++;
5762b7f0 320 } else if (!strcmp(argv[i],"-r") && !lastarg) {
321 config.repeat = strtoll(argv[i+1],NULL,10);
322 i++;
62e920df 323 } else if (!strcmp(argv[i],"-n") && !lastarg) {
324 config.dbnum = atoi(argv[i+1]);
325 i++;
fdfdae0f 326 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 327 config.auth = argv[i+1];
fdfdae0f 328 i++;
6cf5882c
MMDJ
329 } else if (!strcmp(argv[i],"-i")) {
330 config.interactive = 1;
37dc9e5a
PN
331 } else if (!strcmp(argv[i],"-c")) {
332 config.argn_from_stdin = 1;
185cabda 333 } else if (!strcmp(argv[i],"-v")) {
334 printf("redis-cli shipped with Redis verison %s\n", REDIS_VERSION);
335 exit(0);
ed9b544e 336 } else {
337 break;
338 }
339 }
340 return i;
341}
342
343static 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
a9158272 360static void usage() {
185cabda 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");
37dc9e5a 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");
a9158272 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");
d239ec59 367 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 368 exit(1);
369}
370
6cf5882c
MMDJ
371/* Turn the plain C strings into Sds strings */
372static char **convertToSds(int count, char** args) {
373 int j;
37dc9e5a 374 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
375
376 for(j = 0; j < count; j++)
377 sds[j] = sdsnew(args[j]);
378
379 return sds;
380}
381
a88a2af6 382#define LINE_BUFLEN 4096
6cf5882c 383static void repl() {
a88a2af6 384 int argc, j;
cbce5171 385 char *line;
386 sds *argv;
6cf5882c 387
bc86d88e 388 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 389 if (line[0] != '\0') {
cbce5171 390 argv = sdssplitargs(line,&argc);
a88a2af6 391 linenoiseHistoryAdd(line);
99628c1a 392 if (config.historyfile) linenoiseHistorySave(config.historyfile);
a88a2af6 393 if (argc > 0) {
394 if (strcasecmp(argv[0],"quit") == 0 ||
395 strcasecmp(argv[0],"exit") == 0)
c0b3d423 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 }
a88a2af6 411 }
412 /* Free the argument vector */
413 for (j = 0; j < argc; j++)
414 sdsfree(argv[j]);
8ff6a48b 415 zfree(argv);
6cf5882c 416 }
a88a2af6 417 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 418 free(line);
6cf5882c 419 }
6cf5882c
MMDJ
420 exit(0);
421}
422
ed9b544e 423int main(int argc, char **argv) {
6cf5882c 424 int firstarg;
ed9b544e 425 char **argvcopy;
426
427 config.hostip = "127.0.0.1";
428 config.hostport = 6379;
5762b7f0 429 config.repeat = 1;
62e920df 430 config.dbnum = 0;
37dc9e5a 431 config.argn_from_stdin = 0;
36e5db6d 432 config.shutdown = 0;
6cf5882c 433 config.interactive = 0;
249c3a7d 434 config.monitor_mode = 0;
435 config.pubsub_mode = 0;
f40b035d 436 config.raw_output = 0;
288799e0 437 config.auth = NULL;
99628c1a 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 }
ed9b544e 445
446 firstarg = parseOptions(argc,argv);
447 argc -= firstarg;
448 argv += firstarg;
ed9b544e 449
aab055ae
MMDJ
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
c0b3d423 458 if (argc == 0) config.interactive = 1;
459 if (config.interactive) repl();
ed9b544e 460
37dc9e5a
PN
461 argvcopy = convertToSds(argc+1, argv);
462 if (config.argn_from_stdin) {
6cf5882c
MMDJ
463 sds lastarg = readArgFromStdin();
464 argvcopy[argc] = lastarg;
465 argc++;
2073a849 466 }
aab055ae 467 return cliSendCommand(argc, argvcopy, config.repeat);
ed9b544e 468}