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