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