]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
now redis-cli is able to show the Git SHA1 in the version output
[redis.git] / src / redis-cli.c
1 /* Redis CLI (command line interface)
2 *
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
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
31 #include "fmacros.h"
32 #include "version.h"
33
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <sys/stat.h>
41 #include <sys/time.h>
42
43 #include "hiredis.h"
44 #include "sds.h"
45 #include "zmalloc.h"
46 #include "linenoise.h"
47
48 #define REDIS_NOTUSED(V) ((void) V)
49
50 static redisContext *context;
51 static struct config {
52 char *hostip;
53 int hostport;
54 char *hostsocket;
55 long repeat;
56 int dbnum;
57 int interactive;
58 int shutdown;
59 int monitor_mode;
60 int pubsub_mode;
61 int raw_output; /* output mode per command */
62 int tty; /* flag for default output format */
63 int stdinarg; /* get last arg from stdin. (-x option) */
64 char mb_sep;
65 char *auth;
66 char *historyfile;
67 } config;
68
69 static void usage();
70 char *redisGitSHA1(void);
71
72 /*------------------------------------------------------------------------------
73 * Utility functions
74 *--------------------------------------------------------------------------- */
75
76 static 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
86 /*------------------------------------------------------------------------------
87 * Networking / parsing
88 *--------------------------------------------------------------------------- */
89
90 /* Send AUTH command to the server */
91 static 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 */
104 static 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
118 /* Connect to the client. If force is not zero the connection is performed
119 * even if there is already a connected socket. */
120 static int cliConnect(int force) {
121 if (context == NULL || force) {
122 if (context != NULL)
123 redisFree(context);
124
125 if (config.hostsocket == NULL) {
126 context = redisConnect(config.hostip,config.hostport);
127 } else {
128 context = redisConnectUnix(config.hostsocket);
129 }
130
131 if (context->err) {
132 fprintf(stderr,"Could not connect to Redis at ");
133 if (config.hostsocket == NULL)
134 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
135 else
136 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
137 redisFree(context);
138 context = NULL;
139 return REDIS_ERR;
140 }
141
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;
147 }
148 return REDIS_OK;
149 }
150
151 static void cliPrintContextErrorAndExit() {
152 if (context == NULL) return;
153 fprintf(stderr,"Error: %s\n",context->errstr);
154 exit(1);
155 }
156
157 static sds cliFormatReply(redisReply *r, char *prefix) {
158 sds out = sdsempty();
159 switch (r->type) {
160 case REDIS_REPLY_ERROR:
161 if (config.tty) out = sdscat(out,"(error) ");
162 out = sdscatprintf(out,"%s\n", r->str);
163 break;
164 case REDIS_REPLY_STATUS:
165 out = sdscat(out,r->str);
166 out = sdscat(out,"\n");
167 break;
168 case REDIS_REPLY_INTEGER:
169 if (config.tty) out = sdscat(out,"(integer) ");
170 out = sdscatprintf(out,"%lld\n",r->integer);
171 break;
172 case REDIS_REPLY_STRING:
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");
180 }
181 break;
182 case REDIS_REPLY_NIL:
183 out = sdscat(out,"(nil)\n");
184 break;
185 case REDIS_REPLY_ARRAY:
186 if (r->elements == 0) {
187 out = sdscat(out,"(empty list or set)\n");
188 } else {
189 unsigned int i, idxlen = 0;
190 char _prefixlen[16];
191 char _prefixfmt[16];
192 sds _prefix;
193 sds tmp;
194
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
210 for (i = 0; i < r->elements; i++) {
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);
217 out = sdscatlen(out,tmp,sdslen(tmp));
218 sdsfree(tmp);
219 }
220 sdsfree(_prefix);
221 }
222 break;
223 default:
224 fprintf(stderr,"Unknown reply type: %d\n", r->type);
225 exit(1);
226 }
227 return out;
228 }
229
230 static 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 */
246 }
247
248 out = cliFormatReply(reply,"");
249 freeReplyObject(reply);
250 fwrite(out,sdslen(out),1,stdout);
251 sdsfree(out);
252 return REDIS_OK;
253 }
254
255 static 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
271 static int cliSendCommand(int argc, char **argv, int repeat) {
272 char *command = argv[0];
273 size_t *argvlen;
274 int j;
275
276 config.raw_output = !strcasecmp(command,"info");
277 if (!strcasecmp(command,"help")) {
278 showInteractiveHelp();
279 return REDIS_OK;
280 }
281 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
282 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
283 if (!strcasecmp(command,"subscribe") ||
284 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
285
286 /* Setup argument length */
287 argvlen = malloc(argc*sizeof(size_t));
288 for (j = 0; j < argc; j++)
289 argvlen[j] = sdslen(argv[j]);
290
291 while(repeat--) {
292 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
293 while (config.monitor_mode) {
294 if (cliReadReply() != REDIS_OK) exit(1);
295 fflush(stdout);
296 }
297
298 if (config.pubsub_mode) {
299 printf("Reading messages... (press Ctrl-C to quit)\n");
300 while (1) {
301 if (cliReadReply() != REDIS_OK) exit(1);
302 }
303 }
304
305 if (cliReadReply() != REDIS_OK)
306 return REDIS_ERR;
307 }
308 return REDIS_OK;
309 }
310
311 /*------------------------------------------------------------------------------
312 * User interface
313 *--------------------------------------------------------------------------- */
314
315 static int parseOptions(int argc, char **argv) {
316 int i;
317
318 for (i = 1; i < argc; i++) {
319 int lastarg = i==argc-1;
320
321 if (!strcmp(argv[i],"-h") && !lastarg) {
322 config.hostip = argv[i+1];
323 i++;
324 } else if (!strcmp(argv[i],"-h") && lastarg) {
325 usage();
326 } else if (!strcmp(argv[i],"-x")) {
327 config.stdinarg = 1;
328 } else if (!strcmp(argv[i],"-p") && !lastarg) {
329 config.hostport = atoi(argv[i+1]);
330 i++;
331 } else if (!strcmp(argv[i],"-s") && !lastarg) {
332 config.hostsocket = argv[i+1];
333 i++;
334 } else if (!strcmp(argv[i],"-r") && !lastarg) {
335 config.repeat = strtoll(argv[i+1],NULL,10);
336 i++;
337 } else if (!strcmp(argv[i],"-n") && !lastarg) {
338 config.dbnum = atoi(argv[i+1]);
339 i++;
340 } else if (!strcmp(argv[i],"-a") && !lastarg) {
341 config.auth = argv[i+1];
342 i++;
343 } else if (!strcmp(argv[i],"-i")) {
344 fprintf(stderr,
345 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
346 "by default when redis-cli is executed without a command to execute.\n"
347 );
348 } else if (!strcmp(argv[i],"-c")) {
349 fprintf(stderr,
350 "Reading last argument from standard input using -c is deprecated.\n"
351 "When standard input is connected to a pipe or regular file, it is\n"
352 "automatically used as last argument.\n"
353 );
354 } else if (!strcmp(argv[i],"-v")) {
355 printf("redis-cli shipped with Redis version %s (%s)\n", REDIS_VERSION, redisGitSHA1());
356 exit(0);
357 } else {
358 break;
359 }
360 }
361 return i;
362 }
363
364 static sds readArgFromStdin(void) {
365 char buf[1024];
366 sds arg = sdsempty();
367
368 while(1) {
369 int nread = read(fileno(stdin),buf,1024);
370
371 if (nread == 0) break;
372 else if (nread == -1) {
373 perror("Reading from standard input");
374 exit(1);
375 }
376 arg = sdscatlen(arg,buf,nread);
377 }
378 return arg;
379 }
380
381 static void usage() {
382 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");
383 fprintf(stderr, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
384 fprintf(stderr, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
385 fprintf(stderr, "example: redis-cli get my_passwd\n");
386 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
387 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
388 exit(1);
389 }
390
391 /* Turn the plain C strings into Sds strings */
392 static char **convertToSds(int count, char** args) {
393 int j;
394 char **sds = zmalloc(sizeof(char*)*count);
395
396 for(j = 0; j < count; j++)
397 sds[j] = sdsnew(args[j]);
398
399 return sds;
400 }
401
402 #define LINE_BUFLEN 4096
403 static void repl() {
404 int argc, j;
405 char *line;
406 sds *argv;
407
408 config.interactive = 1;
409 while((line = linenoise("redis> ")) != NULL) {
410 if (line[0] != '\0') {
411 argv = sdssplitargs(line,&argc);
412 linenoiseHistoryAdd(line);
413 if (config.historyfile) linenoiseHistorySave(config.historyfile);
414 if (argv == NULL) {
415 printf("Invalid argument(s)\n");
416 continue;
417 } else if (argc > 0) {
418 if (strcasecmp(argv[0],"quit") == 0 ||
419 strcasecmp(argv[0],"exit") == 0)
420 {
421 exit(0);
422 } else {
423 long long start_time = mstime(), elapsed;
424
425 if (cliSendCommand(argc,argv,1) != REDIS_OK) {
426 printf("Reconnecting... ");
427 fflush(stdout);
428 if (cliConnect(1) != REDIS_OK) exit(1);
429 printf("OK\n");
430
431 /* If we still cannot send the command,
432 * print error and abort. */
433 if (cliSendCommand(argc,argv,1) != REDIS_OK)
434 cliPrintContextErrorAndExit();
435 }
436 elapsed = mstime()-start_time;
437 if (elapsed >= 500) {
438 printf("(%.2fs)\n",(double)elapsed/1000);
439 }
440 }
441 }
442 /* Free the argument vector */
443 for (j = 0; j < argc; j++)
444 sdsfree(argv[j]);
445 zfree(argv);
446 }
447 /* linenoise() returns malloc-ed lines like readline() */
448 free(line);
449 }
450 exit(0);
451 }
452
453 static int noninteractive(int argc, char **argv) {
454 int retval = 0;
455 if (config.stdinarg) {
456 argv = zrealloc(argv, (argc+1)*sizeof(char*));
457 argv[argc] = readArgFromStdin();
458 retval = cliSendCommand(argc+1, argv, config.repeat);
459 } else {
460 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
461 retval = cliSendCommand(argc, argv, config.repeat);
462 }
463 return retval;
464 }
465
466 int main(int argc, char **argv) {
467 int firstarg;
468
469 config.hostip = "127.0.0.1";
470 config.hostport = 6379;
471 config.hostsocket = NULL;
472 config.repeat = 1;
473 config.dbnum = 0;
474 config.interactive = 0;
475 config.shutdown = 0;
476 config.monitor_mode = 0;
477 config.pubsub_mode = 0;
478 config.raw_output = 0;
479 config.stdinarg = 0;
480 config.auth = NULL;
481 config.historyfile = NULL;
482 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
483 config.mb_sep = '\n';
484
485 if (getenv("HOME") != NULL) {
486 config.historyfile = malloc(256);
487 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
488 linenoiseHistoryLoad(config.historyfile);
489 }
490
491 firstarg = parseOptions(argc,argv);
492 argc -= firstarg;
493 argv += firstarg;
494
495 /* Try to connect */
496 if (cliConnect(0) != REDIS_OK) exit(1);
497
498 /* Start interactive mode when no command is provided */
499 if (argc == 0) repl();
500 /* Otherwise, we have some arguments to execute */
501 return noninteractive(argc,convertToSds(argc,argv));
502 }