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