]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
Do not update the LRU info on key lookup when we have a saving child. With this trivi...
[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>
3ce014c7 41#include <sys/time.h>
ed9b544e 42
43#include "anet.h"
44#include "sds.h"
45#include "adlist.h"
46#include "zmalloc.h"
cf87ebf2 47#include "linenoise.h"
ed9b544e 48
ed9b544e 49#define REDIS_NOTUSED(V) ((void) V)
50
51static struct config {
52 char *hostip;
53 int hostport;
5762b7f0 54 long repeat;
62e920df 55 int dbnum;
5d15b520 56 int interactive;
36e5db6d 57 int shutdown;
249c3a7d 58 int monitor_mode;
59 int pubsub_mode;
f2dd4769 60 int raw_output; /* output mode per command */
123a10f7 61 int tty; /* flag for default output format */
bc63407b 62 int stdinarg; /* get last arg from stdin. (-x option) */
3a51bff0 63 char mb_sep;
288799e0 64 char *auth;
99628c1a 65 char *historyfile;
ed9b544e 66} config;
67
c937aa89 68static int cliReadReply(int fd);
a9158272 69static void usage();
c937aa89 70
3ce014c7 71/*------------------------------------------------------------------------------
72 * Utility functions
73 *--------------------------------------------------------------------------- */
74
75static 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
85static 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
c0b3d423 114/* Connect to the client. If force is not zero the connection is performed
115 * even if there is already a connected socket. */
116static int cliConnect(int force) {
ed9b544e 117 char err[ANET_ERR_LEN];
6fa24622 118 static int fd = ANET_ERR;
ed9b544e 119
c0b3d423 120 if (fd == ANET_ERR || force) {
121 if (force) close(fd);
6fa24622
DJMM
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);
ed9b544e 128 }
ed9b544e 129 return fd;
130}
131
132static sds cliReadLine(int fd) {
133 sds line = sdsempty();
134
135 while(1) {
136 char c;
b91f03a4 137 ssize_t ret;
ed9b544e 138
b91f03a4 139 ret = read(fd,&c,1);
e0e1c195 140 if (ret <= 0) {
ed9b544e 141 sdsfree(line);
142 return NULL;
b91f03a4 143 } else if ((ret == 0) || (c == '\n')) {
ed9b544e 144 break;
145 } else {
146 line = sdscatlen(line,&c,1);
147 }
148 }
149 return sdstrim(line,"\r\n");
150}
151
62e920df 152static int cliReadSingleLineReply(int fd, int quiet) {
ed9b544e 153 sds reply = cliReadLine(fd);
154
155 if (reply == NULL) return 1;
62e920df 156 if (!quiet)
3a51bff0 157 printf("%s", reply);
621d5c19 158 sdsfree(reply);
ed9b544e 159 return 0;
160}
161
c937aa89 162static int cliReadBulkReply(int fd) {
ed9b544e 163 sds replylen = cliReadLine(fd);
164 char *reply, crlf[2];
c937aa89 165 int bulklen;
ed9b544e 166
167 if (replylen == NULL) return 1;
ed9b544e 168 bulklen = atoi(replylen);
c937aa89 169 if (bulklen == -1) {
ed9b544e 170 sdsfree(replylen);
060f6be6 171 printf("(nil)\n");
ed9b544e 172 return 0;
173 }
ed9b544e 174 reply = zmalloc(bulklen);
175 anetRead(fd,reply,bulklen);
176 anetRead(fd,crlf,2);
123a10f7 177 if (config.raw_output || !config.tty) {
21cdc9f0 178 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
179 zfree(reply);
180 return 1;
181 }
21cdc9f0 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);
ed9b544e 186 }
ed9b544e 187 zfree(reply);
c937aa89 188 return 0;
ed9b544e 189}
190
191static int cliReadMultiBulkReply(int fd) {
192 sds replylen = cliReadLine(fd);
193 int elements, c = 1;
b37ca6ed 194 int retval = 0;
ed9b544e 195
196 if (replylen == NULL) return 1;
c937aa89 197 elements = atoi(replylen);
198 if (elements == -1) {
ed9b544e 199 sdsfree(replylen);
200 printf("(nil)\n");
201 return 0;
202 }
c937aa89 203 if (elements == 0) {
204 printf("(empty list or set)\n");
205 }
ed9b544e 206 while(elements--) {
3a51bff0 207 if (config.tty) printf("%d. ", c);
b37ca6ed 208 if (cliReadReply(fd)) retval = 1;
3a51bff0 209 if (elements) printf("%c",config.mb_sep);
ed9b544e 210 c++;
211 }
b37ca6ed 212 return retval;
ed9b544e 213}
214
c937aa89 215static int cliReadReply(int fd) {
216 char type;
c0b3d423 217 int nread;
c937aa89 218
c0b3d423 219 if ((nread = anetRead(fd,&type,1)) <= 0) {
36e5db6d 220 if (config.shutdown) return 0;
c0b3d423 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 }
36e5db6d 229 }
c937aa89 230 switch(type) {
231 case '-':
3a51bff0 232 if (config.tty) printf("(error) ");
62e920df 233 cliReadSingleLineReply(fd,0);
c937aa89 234 return 1;
235 case '+':
62e920df 236 return cliReadSingleLineReply(fd,0);
c937aa89 237 case ':':
3a51bff0 238 if (config.tty) printf("(integer) ");
62e920df 239 return cliReadSingleLineReply(fd,0);
c937aa89 240 case '$':
241 return cliReadBulkReply(fd);
242 case '*':
243 return cliReadMultiBulkReply(fd);
244 default:
ae77016e 245 printf("protocol error, got '%c' as reply type byte", type);
c937aa89 246 return 1;
247 }
248}
249
6cf5882c 250static int selectDb(int fd) {
62e920df 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) {
6cf5882c 265 return retval;
62e920df 266 }
267 return 0;
268}
269
8079656a 270static 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
aab055ae 286static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 287 char *command = argv[0];
ed9b544e 288 int fd, j, retval = 0;
5762b7f0 289 sds cmd;
ed9b544e 290
37dc9e5a 291 config.raw_output = !strcasecmp(command,"info");
8079656a 292 if (!strcasecmp(command,"help")) {
293 showInteractiveHelp();
294 return 0;
295 }
37dc9e5a
PN
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;
c0b3d423 300 if ((fd = cliConnect(0)) == -1) return 1;
ed9b544e 301
62e920df 302 /* Select db number */
303 retval = selectDb(fd);
304 if (retval) {
305 fprintf(stderr,"Error setting DB num\n");
306 return 1;
307 }
6cf5882c 308
a2f4f871
PN
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
aab055ae 318 while(repeat--) {
5762b7f0 319 anetWrite(fd,cmd,sdslen(cmd));
249c3a7d 320 while (config.monitor_mode) {
e0e1c195 321 if (cliReadSingleLineReply(fd,0)) exit(1);
322 printf("\n");
621d5c19 323 }
324
249c3a7d 325 if (config.pubsub_mode) {
326 printf("Reading messages... (press Ctrl-c to quit)\n");
327 while (1) {
328 cliReadReply(fd);
3a51bff0 329 printf("\n\n");
249c3a7d 330 }
331 }
332
5762b7f0 333 retval = cliReadReply(fd);
ae77016e
PN
334 if (!config.raw_output && config.tty) printf("\n");
335 if (retval) return retval;
ed9b544e 336 }
ed9b544e 337 return 0;
338}
339
3ce014c7 340/*------------------------------------------------------------------------------
341 * User interface
342 *--------------------------------------------------------------------------- */
343
ed9b544e 344static int parseOptions(int argc, char **argv) {
345 int i;
346
347 for (i = 1; i < argc; i++) {
348 int lastarg = i==argc-1;
6cf5882c 349
ed9b544e 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++;
a9158272 358 } else if (!strcmp(argv[i],"-h") && lastarg) {
359 usage();
bc63407b 360 } else if (!strcmp(argv[i],"-x")) {
361 config.stdinarg = 1;
ed9b544e 362 } else if (!strcmp(argv[i],"-p") && !lastarg) {
363 config.hostport = atoi(argv[i+1]);
364 i++;
5762b7f0 365 } else if (!strcmp(argv[i],"-r") && !lastarg) {
366 config.repeat = strtoll(argv[i+1],NULL,10);
367 i++;
62e920df 368 } else if (!strcmp(argv[i],"-n") && !lastarg) {
369 config.dbnum = atoi(argv[i+1]);
370 i++;
fdfdae0f 371 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 372 config.auth = argv[i+1];
fdfdae0f 373 i++;
6cf5882c 374 } else if (!strcmp(argv[i],"-i")) {
abb731e5
PN
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 );
37dc9e5a 379 } else if (!strcmp(argv[i],"-c")) {
b4b62c34
PN
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 );
185cabda 385 } else if (!strcmp(argv[i],"-v")) {
fdc0bde9 386 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION);
185cabda 387 exit(0);
ed9b544e 388 } else {
389 break;
390 }
391 }
392 return i;
393}
394
395static 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
a9158272 412static void usage() {
185cabda 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");
bc63407b 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");
a9158272 416 fprintf(stderr, "example: redis-cli get my_passwd\n");
417 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
d239ec59 418 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 419 exit(1);
420}
421
6cf5882c
MMDJ
422/* Turn the plain C strings into Sds strings */
423static char **convertToSds(int count, char** args) {
424 int j;
37dc9e5a 425 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
426
427 for(j = 0; j < count; j++)
428 sds[j] = sdsnew(args[j]);
429
430 return sds;
431}
432
a88a2af6 433#define LINE_BUFLEN 4096
6cf5882c 434static void repl() {
a88a2af6 435 int argc, j;
cbce5171 436 char *line;
437 sds *argv;
6cf5882c 438
5d15b520 439 config.interactive = 1;
bc86d88e 440 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 441 if (line[0] != '\0') {
cbce5171 442 argv = sdssplitargs(line,&argc);
a88a2af6 443 linenoiseHistoryAdd(line);
99628c1a 444 if (config.historyfile) linenoiseHistorySave(config.historyfile);
0439d792
PN
445 if (argv == NULL) {
446 printf("Invalid argument(s)\n");
447 continue;
448 } else if (argc > 0) {
a88a2af6 449 if (strcasecmp(argv[0],"quit") == 0 ||
450 strcasecmp(argv[0],"exit") == 0)
c0b3d423 451 {
452 exit(0);
453 } else {
454 int err;
3ce014c7 455 long long start_time = mstime(), elapsed;
c0b3d423 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 }
3ce014c7 466 elapsed = mstime()-start_time;
467 if (elapsed > 500) printf("%.2f seconds\n",
468 (double)elapsed/1000);
c0b3d423 469 }
a88a2af6 470 }
471 /* Free the argument vector */
472 for (j = 0; j < argc; j++)
473 sdsfree(argv[j]);
8ff6a48b 474 zfree(argv);
6cf5882c 475 }
a88a2af6 476 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 477 free(line);
6cf5882c 478 }
6cf5882c
MMDJ
479 exit(0);
480}
481
b4b62c34
PN
482static int noninteractive(int argc, char **argv) {
483 int retval = 0;
bc63407b 484 if (config.stdinarg) {
b4b62c34
PN
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
ed9b544e 495int main(int argc, char **argv) {
6cf5882c 496 int firstarg;
ed9b544e 497
498 config.hostip = "127.0.0.1";
499 config.hostport = 6379;
5762b7f0 500 config.repeat = 1;
62e920df 501 config.dbnum = 0;
5d15b520 502 config.interactive = 0;
36e5db6d 503 config.shutdown = 0;
249c3a7d 504 config.monitor_mode = 0;
505 config.pubsub_mode = 0;
f40b035d 506 config.raw_output = 0;
bc63407b 507 config.stdinarg = 0;
288799e0 508 config.auth = NULL;
99628c1a 509 config.historyfile = NULL;
cf0c6b78 510 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
3a51bff0 511 config.mb_sep = '\n';
99628c1a 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 }
ed9b544e 518
519 firstarg = parseOptions(argc,argv);
520 argc -= firstarg;
521 argv += firstarg;
ed9b544e 522
aab055ae
MMDJ
523 if (config.auth != NULL) {
524 char *authargv[2];
93b2a771 525 int dbnum = config.dbnum;
aab055ae 526
93b2a771 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;
aab055ae
MMDJ
531 authargv[0] = "AUTH";
532 authargv[1] = config.auth;
533 cliSendCommand(2, convertToSds(2, authargv), 1);
93b2a771 534 config.dbnum = dbnum; /* restore the right DB number */
aab055ae
MMDJ
535 }
536
abb731e5
PN
537 /* Start interactive mode when no command is provided */
538 if (argc == 0) repl();
b4b62c34
PN
539 /* Otherwise, we have some arguments to execute */
540 return noninteractive(argc,convertToSds(argc,argv));
ed9b544e 541}