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