]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
make sure to flush stdout every line read in monitor mode, to play well with redirect...
[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
7fc4ce13 43#include "hiredis.h"
ed9b544e 44#include "sds.h"
ed9b544e 45#include "zmalloc.h"
cf87ebf2 46#include "linenoise.h"
ed9b544e 47
ed9b544e 48#define REDIS_NOTUSED(V) ((void) V)
49
7fc4ce13 50static redisContext *context;
ed9b544e 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
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
3ce014c7 85/*------------------------------------------------------------------------------
86 * Networking / parsing
87 *--------------------------------------------------------------------------- */
88
7fc4ce13
PN
89/* Send AUTH command to the server */
90static int cliAuth() {
91 redisReply *reply;
92 if (config.auth == NULL) return REDIS_OK;
93
94 reply = redisCommand(context,"AUTH %s",config.auth);
95 if (reply != NULL) {
96 freeReplyObject(reply);
97 return REDIS_OK;
98 }
99 return REDIS_ERR;
100}
101
102/* Send SELECT dbnum to the server */
103static int cliSelect() {
104 redisReply *reply;
105 char dbnum[16];
106 if (config.dbnum == 0) return REDIS_OK;
107
108 snprintf(dbnum,sizeof(dbnum),"%d",config.dbnum);
109 reply = redisCommand(context,"SELECT %s",dbnum);
110 if (reply != NULL) {
111 freeReplyObject(reply);
112 return REDIS_OK;
113 }
114 return REDIS_ERR;
115}
116
c0b3d423 117/* Connect to the client. If force is not zero the connection is performed
118 * even if there is already a connected socket. */
119static int cliConnect(int force) {
7fc4ce13
PN
120 if (context == NULL || force) {
121 if (context != NULL)
122 redisFree(context);
ed9b544e 123
7e91f971 124 if (config.hostsocket == NULL) {
7fc4ce13 125 context = redisConnect(config.hostip,config.hostport);
7e91f971 126 } else {
7fc4ce13 127 context = redisConnectUnix(config.hostsocket);
7e91f971 128 }
7fc4ce13
PN
129
130 if (context->err) {
7e91f971
PN
131 fprintf(stderr,"Could not connect to Redis at ");
132 if (config.hostsocket == NULL)
7fc4ce13 133 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
7e91f971 134 else
7fc4ce13
PN
135 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
136 redisFree(context);
137 context = NULL;
138 return REDIS_ERR;
6fa24622 139 }
ed9b544e 140
7fc4ce13
PN
141 /* Do AUTH and select the right DB. */
142 if (cliAuth() != REDIS_OK)
143 return REDIS_ERR;
144 if (cliSelect() != REDIS_OK)
145 return REDIS_ERR;
ed9b544e 146 }
7fc4ce13 147 return REDIS_OK;
ed9b544e 148}
149
7fc4ce13
PN
150static void cliPrintContextErrorAndExit() {
151 if (context == NULL) return;
152 fprintf(stderr,"Error: %s\n",context->errstr);
153 exit(1);
ed9b544e 154}
155
7fc4ce13
PN
156static sds cliFormatReply(redisReply *r, char *prefix) {
157 sds out = sdsempty();
158 switch (r->type) {
159 case REDIS_REPLY_ERROR:
7fc4ce13
PN
160 if (config.tty) out = sdscat(out,"(error) ");
161 out = sdscatprintf(out,"%s\n", r->str);
162 break;
163 case REDIS_REPLY_STATUS:
7fc4ce13
PN
164 out = sdscat(out,r->str);
165 out = sdscat(out,"\n");
166 break;
167 case REDIS_REPLY_INTEGER:
7fc4ce13
PN
168 if (config.tty) out = sdscat(out,"(integer) ");
169 out = sdscatprintf(out,"%lld\n",r->integer);
170 break;
171 case REDIS_REPLY_STRING:
7fc4ce13
PN
172 if (config.raw_output || !config.tty) {
173 out = sdscatlen(out,r->str,r->len);
174 } else {
175 /* If you are producing output for the standard output we want
176 * a more interesting output with quoted characters and so forth */
177 out = sdscatrepr(out,r->str,r->len);
178 out = sdscat(out,"\n");
21cdc9f0 179 }
7fc4ce13
PN
180 break;
181 case REDIS_REPLY_NIL:
7fc4ce13
PN
182 out = sdscat(out,"(nil)\n");
183 break;
184 case REDIS_REPLY_ARRAY:
185 if (r->elements == 0) {
7fc4ce13 186 out = sdscat(out,"(empty list or set)\n");
c0b3d423 187 } else {
cfcd5d6d
PN
188 unsigned int i, idxlen = 0;
189 char _prefixlen[16];
190 char _prefixfmt[16];
191 sds _prefix;
7fc4ce13
PN
192 sds tmp;
193
cfcd5d6d
PN
194 /* Calculate chars needed to represent the largest index */
195 i = r->elements;
196 do {
197 idxlen++;
198 i /= 10;
199 } while(i);
200
201 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
202 memset(_prefixlen,' ',idxlen+2);
203 _prefixlen[idxlen+2] = '\0';
204 _prefix = sdscat(sdsnew(prefix),_prefixlen);
205
206 /* Setup prefix format for every entry */
207 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);
208
7fc4ce13 209 for (i = 0; i < r->elements; i++) {
cfcd5d6d
PN
210 /* Don't use the prefix for the first element, as the parent
211 * caller already prepended the index number. */
212 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);
213
214 /* Format the multi bulk entry */
215 tmp = cliFormatReply(r->element[i],_prefix);
7fc4ce13
PN
216 out = sdscatlen(out,tmp,sdslen(tmp));
217 sdsfree(tmp);
218 }
cfcd5d6d 219 sdsfree(_prefix);
c0b3d423 220 }
7fc4ce13 221 break;
c937aa89 222 default:
7fc4ce13
PN
223 fprintf(stderr,"Unknown reply type: %d\n", r->type);
224 exit(1);
c937aa89 225 }
7fc4ce13 226 return out;
c937aa89 227}
228
7fc4ce13
PN
229static int cliReadReply() {
230 redisReply *reply;
231 sds out;
232
233 if (redisGetReply(context,(void**)&reply) != REDIS_OK) {
234 if (config.shutdown)
235 return REDIS_OK;
236 if (config.interactive) {
237 /* Filter cases where we should reconnect */
238 if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
239 return REDIS_ERR;
240 if (context->err == REDIS_ERR_EOF)
241 return REDIS_ERR;
242 }
243 cliPrintContextErrorAndExit();
244 return REDIS_ERR; /* avoid compiler warning */
62e920df 245 }
7fc4ce13
PN
246
247 out = cliFormatReply(reply,"");
248 freeReplyObject(reply);
249 fwrite(out,sdslen(out),1,stdout);
250 sdsfree(out);
251 return REDIS_OK;
62e920df 252}
253
8079656a 254static void showInteractiveHelp(void) {
255 printf(
256 "\n"
257 "Welcome to redis-cli " REDIS_VERSION "!\n"
258 "Just type any valid Redis command to see a pretty printed output.\n"
259 "\n"
260 "It is possible to quote strings, like in:\n"
261 " set \"my key\" \"some string \\xff\\n\"\n"
262 "\n"
263 "You can find a list of valid Redis commands at\n"
264 " http://code.google.com/p/redis/wiki/CommandReference\n"
265 "\n"
266 "Note: redis-cli supports line editing, use up/down arrows for history."
267 "\n\n");
268}
269
aab055ae 270static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 271 char *command = argv[0];
7fc4ce13
PN
272 size_t *argvlen;
273 int j;
ed9b544e 274
37dc9e5a 275 config.raw_output = !strcasecmp(command,"info");
8079656a 276 if (!strcasecmp(command,"help")) {
277 showInteractiveHelp();
7fc4ce13 278 return REDIS_OK;
8079656a 279 }
37dc9e5a
PN
280 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
281 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
282 if (!strcasecmp(command,"subscribe") ||
283 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
ed9b544e 284
7fc4ce13
PN
285 /* Setup argument length */
286 argvlen = malloc(argc*sizeof(size_t));
287 for (j = 0; j < argc; j++)
288 argvlen[j] = sdslen(argv[j]);
a2f4f871 289
aab055ae 290 while(repeat--) {
7fc4ce13 291 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
249c3a7d 292 while (config.monitor_mode) {
7fc4ce13 293 if (cliReadReply() != REDIS_OK) exit(1);
d9d8ccab 294 fflush(stdout);
621d5c19 295 }
296
249c3a7d 297 if (config.pubsub_mode) {
7fc4ce13 298 printf("Reading messages... (press Ctrl-C to quit)\n");
249c3a7d 299 while (1) {
7fc4ce13 300 if (cliReadReply() != REDIS_OK) exit(1);
249c3a7d 301 }
302 }
303
7fc4ce13
PN
304 if (cliReadReply() != REDIS_OK)
305 return REDIS_ERR;
ed9b544e 306 }
7fc4ce13 307 return REDIS_OK;
ed9b544e 308}
309
3ce014c7 310/*------------------------------------------------------------------------------
311 * User interface
312 *--------------------------------------------------------------------------- */
313
ed9b544e 314static int parseOptions(int argc, char **argv) {
315 int i;
316
317 for (i = 1; i < argc; i++) {
318 int lastarg = i==argc-1;
6cf5882c 319
ed9b544e 320 if (!strcmp(argv[i],"-h") && !lastarg) {
7fc4ce13 321 config.hostip = argv[i+1];
ed9b544e 322 i++;
a9158272 323 } else if (!strcmp(argv[i],"-h") && lastarg) {
324 usage();
bc63407b 325 } else if (!strcmp(argv[i],"-x")) {
326 config.stdinarg = 1;
ed9b544e 327 } else if (!strcmp(argv[i],"-p") && !lastarg) {
328 config.hostport = atoi(argv[i+1]);
329 i++;
7e91f971
PN
330 } else if (!strcmp(argv[i],"-s") && !lastarg) {
331 config.hostsocket = argv[i+1];
332 i++;
5762b7f0 333 } else if (!strcmp(argv[i],"-r") && !lastarg) {
334 config.repeat = strtoll(argv[i+1],NULL,10);
335 i++;
62e920df 336 } else if (!strcmp(argv[i],"-n") && !lastarg) {
337 config.dbnum = atoi(argv[i+1]);
338 i++;
fdfdae0f 339 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 340 config.auth = argv[i+1];
fdfdae0f 341 i++;
6cf5882c 342 } else if (!strcmp(argv[i],"-i")) {
abb731e5
PN
343 fprintf(stderr,
344"Starting interactive mode using -i is deprecated. Interactive mode is started\n"
345"by default when redis-cli is executed without a command to execute.\n"
346 );
37dc9e5a 347 } else if (!strcmp(argv[i],"-c")) {
b4b62c34
PN
348 fprintf(stderr,
349"Reading last argument from standard input using -c is deprecated.\n"
350"When standard input is connected to a pipe or regular file, it is\n"
351"automatically used as last argument.\n"
352 );
185cabda 353 } else if (!strcmp(argv[i],"-v")) {
fdc0bde9 354 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION);
185cabda 355 exit(0);
ed9b544e 356 } else {
357 break;
358 }
359 }
360 return i;
361}
362
363static sds readArgFromStdin(void) {
364 char buf[1024];
365 sds arg = sdsempty();
366
367 while(1) {
368 int nread = read(fileno(stdin),buf,1024);
369
370 if (nread == 0) break;
371 else if (nread == -1) {
372 perror("Reading from standard input");
373 exit(1);
374 }
375 arg = sdscatlen(arg,buf,nread);
376 }
377 return arg;
378}
379
a9158272 380static void usage() {
7e91f971 381 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 382 fprintf(stderr, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
383 fprintf(stderr, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
a9158272 384 fprintf(stderr, "example: redis-cli get my_passwd\n");
385 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
d239ec59 386 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 387 exit(1);
388}
389
6cf5882c
MMDJ
390/* Turn the plain C strings into Sds strings */
391static char **convertToSds(int count, char** args) {
392 int j;
37dc9e5a 393 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
394
395 for(j = 0; j < count; j++)
396 sds[j] = sdsnew(args[j]);
397
398 return sds;
399}
400
a88a2af6 401#define LINE_BUFLEN 4096
6cf5882c 402static void repl() {
a88a2af6 403 int argc, j;
cbce5171 404 char *line;
405 sds *argv;
6cf5882c 406
5d15b520 407 config.interactive = 1;
bc86d88e 408 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 409 if (line[0] != '\0') {
cbce5171 410 argv = sdssplitargs(line,&argc);
a88a2af6 411 linenoiseHistoryAdd(line);
99628c1a 412 if (config.historyfile) linenoiseHistorySave(config.historyfile);
0439d792
PN
413 if (argv == NULL) {
414 printf("Invalid argument(s)\n");
415 continue;
416 } else if (argc > 0) {
a88a2af6 417 if (strcasecmp(argv[0],"quit") == 0 ||
418 strcasecmp(argv[0],"exit") == 0)
c0b3d423 419 {
420 exit(0);
421 } else {
3ce014c7 422 long long start_time = mstime(), elapsed;
c0b3d423 423
7fc4ce13
PN
424 if (cliSendCommand(argc,argv,1) != REDIS_OK) {
425 printf("Reconnecting... ");
426 fflush(stdout);
427 if (cliConnect(1) != REDIS_OK) exit(1);
428 printf("OK\n");
429
430 /* If we still cannot send the command,
431 * print error and abort. */
432 if (cliSendCommand(argc,argv,1) != REDIS_OK)
433 cliPrintContextErrorAndExit();
c0b3d423 434 }
3ce014c7 435 elapsed = mstime()-start_time;
339b9dc2
PN
436 if (elapsed >= 500) {
437 printf("(%.2fs)\n",(double)elapsed/1000);
438 }
c0b3d423 439 }
a88a2af6 440 }
441 /* Free the argument vector */
442 for (j = 0; j < argc; j++)
443 sdsfree(argv[j]);
8ff6a48b 444 zfree(argv);
6cf5882c 445 }
a88a2af6 446 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 447 free(line);
6cf5882c 448 }
6cf5882c
MMDJ
449 exit(0);
450}
451
b4b62c34
PN
452static int noninteractive(int argc, char **argv) {
453 int retval = 0;
bc63407b 454 if (config.stdinarg) {
b4b62c34
PN
455 argv = zrealloc(argv, (argc+1)*sizeof(char*));
456 argv[argc] = readArgFromStdin();
457 retval = cliSendCommand(argc+1, argv, config.repeat);
458 } else {
459 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
460 retval = cliSendCommand(argc, argv, config.repeat);
461 }
462 return retval;
463}
464
ed9b544e 465int main(int argc, char **argv) {
6cf5882c 466 int firstarg;
ed9b544e 467
468 config.hostip = "127.0.0.1";
469 config.hostport = 6379;
7e91f971 470 config.hostsocket = NULL;
5762b7f0 471 config.repeat = 1;
62e920df 472 config.dbnum = 0;
5d15b520 473 config.interactive = 0;
36e5db6d 474 config.shutdown = 0;
249c3a7d 475 config.monitor_mode = 0;
476 config.pubsub_mode = 0;
f40b035d 477 config.raw_output = 0;
bc63407b 478 config.stdinarg = 0;
288799e0 479 config.auth = NULL;
99628c1a 480 config.historyfile = NULL;
cf0c6b78 481 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
3a51bff0 482 config.mb_sep = '\n';
99628c1a 483
484 if (getenv("HOME") != NULL) {
485 config.historyfile = malloc(256);
486 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
487 linenoiseHistoryLoad(config.historyfile);
488 }
ed9b544e 489
490 firstarg = parseOptions(argc,argv);
491 argc -= firstarg;
492 argv += firstarg;
ed9b544e 493
7fc4ce13
PN
494 /* Try to connect */
495 if (cliConnect(0) != REDIS_OK) exit(1);
aab055ae 496
abb731e5
PN
497 /* Start interactive mode when no command is provided */
498 if (argc == 0) repl();
b4b62c34
PN
499 /* Otherwise, we have some arguments to execute */
500 return noninteractive(argc,convertToSds(argc,argv));
ed9b544e 501}