]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
Add hiredis dependency for redis-cli, redis-benchmark, etc
[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;
7e91f971 54 char *hostsocket;
5762b7f0 55 long repeat;
62e920df 56 int dbnum;
5d15b520 57 int interactive;
36e5db6d 58 int shutdown;
249c3a7d 59 int monitor_mode;
60 int pubsub_mode;
f2dd4769 61 int raw_output; /* output mode per command */
123a10f7 62 int tty; /* flag for default output format */
bc63407b 63 int stdinarg; /* get last arg from stdin. (-x option) */
3a51bff0 64 char mb_sep;
288799e0 65 char *auth;
99628c1a 66 char *historyfile;
ed9b544e 67} config;
68
c937aa89 69static int cliReadReply(int fd);
a9158272 70static void usage();
c937aa89 71
3ce014c7 72/*------------------------------------------------------------------------------
73 * Utility functions
74 *--------------------------------------------------------------------------- */
75
76static 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
86static 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
c0b3d423 115/* Connect to the client. If force is not zero the connection is performed
116 * even if there is already a connected socket. */
117static int cliConnect(int force) {
ed9b544e 118 char err[ANET_ERR_LEN];
6fa24622 119 static int fd = ANET_ERR;
ed9b544e 120
c0b3d423 121 if (fd == ANET_ERR || force) {
122 if (force) close(fd);
7e91f971
PN
123 if (config.hostsocket == NULL) {
124 fd = anetTcpConnect(err,config.hostip,config.hostport);
125 } else {
126 fd = anetUnixConnect(err,config.hostsocket);
7e91f971 127 }
6fa24622 128 if (fd == ANET_ERR) {
7e91f971
PN
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);
6fa24622
DJMM
134 return -1;
135 }
136 anetTcpNoDelay(NULL,fd);
ed9b544e 137 }
ed9b544e 138 return fd;
139}
140
141static sds cliReadLine(int fd) {
142 sds line = sdsempty();
143
144 while(1) {
145 char c;
b91f03a4 146 ssize_t ret;
ed9b544e 147
b91f03a4 148 ret = read(fd,&c,1);
e0e1c195 149 if (ret <= 0) {
ed9b544e 150 sdsfree(line);
151 return NULL;
b91f03a4 152 } else if ((ret == 0) || (c == '\n')) {
ed9b544e 153 break;
154 } else {
155 line = sdscatlen(line,&c,1);
156 }
157 }
158 return sdstrim(line,"\r\n");
159}
160
62e920df 161static int cliReadSingleLineReply(int fd, int quiet) {
ed9b544e 162 sds reply = cliReadLine(fd);
163
164 if (reply == NULL) return 1;
62e920df 165 if (!quiet)
3a51bff0 166 printf("%s", reply);
621d5c19 167 sdsfree(reply);
ed9b544e 168 return 0;
169}
170
c937aa89 171static int cliReadBulkReply(int fd) {
ed9b544e 172 sds replylen = cliReadLine(fd);
173 char *reply, crlf[2];
c937aa89 174 int bulklen;
ed9b544e 175
176 if (replylen == NULL) return 1;
ed9b544e 177 bulklen = atoi(replylen);
c937aa89 178 if (bulklen == -1) {
ed9b544e 179 sdsfree(replylen);
060f6be6 180 printf("(nil)\n");
ed9b544e 181 return 0;
182 }
ed9b544e 183 reply = zmalloc(bulklen);
184 anetRead(fd,reply,bulklen);
185 anetRead(fd,crlf,2);
123a10f7 186 if (config.raw_output || !config.tty) {
21cdc9f0 187 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
188 zfree(reply);
189 return 1;
190 }
21cdc9f0 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);
ed9b544e 195 }
ed9b544e 196 zfree(reply);
c937aa89 197 return 0;
ed9b544e 198}
199
200static int cliReadMultiBulkReply(int fd) {
201 sds replylen = cliReadLine(fd);
202 int elements, c = 1;
b37ca6ed 203 int retval = 0;
ed9b544e 204
205 if (replylen == NULL) return 1;
c937aa89 206 elements = atoi(replylen);
207 if (elements == -1) {
ed9b544e 208 sdsfree(replylen);
209 printf("(nil)\n");
210 return 0;
211 }
c937aa89 212 if (elements == 0) {
213 printf("(empty list or set)\n");
214 }
ed9b544e 215 while(elements--) {
3a51bff0 216 if (config.tty) printf("%d. ", c);
b37ca6ed 217 if (cliReadReply(fd)) retval = 1;
3a51bff0 218 if (elements) printf("%c",config.mb_sep);
ed9b544e 219 c++;
220 }
b37ca6ed 221 return retval;
ed9b544e 222}
223
c937aa89 224static int cliReadReply(int fd) {
225 char type;
c0b3d423 226 int nread;
c937aa89 227
c0b3d423 228 if ((nread = anetRead(fd,&type,1)) <= 0) {
36e5db6d 229 if (config.shutdown) return 0;
c0b3d423 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 }
36e5db6d 238 }
c937aa89 239 switch(type) {
240 case '-':
3a51bff0 241 if (config.tty) printf("(error) ");
62e920df 242 cliReadSingleLineReply(fd,0);
c937aa89 243 return 1;
244 case '+':
62e920df 245 return cliReadSingleLineReply(fd,0);
c937aa89 246 case ':':
3a51bff0 247 if (config.tty) printf("(integer) ");
62e920df 248 return cliReadSingleLineReply(fd,0);
c937aa89 249 case '$':
250 return cliReadBulkReply(fd);
251 case '*':
252 return cliReadMultiBulkReply(fd);
253 default:
ae77016e 254 printf("protocol error, got '%c' as reply type byte", type);
c937aa89 255 return 1;
256 }
257}
258
6cf5882c 259static int selectDb(int fd) {
62e920df 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) {
6cf5882c 274 return retval;
62e920df 275 }
276 return 0;
277}
278
8079656a 279static 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
aab055ae 295static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 296 char *command = argv[0];
ed9b544e 297 int fd, j, retval = 0;
5762b7f0 298 sds cmd;
ed9b544e 299
37dc9e5a 300 config.raw_output = !strcasecmp(command,"info");
8079656a 301 if (!strcasecmp(command,"help")) {
302 showInteractiveHelp();
303 return 0;
304 }
37dc9e5a
PN
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;
c0b3d423 309 if ((fd = cliConnect(0)) == -1) return 1;
ed9b544e 310
62e920df 311 /* Select db number */
312 retval = selectDb(fd);
313 if (retval) {
314 fprintf(stderr,"Error setting DB num\n");
315 return 1;
316 }
6cf5882c 317
a2f4f871
PN
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
aab055ae 327 while(repeat--) {
5762b7f0 328 anetWrite(fd,cmd,sdslen(cmd));
249c3a7d 329 while (config.monitor_mode) {
e0e1c195 330 if (cliReadSingleLineReply(fd,0)) exit(1);
331 printf("\n");
621d5c19 332 }
333
249c3a7d 334 if (config.pubsub_mode) {
335 printf("Reading messages... (press Ctrl-c to quit)\n");
336 while (1) {
337 cliReadReply(fd);
3a51bff0 338 printf("\n\n");
249c3a7d 339 }
340 }
341
5762b7f0 342 retval = cliReadReply(fd);
ae77016e
PN
343 if (!config.raw_output && config.tty) printf("\n");
344 if (retval) return retval;
ed9b544e 345 }
ed9b544e 346 return 0;
347}
348
3ce014c7 349/*------------------------------------------------------------------------------
350 * User interface
351 *--------------------------------------------------------------------------- */
352
ed9b544e 353static int parseOptions(int argc, char **argv) {
354 int i;
355
356 for (i = 1; i < argc; i++) {
357 int lastarg = i==argc-1;
6cf5882c 358
ed9b544e 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++;
a9158272 367 } else if (!strcmp(argv[i],"-h") && lastarg) {
368 usage();
bc63407b 369 } else if (!strcmp(argv[i],"-x")) {
370 config.stdinarg = 1;
ed9b544e 371 } else if (!strcmp(argv[i],"-p") && !lastarg) {
372 config.hostport = atoi(argv[i+1]);
373 i++;
7e91f971
PN
374 } else if (!strcmp(argv[i],"-s") && !lastarg) {
375 config.hostsocket = argv[i+1];
376 i++;
5762b7f0 377 } else if (!strcmp(argv[i],"-r") && !lastarg) {
378 config.repeat = strtoll(argv[i+1],NULL,10);
379 i++;
62e920df 380 } else if (!strcmp(argv[i],"-n") && !lastarg) {
381 config.dbnum = atoi(argv[i+1]);
382 i++;
fdfdae0f 383 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 384 config.auth = argv[i+1];
fdfdae0f 385 i++;
6cf5882c 386 } else if (!strcmp(argv[i],"-i")) {
abb731e5
PN
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 );
37dc9e5a 391 } else if (!strcmp(argv[i],"-c")) {
b4b62c34
PN
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 );
185cabda 397 } else if (!strcmp(argv[i],"-v")) {
fdc0bde9 398 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION);
185cabda 399 exit(0);
ed9b544e 400 } else {
401 break;
402 }
403 }
404 return i;
405}
406
407static 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
a9158272 424static void usage() {
7e91f971 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");
bc63407b 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");
a9158272 428 fprintf(stderr, "example: redis-cli get my_passwd\n");
429 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
d239ec59 430 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 431 exit(1);
432}
433
6cf5882c
MMDJ
434/* Turn the plain C strings into Sds strings */
435static char **convertToSds(int count, char** args) {
436 int j;
37dc9e5a 437 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
438
439 for(j = 0; j < count; j++)
440 sds[j] = sdsnew(args[j]);
441
442 return sds;
443}
444
a88a2af6 445#define LINE_BUFLEN 4096
6cf5882c 446static void repl() {
a88a2af6 447 int argc, j;
cbce5171 448 char *line;
449 sds *argv;
6cf5882c 450
5d15b520 451 config.interactive = 1;
bc86d88e 452 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 453 if (line[0] != '\0') {
cbce5171 454 argv = sdssplitargs(line,&argc);
a88a2af6 455 linenoiseHistoryAdd(line);
99628c1a 456 if (config.historyfile) linenoiseHistorySave(config.historyfile);
0439d792
PN
457 if (argv == NULL) {
458 printf("Invalid argument(s)\n");
459 continue;
460 } else if (argc > 0) {
a88a2af6 461 if (strcasecmp(argv[0],"quit") == 0 ||
462 strcasecmp(argv[0],"exit") == 0)
c0b3d423 463 {
464 exit(0);
465 } else {
466 int err;
3ce014c7 467 long long start_time = mstime(), elapsed;
c0b3d423 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 }
3ce014c7 478 elapsed = mstime()-start_time;
479 if (elapsed > 500) printf("%.2f seconds\n",
480 (double)elapsed/1000);
c0b3d423 481 }
a88a2af6 482 }
483 /* Free the argument vector */
484 for (j = 0; j < argc; j++)
485 sdsfree(argv[j]);
8ff6a48b 486 zfree(argv);
6cf5882c 487 }
a88a2af6 488 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 489 free(line);
6cf5882c 490 }
6cf5882c
MMDJ
491 exit(0);
492}
493
b4b62c34
PN
494static int noninteractive(int argc, char **argv) {
495 int retval = 0;
bc63407b 496 if (config.stdinarg) {
b4b62c34
PN
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
ed9b544e 507int main(int argc, char **argv) {
6cf5882c 508 int firstarg;
ed9b544e 509
510 config.hostip = "127.0.0.1";
511 config.hostport = 6379;
7e91f971 512 config.hostsocket = NULL;
5762b7f0 513 config.repeat = 1;
62e920df 514 config.dbnum = 0;
5d15b520 515 config.interactive = 0;
36e5db6d 516 config.shutdown = 0;
249c3a7d 517 config.monitor_mode = 0;
518 config.pubsub_mode = 0;
f40b035d 519 config.raw_output = 0;
bc63407b 520 config.stdinarg = 0;
288799e0 521 config.auth = NULL;
99628c1a 522 config.historyfile = NULL;
cf0c6b78 523 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
3a51bff0 524 config.mb_sep = '\n';
99628c1a 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 }
ed9b544e 531
532 firstarg = parseOptions(argc,argv);
533 argc -= firstarg;
534 argv += firstarg;
ed9b544e 535
aab055ae
MMDJ
536 if (config.auth != NULL) {
537 char *authargv[2];
93b2a771 538 int dbnum = config.dbnum;
aab055ae 539
93b2a771 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;
aab055ae
MMDJ
544 authargv[0] = "AUTH";
545 authargv[1] = config.auth;
546 cliSendCommand(2, convertToSds(2, authargv), 1);
93b2a771 547 config.dbnum = dbnum; /* restore the right DB number */
aab055ae
MMDJ
548 }
549
abb731e5
PN
550 /* Start interactive mode when no command is provided */
551 if (argc == 0) repl();
b4b62c34
PN
552 /* Otherwise, we have some arguments to execute */
553 return noninteractive(argc,convertToSds(argc,argv));
ed9b544e 554}