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