]>
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 | #include <assert.h> | |
43 | ||
44 | #include "hiredis.h" | |
45 | #include "sds.h" | |
46 | #include "zmalloc.h" | |
47 | #include "linenoise.h" | |
48 | #include "help.h" | |
49 | ||
50 | #define REDIS_NOTUSED(V) ((void) V) | |
51 | ||
52 | static redisContext *context; | |
53 | static struct config { | |
54 | char *hostip; | |
55 | int hostport; | |
56 | char *hostsocket; | |
57 | long repeat; | |
58 | long interval; | |
59 | int dbnum; | |
60 | int interactive; | |
61 | int shutdown; | |
62 | int monitor_mode; | |
63 | int pubsub_mode; | |
64 | int latency_mode; | |
65 | int stdinarg; /* get last arg from stdin. (-x option) */ | |
66 | char *auth; | |
67 | int raw_output; /* output mode per command */ | |
68 | sds mb_delim; | |
69 | char prompt[32]; | |
70 | } config; | |
71 | ||
72 | static void usage(); | |
73 | char *redisGitSHA1(void); | |
74 | char *redisGitDirty(void); | |
75 | ||
76 | /*------------------------------------------------------------------------------ | |
77 | * Utility functions | |
78 | *--------------------------------------------------------------------------- */ | |
79 | ||
80 | static long long mstime(void) { | |
81 | struct timeval tv; | |
82 | long long mst; | |
83 | ||
84 | gettimeofday(&tv, NULL); | |
85 | mst = ((long)tv.tv_sec)*1000; | |
86 | mst += tv.tv_usec/1000; | |
87 | return mst; | |
88 | } | |
89 | ||
90 | static void cliRefreshPrompt(void) { | |
91 | if (config.dbnum == 0) | |
92 | snprintf(config.prompt,sizeof(config.prompt),"redis %s:%d> ", | |
93 | config.hostip, config.hostport); | |
94 | else | |
95 | snprintf(config.prompt,sizeof(config.prompt),"redis %s:%d[%d]> ", | |
96 | config.hostip, config.hostport, config.dbnum); | |
97 | } | |
98 | ||
99 | /*------------------------------------------------------------------------------ | |
100 | * Help functions | |
101 | *--------------------------------------------------------------------------- */ | |
102 | ||
103 | #define CLI_HELP_COMMAND 1 | |
104 | #define CLI_HELP_GROUP 2 | |
105 | ||
106 | typedef struct { | |
107 | int type; | |
108 | int argc; | |
109 | sds *argv; | |
110 | sds full; | |
111 | ||
112 | /* Only used for help on commands */ | |
113 | struct commandHelp *org; | |
114 | } helpEntry; | |
115 | ||
116 | static helpEntry *helpEntries; | |
117 | static int helpEntriesLen; | |
118 | ||
119 | static sds cliVersion() { | |
120 | sds version; | |
121 | version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION); | |
122 | ||
123 | /* Add git commit and working tree status when available */ | |
124 | if (strtoll(redisGitSHA1(),NULL,16)) { | |
125 | version = sdscatprintf(version, " (git:%s", redisGitSHA1()); | |
126 | if (strtoll(redisGitDirty(),NULL,10)) | |
127 | version = sdscatprintf(version, "-dirty"); | |
128 | version = sdscat(version, ")"); | |
129 | } | |
130 | return version; | |
131 | } | |
132 | ||
133 | static void cliInitHelp() { | |
134 | int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp); | |
135 | int groupslen = sizeof(commandGroups)/sizeof(char*); | |
136 | int i, len, pos = 0; | |
137 | helpEntry tmp; | |
138 | ||
139 | helpEntriesLen = len = commandslen+groupslen; | |
140 | helpEntries = malloc(sizeof(helpEntry)*len); | |
141 | ||
142 | for (i = 0; i < groupslen; i++) { | |
143 | tmp.argc = 1; | |
144 | tmp.argv = malloc(sizeof(sds)); | |
145 | tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]); | |
146 | tmp.full = tmp.argv[0]; | |
147 | tmp.type = CLI_HELP_GROUP; | |
148 | tmp.org = NULL; | |
149 | helpEntries[pos++] = tmp; | |
150 | } | |
151 | ||
152 | for (i = 0; i < commandslen; i++) { | |
153 | tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc); | |
154 | tmp.full = sdsnew(commandHelp[i].name); | |
155 | tmp.type = CLI_HELP_COMMAND; | |
156 | tmp.org = &commandHelp[i]; | |
157 | helpEntries[pos++] = tmp; | |
158 | } | |
159 | } | |
160 | ||
161 | /* Output command help to stdout. */ | |
162 | static void cliOutputCommandHelp(struct commandHelp *help, int group) { | |
163 | printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params); | |
164 | printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary); | |
165 | printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since); | |
166 | if (group) { | |
167 | printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]); | |
168 | } | |
169 | } | |
170 | ||
171 | /* Print generic help. */ | |
172 | static void cliOutputGenericHelp() { | |
173 | sds version = cliVersion(); | |
174 | printf( | |
175 | "redis-cli %s\r\n" | |
176 | "Type: \"help @<group>\" to get a list of commands in <group>\r\n" | |
177 | " \"help <command>\" for help on <command>\r\n" | |
178 | " \"help <tab>\" to get a list of possible help topics\r\n" | |
179 | " \"quit\" to exit\r\n", | |
180 | version | |
181 | ); | |
182 | sdsfree(version); | |
183 | } | |
184 | ||
185 | /* Output all command help, filtering by group or command name. */ | |
186 | static void cliOutputHelp(int argc, char **argv) { | |
187 | int i, j, len; | |
188 | int group = -1; | |
189 | helpEntry *entry; | |
190 | struct commandHelp *help; | |
191 | ||
192 | if (argc == 0) { | |
193 | cliOutputGenericHelp(); | |
194 | return; | |
195 | } else if (argc > 0 && argv[0][0] == '@') { | |
196 | len = sizeof(commandGroups)/sizeof(char*); | |
197 | for (i = 0; i < len; i++) { | |
198 | if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) { | |
199 | group = i; | |
200 | break; | |
201 | } | |
202 | } | |
203 | } | |
204 | ||
205 | assert(argc > 0); | |
206 | for (i = 0; i < helpEntriesLen; i++) { | |
207 | entry = &helpEntries[i]; | |
208 | if (entry->type != CLI_HELP_COMMAND) continue; | |
209 | ||
210 | help = entry->org; | |
211 | if (group == -1) { | |
212 | /* Compare all arguments */ | |
213 | if (argc == entry->argc) { | |
214 | for (j = 0; j < argc; j++) { | |
215 | if (strcasecmp(argv[j],entry->argv[j]) != 0) break; | |
216 | } | |
217 | if (j == argc) { | |
218 | cliOutputCommandHelp(help,1); | |
219 | } | |
220 | } | |
221 | } else { | |
222 | if (group == help->group) { | |
223 | cliOutputCommandHelp(help,0); | |
224 | } | |
225 | } | |
226 | } | |
227 | printf("\r\n"); | |
228 | } | |
229 | ||
230 | static void completionCallback(const char *buf, linenoiseCompletions *lc) { | |
231 | size_t startpos = 0; | |
232 | int mask; | |
233 | int i; | |
234 | size_t matchlen; | |
235 | sds tmp; | |
236 | ||
237 | if (strncasecmp(buf,"help ",5) == 0) { | |
238 | startpos = 5; | |
239 | while (isspace(buf[startpos])) startpos++; | |
240 | mask = CLI_HELP_COMMAND | CLI_HELP_GROUP; | |
241 | } else { | |
242 | mask = CLI_HELP_COMMAND; | |
243 | } | |
244 | ||
245 | for (i = 0; i < helpEntriesLen; i++) { | |
246 | if (!(helpEntries[i].type & mask)) continue; | |
247 | ||
248 | matchlen = strlen(buf+startpos); | |
249 | if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) { | |
250 | tmp = sdsnewlen(buf,startpos); | |
251 | tmp = sdscat(tmp,helpEntries[i].full); | |
252 | linenoiseAddCompletion(lc,tmp); | |
253 | sdsfree(tmp); | |
254 | } | |
255 | } | |
256 | } | |
257 | ||
258 | /*------------------------------------------------------------------------------ | |
259 | * Networking / parsing | |
260 | *--------------------------------------------------------------------------- */ | |
261 | ||
262 | /* Send AUTH command to the server */ | |
263 | static int cliAuth() { | |
264 | redisReply *reply; | |
265 | if (config.auth == NULL) return REDIS_OK; | |
266 | ||
267 | reply = redisCommand(context,"AUTH %s",config.auth); | |
268 | if (reply != NULL) { | |
269 | freeReplyObject(reply); | |
270 | return REDIS_OK; | |
271 | } | |
272 | return REDIS_ERR; | |
273 | } | |
274 | ||
275 | /* Send SELECT dbnum to the server */ | |
276 | static int cliSelect() { | |
277 | redisReply *reply; | |
278 | if (config.dbnum == 0) return REDIS_OK; | |
279 | ||
280 | reply = redisCommand(context,"SELECT %d",config.dbnum); | |
281 | if (reply != NULL) { | |
282 | freeReplyObject(reply); | |
283 | return REDIS_OK; | |
284 | } | |
285 | return REDIS_ERR; | |
286 | } | |
287 | ||
288 | /* Connect to the client. If force is not zero the connection is performed | |
289 | * even if there is already a connected socket. */ | |
290 | static int cliConnect(int force) { | |
291 | if (context == NULL || force) { | |
292 | if (context != NULL) | |
293 | redisFree(context); | |
294 | ||
295 | if (config.hostsocket == NULL) { | |
296 | context = redisConnect(config.hostip,config.hostport); | |
297 | } else { | |
298 | context = redisConnectUnix(config.hostsocket); | |
299 | } | |
300 | ||
301 | if (context->err) { | |
302 | fprintf(stderr,"Could not connect to Redis at "); | |
303 | if (config.hostsocket == NULL) | |
304 | fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr); | |
305 | else | |
306 | fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr); | |
307 | redisFree(context); | |
308 | context = NULL; | |
309 | return REDIS_ERR; | |
310 | } | |
311 | ||
312 | /* Do AUTH and select the right DB. */ | |
313 | if (cliAuth() != REDIS_OK) | |
314 | return REDIS_ERR; | |
315 | if (cliSelect() != REDIS_OK) | |
316 | return REDIS_ERR; | |
317 | } | |
318 | return REDIS_OK; | |
319 | } | |
320 | ||
321 | static void cliPrintContextError() { | |
322 | if (context == NULL) return; | |
323 | fprintf(stderr,"Error: %s\n",context->errstr); | |
324 | } | |
325 | ||
326 | static sds cliFormatReplyTTY(redisReply *r, char *prefix) { | |
327 | sds out = sdsempty(); | |
328 | switch (r->type) { | |
329 | case REDIS_REPLY_ERROR: | |
330 | out = sdscatprintf(out,"(error) %s\n", r->str); | |
331 | break; | |
332 | case REDIS_REPLY_STATUS: | |
333 | out = sdscat(out,r->str); | |
334 | out = sdscat(out,"\n"); | |
335 | break; | |
336 | case REDIS_REPLY_INTEGER: | |
337 | out = sdscatprintf(out,"(integer) %lld\n",r->integer); | |
338 | break; | |
339 | case REDIS_REPLY_STRING: | |
340 | /* If you are producing output for the standard output we want | |
341 | * a more interesting output with quoted characters and so forth */ | |
342 | out = sdscatrepr(out,r->str,r->len); | |
343 | out = sdscat(out,"\n"); | |
344 | break; | |
345 | case REDIS_REPLY_NIL: | |
346 | out = sdscat(out,"(nil)\n"); | |
347 | break; | |
348 | case REDIS_REPLY_ARRAY: | |
349 | if (r->elements == 0) { | |
350 | out = sdscat(out,"(empty list or set)\n"); | |
351 | } else { | |
352 | unsigned int i, idxlen = 0; | |
353 | char _prefixlen[16]; | |
354 | char _prefixfmt[16]; | |
355 | sds _prefix; | |
356 | sds tmp; | |
357 | ||
358 | /* Calculate chars needed to represent the largest index */ | |
359 | i = r->elements; | |
360 | do { | |
361 | idxlen++; | |
362 | i /= 10; | |
363 | } while(i); | |
364 | ||
365 | /* Prefix for nested multi bulks should grow with idxlen+2 spaces */ | |
366 | memset(_prefixlen,' ',idxlen+2); | |
367 | _prefixlen[idxlen+2] = '\0'; | |
368 | _prefix = sdscat(sdsnew(prefix),_prefixlen); | |
369 | ||
370 | /* Setup prefix format for every entry */ | |
371 | snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen); | |
372 | ||
373 | for (i = 0; i < r->elements; i++) { | |
374 | /* Don't use the prefix for the first element, as the parent | |
375 | * caller already prepended the index number. */ | |
376 | out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1); | |
377 | ||
378 | /* Format the multi bulk entry */ | |
379 | tmp = cliFormatReplyTTY(r->element[i],_prefix); | |
380 | out = sdscatlen(out,tmp,sdslen(tmp)); | |
381 | sdsfree(tmp); | |
382 | } | |
383 | sdsfree(_prefix); | |
384 | } | |
385 | break; | |
386 | default: | |
387 | fprintf(stderr,"Unknown reply type: %d\n", r->type); | |
388 | exit(1); | |
389 | } | |
390 | return out; | |
391 | } | |
392 | ||
393 | static sds cliFormatReplyRaw(redisReply *r) { | |
394 | sds out = sdsempty(), tmp; | |
395 | size_t i; | |
396 | ||
397 | switch (r->type) { | |
398 | case REDIS_REPLY_NIL: | |
399 | /* Nothing... */ | |
400 | break; | |
401 | case REDIS_REPLY_ERROR: | |
402 | out = sdscatlen(out,r->str,r->len); | |
403 | out = sdscatlen(out,"\n",1); | |
404 | break; | |
405 | case REDIS_REPLY_STATUS: | |
406 | case REDIS_REPLY_STRING: | |
407 | out = sdscatlen(out,r->str,r->len); | |
408 | break; | |
409 | case REDIS_REPLY_INTEGER: | |
410 | out = sdscatprintf(out,"%lld",r->integer); | |
411 | break; | |
412 | case REDIS_REPLY_ARRAY: | |
413 | for (i = 0; i < r->elements; i++) { | |
414 | if (i > 0) out = sdscat(out,config.mb_delim); | |
415 | tmp = cliFormatReplyRaw(r->element[i]); | |
416 | out = sdscatlen(out,tmp,sdslen(tmp)); | |
417 | sdsfree(tmp); | |
418 | } | |
419 | break; | |
420 | default: | |
421 | fprintf(stderr,"Unknown reply type: %d\n", r->type); | |
422 | exit(1); | |
423 | } | |
424 | return out; | |
425 | } | |
426 | ||
427 | static int cliReadReply(int output_raw_strings) { | |
428 | void *_reply; | |
429 | redisReply *reply; | |
430 | sds out; | |
431 | ||
432 | if (redisGetReply(context,&_reply) != REDIS_OK) { | |
433 | if (config.shutdown) | |
434 | return REDIS_OK; | |
435 | if (config.interactive) { | |
436 | /* Filter cases where we should reconnect */ | |
437 | if (context->err == REDIS_ERR_IO && errno == ECONNRESET) | |
438 | return REDIS_ERR; | |
439 | if (context->err == REDIS_ERR_EOF) | |
440 | return REDIS_ERR; | |
441 | } | |
442 | cliPrintContextError(); | |
443 | exit(1); | |
444 | return REDIS_ERR; /* avoid compiler warning */ | |
445 | } | |
446 | ||
447 | reply = (redisReply*)_reply; | |
448 | if (output_raw_strings) { | |
449 | out = cliFormatReplyRaw(reply); | |
450 | } else { | |
451 | if (config.raw_output) { | |
452 | out = cliFormatReplyRaw(reply); | |
453 | out = sdscat(out,"\n"); | |
454 | } else { | |
455 | out = cliFormatReplyTTY(reply,""); | |
456 | } | |
457 | } | |
458 | fwrite(out,sdslen(out),1,stdout); | |
459 | sdsfree(out); | |
460 | freeReplyObject(reply); | |
461 | return REDIS_OK; | |
462 | } | |
463 | ||
464 | static int cliSendCommand(int argc, char **argv, int repeat) { | |
465 | char *command = argv[0]; | |
466 | size_t *argvlen; | |
467 | int j, output_raw; | |
468 | ||
469 | if (context == NULL) return REDIS_ERR; | |
470 | ||
471 | output_raw = 0; | |
472 | if (!strcasecmp(command,"info") || | |
473 | (argc == 2 && !strcasecmp(command,"cluster") && | |
474 | (!strcasecmp(argv[1],"nodes") || | |
475 | !strcasecmp(argv[1],"info"))) || | |
476 | (argc == 2 && !strcasecmp(command,"client") && | |
477 | !strcasecmp(argv[1],"list"))) | |
478 | ||
479 | { | |
480 | output_raw = 1; | |
481 | } | |
482 | ||
483 | if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) { | |
484 | cliOutputHelp(--argc, ++argv); | |
485 | return REDIS_OK; | |
486 | } | |
487 | if (!strcasecmp(command,"shutdown")) config.shutdown = 1; | |
488 | if (!strcasecmp(command,"monitor")) config.monitor_mode = 1; | |
489 | if (!strcasecmp(command,"subscribe") || | |
490 | !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1; | |
491 | ||
492 | /* Setup argument length */ | |
493 | argvlen = malloc(argc*sizeof(size_t)); | |
494 | for (j = 0; j < argc; j++) | |
495 | argvlen[j] = sdslen(argv[j]); | |
496 | ||
497 | while(repeat--) { | |
498 | redisAppendCommandArgv(context,argc,(const char**)argv,argvlen); | |
499 | while (config.monitor_mode) { | |
500 | if (cliReadReply(output_raw) != REDIS_OK) exit(1); | |
501 | fflush(stdout); | |
502 | } | |
503 | ||
504 | if (config.pubsub_mode) { | |
505 | if (!config.raw_output) | |
506 | printf("Reading messages... (press Ctrl-C to quit)\n"); | |
507 | while (1) { | |
508 | if (cliReadReply(output_raw) != REDIS_OK) exit(1); | |
509 | } | |
510 | } | |
511 | ||
512 | if (cliReadReply(output_raw) != REDIS_OK) { | |
513 | free(argvlen); | |
514 | return REDIS_ERR; | |
515 | } else { | |
516 | /* Store database number when SELECT was successfully executed. */ | |
517 | if (!strcasecmp(command,"select") && argc == 2) { | |
518 | config.dbnum = atoi(argv[1]); | |
519 | cliRefreshPrompt(); | |
520 | } | |
521 | } | |
522 | if (config.interval) usleep(config.interval); | |
523 | fflush(stdout); /* Make it grep friendly */ | |
524 | } | |
525 | ||
526 | free(argvlen); | |
527 | return REDIS_OK; | |
528 | } | |
529 | ||
530 | /*------------------------------------------------------------------------------ | |
531 | * User interface | |
532 | *--------------------------------------------------------------------------- */ | |
533 | ||
534 | static int parseOptions(int argc, char **argv) { | |
535 | int i; | |
536 | ||
537 | for (i = 1; i < argc; i++) { | |
538 | int lastarg = i==argc-1; | |
539 | ||
540 | if (!strcmp(argv[i],"-h") && !lastarg) { | |
541 | sdsfree(config.hostip); | |
542 | config.hostip = sdsnew(argv[i+1]); | |
543 | i++; | |
544 | } else if (!strcmp(argv[i],"-h") && lastarg) { | |
545 | usage(); | |
546 | } else if (!strcmp(argv[i],"--help")) { | |
547 | usage(); | |
548 | } else if (!strcmp(argv[i],"-x")) { | |
549 | config.stdinarg = 1; | |
550 | } else if (!strcmp(argv[i],"-p") && !lastarg) { | |
551 | config.hostport = atoi(argv[i+1]); | |
552 | i++; | |
553 | } else if (!strcmp(argv[i],"-s") && !lastarg) { | |
554 | config.hostsocket = argv[i+1]; | |
555 | i++; | |
556 | } else if (!strcmp(argv[i],"-r") && !lastarg) { | |
557 | config.repeat = strtoll(argv[i+1],NULL,10); | |
558 | i++; | |
559 | } else if (!strcmp(argv[i],"-i") && !lastarg) { | |
560 | double seconds = atof(argv[i+1]); | |
561 | config.interval = seconds*1000000; | |
562 | i++; | |
563 | } else if (!strcmp(argv[i],"-n") && !lastarg) { | |
564 | config.dbnum = atoi(argv[i+1]); | |
565 | i++; | |
566 | } else if (!strcmp(argv[i],"-a") && !lastarg) { | |
567 | config.auth = argv[i+1]; | |
568 | i++; | |
569 | } else if (!strcmp(argv[i],"--raw")) { | |
570 | config.raw_output = 1; | |
571 | } else if (!strcmp(argv[i],"--latency")) { | |
572 | config.latency_mode = 1; | |
573 | } else if (!strcmp(argv[i],"-d") && !lastarg) { | |
574 | sdsfree(config.mb_delim); | |
575 | config.mb_delim = sdsnew(argv[i+1]); | |
576 | i++; | |
577 | } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) { | |
578 | sds version = cliVersion(); | |
579 | printf("redis-cli %s\n", version); | |
580 | sdsfree(version); | |
581 | exit(0); | |
582 | } else { | |
583 | break; | |
584 | } | |
585 | } | |
586 | return i; | |
587 | } | |
588 | ||
589 | static sds readArgFromStdin(void) { | |
590 | char buf[1024]; | |
591 | sds arg = sdsempty(); | |
592 | ||
593 | while(1) { | |
594 | int nread = read(fileno(stdin),buf,1024); | |
595 | ||
596 | if (nread == 0) break; | |
597 | else if (nread == -1) { | |
598 | perror("Reading from standard input"); | |
599 | exit(1); | |
600 | } | |
601 | arg = sdscatlen(arg,buf,nread); | |
602 | } | |
603 | return arg; | |
604 | } | |
605 | ||
606 | static void usage() { | |
607 | sds version = cliVersion(); | |
608 | fprintf(stderr, | |
609 | "redis-cli %s\n" | |
610 | "\n" | |
611 | "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n" | |
612 | " -h <hostname> Server hostname (default: 127.0.0.1)\n" | |
613 | " -p <port> Server port (default: 6379)\n" | |
614 | " -s <socket> Server socket (overrides hostname and port)\n" | |
615 | " -a <password> Password to use when connecting to the server\n" | |
616 | " -r <repeat> Execute specified command N times\n" | |
617 | " -i <interval> When -r is used, waits <interval> seconds per command.\n" | |
618 | " It is possible to specify sub-second times like -i 0.1.\n" | |
619 | " -n <db> Database number\n" | |
620 | " -x Read last argument from STDIN\n" | |
621 | " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n)\n" | |
622 | " --raw Use raw formatting for replies (default when STDOUT is not a tty)\n" | |
623 | " --latency Enter a special mode continuously sampling latency.\n" | |
624 | " --help Output this help and exit\n" | |
625 | " --version Output version and exit\n" | |
626 | "\n" | |
627 | "Examples:\n" | |
628 | " cat /etc/passwd | redis-cli -x set mypasswd\n" | |
629 | " redis-cli get mypasswd\n" | |
630 | " redis-cli -r 100 lpush mylist x\n" | |
631 | " redis-cli -r 100 -i 1 info | grep used_memory_human:\n" | |
632 | "\n" | |
633 | "When no command is given, redis-cli starts in interactive mode.\n" | |
634 | "Type \"help\" in interactive mode for information on available commands.\n" | |
635 | "\n", | |
636 | version); | |
637 | sdsfree(version); | |
638 | exit(1); | |
639 | } | |
640 | ||
641 | /* Turn the plain C strings into Sds strings */ | |
642 | static char **convertToSds(int count, char** args) { | |
643 | int j; | |
644 | char **sds = zmalloc(sizeof(char*)*count); | |
645 | ||
646 | for(j = 0; j < count; j++) | |
647 | sds[j] = sdsnew(args[j]); | |
648 | ||
649 | return sds; | |
650 | } | |
651 | ||
652 | #define LINE_BUFLEN 4096 | |
653 | static void repl() { | |
654 | sds historyfile = NULL; | |
655 | int history = 0; | |
656 | char *line; | |
657 | int argc; | |
658 | sds *argv; | |
659 | ||
660 | config.interactive = 1; | |
661 | linenoiseSetCompletionCallback(completionCallback); | |
662 | ||
663 | /* Only use history when stdin is a tty. */ | |
664 | if (isatty(fileno(stdin))) { | |
665 | history = 1; | |
666 | ||
667 | if (getenv("HOME") != NULL) { | |
668 | historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME")); | |
669 | linenoiseHistoryLoad(historyfile); | |
670 | } | |
671 | } | |
672 | ||
673 | cliRefreshPrompt(); | |
674 | while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { | |
675 | if (line[0] != '\0') { | |
676 | argv = sdssplitargs(line,&argc); | |
677 | if (history) linenoiseHistoryAdd(line); | |
678 | if (historyfile) linenoiseHistorySave(historyfile); | |
679 | ||
680 | if (argv == NULL) { | |
681 | printf("Invalid argument(s)\n"); | |
682 | continue; | |
683 | } else if (argc > 0) { | |
684 | if (strcasecmp(argv[0],"quit") == 0 || | |
685 | strcasecmp(argv[0],"exit") == 0) | |
686 | { | |
687 | exit(0); | |
688 | } else if (argc == 3 && !strcasecmp(argv[0],"connect")) { | |
689 | sdsfree(config.hostip); | |
690 | config.hostip = sdsnew(argv[1]); | |
691 | config.hostport = atoi(argv[2]); | |
692 | cliConnect(1); | |
693 | } else if (argc == 1 && !strcasecmp(argv[0],"clear")) { | |
694 | linenoiseClearScreen(); | |
695 | } else { | |
696 | long long start_time = mstime(), elapsed; | |
697 | int repeat, skipargs = 0; | |
698 | ||
699 | repeat = atoi(argv[0]); | |
700 | if (argc > 1 && repeat) { | |
701 | skipargs = 1; | |
702 | } else { | |
703 | repeat = 1; | |
704 | } | |
705 | ||
706 | if (cliSendCommand(argc-skipargs,argv+skipargs,repeat) | |
707 | != REDIS_OK) | |
708 | { | |
709 | cliConnect(1); | |
710 | ||
711 | /* If we still cannot send the command print error. | |
712 | * We'll try to reconnect the next time. */ | |
713 | if (cliSendCommand(argc-skipargs,argv+skipargs,repeat) | |
714 | != REDIS_OK) | |
715 | cliPrintContextError(); | |
716 | } | |
717 | elapsed = mstime()-start_time; | |
718 | if (elapsed >= 500) { | |
719 | printf("(%.2fs)\n",(double)elapsed/1000); | |
720 | } | |
721 | } | |
722 | } | |
723 | /* Free the argument vector */ | |
724 | while(argc--) sdsfree(argv[argc]); | |
725 | zfree(argv); | |
726 | } | |
727 | /* linenoise() returns malloc-ed lines like readline() */ | |
728 | free(line); | |
729 | } | |
730 | exit(0); | |
731 | } | |
732 | ||
733 | static int noninteractive(int argc, char **argv) { | |
734 | int retval = 0; | |
735 | if (config.stdinarg) { | |
736 | argv = zrealloc(argv, (argc+1)*sizeof(char*)); | |
737 | argv[argc] = readArgFromStdin(); | |
738 | retval = cliSendCommand(argc+1, argv, config.repeat); | |
739 | } else { | |
740 | /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */ | |
741 | retval = cliSendCommand(argc, argv, config.repeat); | |
742 | } | |
743 | return retval; | |
744 | } | |
745 | ||
746 | static void latencyMode(void) { | |
747 | redisReply *reply; | |
748 | long long start, latency, min, max, tot, count = 0; | |
749 | double avg; | |
750 | ||
751 | if (!context) exit(1); | |
752 | while(1) { | |
753 | start = mstime(); | |
754 | reply = redisCommand(context,"PING"); | |
755 | if (reply == NULL) { | |
756 | fprintf(stderr,"\nI/O error\n"); | |
757 | exit(1); | |
758 | } | |
759 | latency = mstime()-start; | |
760 | freeReplyObject(reply); | |
761 | count++; | |
762 | if (count == 1) { | |
763 | min = max = tot = latency; | |
764 | avg = (double) latency; | |
765 | } else { | |
766 | if (latency < min) min = latency; | |
767 | if (latency > max) max = latency; | |
768 | tot += latency; | |
769 | avg = (double) tot/count; | |
770 | } | |
771 | printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)", | |
772 | min, max, avg, count); | |
773 | fflush(stdout); | |
774 | usleep(10000); | |
775 | } | |
776 | } | |
777 | ||
778 | int main(int argc, char **argv) { | |
779 | int firstarg; | |
780 | ||
781 | config.hostip = sdsnew("127.0.0.1"); | |
782 | config.hostport = 6379; | |
783 | config.hostsocket = NULL; | |
784 | config.repeat = 1; | |
785 | config.interval = 0; | |
786 | config.dbnum = 0; | |
787 | config.interactive = 0; | |
788 | config.shutdown = 0; | |
789 | config.monitor_mode = 0; | |
790 | config.pubsub_mode = 0; | |
791 | config.latency_mode = 0; | |
792 | config.stdinarg = 0; | |
793 | config.auth = NULL; | |
794 | config.raw_output = !isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL); | |
795 | config.mb_delim = sdsnew("\n"); | |
796 | cliInitHelp(); | |
797 | ||
798 | firstarg = parseOptions(argc,argv); | |
799 | argc -= firstarg; | |
800 | argv += firstarg; | |
801 | ||
802 | /* Start in latency mode if appropriate */ | |
803 | if (config.latency_mode) { | |
804 | cliConnect(0); | |
805 | latencyMode(); | |
806 | } | |
807 | ||
808 | /* Start interactive mode when no command is provided */ | |
809 | if (argc == 0) { | |
810 | /* Note that in repl mode we don't abort on connection error. | |
811 | * A new attempt will be performed for every command send. */ | |
812 | cliConnect(0); | |
813 | repl(); | |
814 | } | |
815 | ||
816 | /* Otherwise, we have some arguments to execute */ | |
817 | if (cliConnect(0) != REDIS_OK) exit(1); | |
818 | return noninteractive(argc,convertToSds(argc,argv)); | |
819 | } |