1 /* Redis CLI (command line interface) 2 * 3 * Copyright (c) 2009-2012, 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 <signal.h> 38 #include <unistd.h> 39 #include <time.h> 40 #include <ctype.h> 41 #include <errno.h> 42 #include <sys/stat.h> 43 #include <sys/time.h> 44 #include <assert.h> 45 #include <fcntl.h> 46 #include <limits.h> 47 48 #include "hiredis.h" 49 #include "sds.h" 50 #include "zmalloc.h" 51 #include "linenoise.h" 52 #include "help.h" 53 #include "anet.h" 54 #include "ae.h" 55 56 #define REDIS_NOTUSED(V) ((void) V) 57 58 #define OUTPUT_STANDARD 0 59 #define OUTPUT_RAW 1 60 #define OUTPUT_CSV 2 61 #define REDIS_CLI_KEEPALIVE_INTERVAL 15 /* seconds */ 62 #define REDIS_CLI_DEFAULT_PIPE_TIMEOUT 30 /* seconds */ 63 #define REDIS_CLI_HISTFILE_ENV "REDISCLI_HISTFILE" 64 #define REDIS_CLI_HISTFILE_DEFAULT ".rediscli_history" 65 66 static redisContext *context; 67 static struct config { 68 char *hostip; 69 int hostport; 70 char *hostsocket; 71 long repeat; 72 long interval; 73 int dbnum; 74 int interactive; 75 int shutdown; 76 int monitor_mode; 77 int pubsub_mode; 78 int latency_mode; 79 int latency_history; 80 int cluster_mode; 81 int cluster_reissue_command; 82 int slave_mode; 83 int pipe_mode; 84 int pipe_timeout; 85 int getrdb_mode; 86 int stat_mode; 87 int scan_mode; 88 int intrinsic_latency_mode; 89 int intrinsic_latency_duration; 90 char *pattern; 91 char *rdb_filename; 92 int bigkeys; 93 int stdinarg; /* get last arg from stdin. (-x option) */ 94 char *auth; 95 int output; /* output mode, see OUTPUT_* defines */ 96 sds mb_delim; 97 char prompt[128]; 98 char *eval; 99 int last_cmd_type; 100 } config; 101 102 static volatile sig_atomic_t force_cancel_loop = 0; 103 static void usage(void); 104 static void slaveMode(void); 105 char *redisGitSHA1(void); 106 char *redisGitDirty(void); 107 108 /*------------------------------------------------------------------------------ 109 * Utility functions 110 *--------------------------------------------------------------------------- */ 111 112 static long long ustime(void) { 113 struct timeval tv; 114 long long ust; 115 116 gettimeofday(&tv, NULL); 117 ust = ((long long)tv.tv_sec)*1000000; 118 ust += tv.tv_usec; 119 return ust; 120 } 121 122 static long long mstime(void) { 123 return ustime()/1000; 124 } 125 126 static void cliRefreshPrompt(void) { 127 int len; 128 129 if (config.hostsocket != NULL) 130 len = snprintf(config.prompt,sizeof(config.prompt),"redis %s", 131 config.hostsocket); 132 else 133 len = anetFormatAddr(config.prompt, sizeof(config.prompt), 134 config.hostip, config.hostport); 135 /* Add [dbnum] if needed */ 136 if (config.dbnum != 0 && config.last_cmd_type != REDIS_REPLY_ERROR) 137 len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]", 138 config.dbnum); 139 snprintf(config.prompt+len,sizeof(config.prompt)-len,"> "); 140 } 141 142 static sds getHistoryPath() { 143 char *path = NULL; 144 sds historyPath = NULL; 145 146 /* check the env for a histfile override */ 147 path = getenv(REDIS_CLI_HISTFILE_ENV); 148 if (path != NULL && *path != '\0') { 149 if (!strcmp("/dev/null", path)) { 150 return NULL; 151 } 152 153 /* if the env is set, return it */ 154 historyPath = sdscatprintf(sdsempty(), "%s", path); 155 } else { 156 char *home = getenv("HOME"); 157 if (home != NULL && *home != '\0') { 158 /* otherwise, return the default */ 159 historyPath = sdscatprintf(sdsempty(), "%s/%s", home, REDIS_CLI_HISTFILE_DEFAULT); 160 } 161 } 162 163 return historyPath; 164 } 165 166 /*------------------------------------------------------------------------------ 167 * Help functions 168 *--------------------------------------------------------------------------- */ 169 170 #define CLI_HELP_COMMAND 1 171 #define CLI_HELP_GROUP 2 172 173 typedef struct { 174 int type; 175 int argc; 176 sds *argv; 177 sds full; 178 179 /* Only used for help on commands */ 180 struct commandHelp *org; 181 } helpEntry; 182 183 static helpEntry *helpEntries; 184 static int helpEntriesLen; 185 186 static sds cliVersion(void) { 187 sds version; 188 version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION); 189 190 /* Add git commit and working tree status when available */ 191 if (strtoll(redisGitSHA1(),NULL,16)) { 192 version = sdscatprintf(version, " (git:%s", redisGitSHA1()); 193 if (strtoll(redisGitDirty(),NULL,10)) 194 version = sdscatprintf(version, "-dirty"); 195 version = sdscat(version, ")"); 196 } 197 return version; 198 } 199 200 static void cliInitHelp(void) { 201 int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp); 202 int groupslen = sizeof(commandGroups)/sizeof(char*); 203 int i, len, pos = 0; 204 helpEntry tmp; 205 206 helpEntriesLen = len = commandslen+groupslen; 207 helpEntries = malloc(sizeof(helpEntry)*len); 208 209 for (i = 0; i < groupslen; i++) { 210 tmp.argc = 1; 211 tmp.argv = malloc(sizeof(sds)); 212 tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]); 213 tmp.full = tmp.argv[0]; 214 tmp.type = CLI_HELP_GROUP; 215 tmp.org = NULL; 216 helpEntries[pos++] = tmp; 217 } 218 219 for (i = 0; i < commandslen; i++) { 220 tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc); 221 tmp.full = sdsnew(commandHelp[i].name); 222 tmp.type = CLI_HELP_COMMAND; 223 tmp.org = &commandHelp[i]; 224 helpEntries[pos++] = tmp; 225 } 226 } 227 228 /* Output command help to stdout. */ 229 static void cliOutputCommandHelp(struct commandHelp *help, int group) { 230 printf("\r\n \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params); 231 printf(" \x1b[33msummary:\x1b[0m %s\r\n", help->summary); 232 printf(" \x1b[33msince:\x1b[0m %s\r\n", help->since); 233 if (group) { 234 printf(" \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]); 235 } 236 } 237 238 /* Print generic help. */ 239 static void cliOutputGenericHelp(void) { 240 sds version = cliVersion(); 241 printf( 242 "redis-cli %s\r\n" 243 "Type: \"help @<group>\" to get a list of commands in <group>\r\n" 244 " \"help <command>\" for help on <command>\r\n" 245 " \"help <tab>\" to get a list of possible help topics\r\n" 246 " \"quit\" to exit\r\n", 247 version 248 ); 249 sdsfree(version); 250 } 251 252 /* Output all command help, filtering by group or command name. */ 253 static void cliOutputHelp(int argc, char **argv) { 254 int i, j, len; 255 int group = -1; 256 helpEntry *entry; 257 struct commandHelp *help; 258 259 if (argc == 0) { 260 cliOutputGenericHelp(); 261 return; 262 } else if (argc > 0 && argv[0][0] == '@') { 263 len = sizeof(commandGroups)/sizeof(char*); 264 for (i = 0; i < len; i++) { 265 if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) { 266 group = i; 267 break; 268 } 269 } 270 } 271 272 assert(argc > 0); 273 for (i = 0; i < helpEntriesLen; i++) { 274 entry = &helpEntries[i]; 275 if (entry->type != CLI_HELP_COMMAND) continue; 276 277 help = entry->org; 278 if (group == -1) { 279 /* Compare all arguments */ 280 if (argc == entry->argc) { 281 for (j = 0; j < argc; j++) { 282 if (strcasecmp(argv[j],entry->argv[j]) != 0) break; 283 } 284 if (j == argc) { 285 cliOutputCommandHelp(help,1); 286 } 287 } 288 } else { 289 if (group == help->group) { 290 cliOutputCommandHelp(help,0); 291 } 292 } 293 } 294 printf("\r\n"); 295 } 296 297 static void completionCallback(const char *buf, linenoiseCompletions *lc) { 298 size_t startpos = 0; 299 int mask; 300 int i; 301 size_t matchlen; 302 sds tmp; 303 304 if (strncasecmp(buf,"help ",5) == 0) { 305 startpos = 5; 306 while (isspace(buf[startpos])) startpos++; 307 mask = CLI_HELP_COMMAND | CLI_HELP_GROUP; 308 } else { 309 mask = CLI_HELP_COMMAND; 310 } 311 312 for (i = 0; i < helpEntriesLen; i++) { 313 if (!(helpEntries[i].type & mask)) continue; 314 315 matchlen = strlen(buf+startpos); 316 if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) { 317 tmp = sdsnewlen(buf,startpos); 318 tmp = sdscat(tmp,helpEntries[i].full); 319 linenoiseAddCompletion(lc,tmp); 320 sdsfree(tmp); 321 } 322 } 323 } 324 325 /*------------------------------------------------------------------------------ 326 * Networking / parsing 327 *--------------------------------------------------------------------------- */ 328 329 /* Send AUTH command to the server */ 330 static int cliAuth(void) { 331 redisReply *reply; 332 if (config.auth == NULL) return REDIS_OK; 333 334 reply = redisCommand(context,"AUTH %s",config.auth); 335 if (reply != NULL) { 336 freeReplyObject(reply); 337 return REDIS_OK; 338 } 339 return REDIS_ERR; 340 } 341 342 /* Send SELECT dbnum to the server */ 343 static int cliSelect(void) { 344 redisReply *reply; 345 if (config.dbnum == 0) return REDIS_OK; 346 347 reply = redisCommand(context,"SELECT %d",config.dbnum); 348 if (reply != NULL) { 349 int result = REDIS_OK; 350 if (reply->type == REDIS_REPLY_ERROR) result = REDIS_ERR; 351 freeReplyObject(reply); 352 return result; 353 } 354 return REDIS_ERR; 355 } 356 357 /* Connect to the server. If force is not zero the connection is performed 358 * even if there is already a connected socket. */ 359 static int cliConnect(int force) { 360 if (context == NULL || force) { 361 if (context != NULL) 362 redisFree(context); 363 364 if (config.hostsocket == NULL) { 365 context = redisConnect(config.hostip,config.hostport); 366 } else { 367 context = redisConnectUnix(config.hostsocket); 368 } 369 370 if (context->err) { 371 fprintf(stderr,"Could not connect to Redis at "); 372 if (config.hostsocket == NULL) 373 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr); 374 else 375 fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr); 376 redisFree(context); 377 context = NULL; 378 return REDIS_ERR; 379 } 380 381 /* Set aggressive KEEP_ALIVE socket option in the Redis context socket 382 * in order to prevent timeouts caused by the execution of long 383 * commands. At the same time this improves the detection of real 384 * errors. */ 385 anetKeepAlive(NULL, context->fd, REDIS_CLI_KEEPALIVE_INTERVAL); 386 387 /* Do AUTH and select the right DB. */ 388 if (cliAuth() != REDIS_OK) 389 return REDIS_ERR; 390 if (cliSelect() != REDIS_OK) 391 return REDIS_ERR; 392 } 393 return REDIS_OK; 394 } 395 396 static void cliPrintContextError(void) { 397 if (context == NULL) return; 398 fprintf(stderr,"Error: %s\n",context->errstr); 399 } 400 401 static sds cliFormatReplyTTY(redisReply *r, char *prefix) { 402 sds out = sdsempty(); 403 switch (r->type) { 404 case REDIS_REPLY_ERROR: 405 out = sdscatprintf(out,"(error) %s\n", r->str); 406 break; 407 case REDIS_REPLY_STATUS: 408 out = sdscat(out,r->str); 409 out = sdscat(out,"\n"); 410 break; 411 case REDIS_REPLY_INTEGER: 412 out = sdscatprintf(out,"(integer) %lld\n",r->integer); 413 break; 414 case REDIS_REPLY_STRING: 415 /* If you are producing output for the standard output we want 416 * a more interesting output with quoted characters and so forth */ 417 out = sdscatrepr(out,r->str,r->len); 418 out = sdscat(out,"\n"); 419 break; 420 case REDIS_REPLY_NIL: 421 out = sdscat(out,"(nil)\n"); 422 break; 423 case REDIS_REPLY_ARRAY: 424 if (r->elements == 0) { 425 out = sdscat(out,"(empty list or set)\n"); 426 } else { 427 unsigned int i, idxlen = 0; 428 char _prefixlen[16]; 429 char _prefixfmt[16]; 430 sds _prefix; 431 sds tmp; 432 433 /* Calculate chars needed to represent the largest index */ 434 i = r->elements; 435 do { 436 idxlen++; 437 i /= 10; 438 } while(i); 439 440 /* Prefix for nested multi bulks should grow with idxlen+2 spaces */ 441 memset(_prefixlen,' ',idxlen+2); 442 _prefixlen[idxlen+2] = '\0'; 443 _prefix = sdscat(sdsnew(prefix),_prefixlen); 444 445 /* Setup prefix format for every entry */ 446 snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen); 447 448 for (i = 0; i < r->elements; i++) { 449 /* Don't use the prefix for the first element, as the parent 450 * caller already prepended the index number. */ 451 out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1); 452 453 /* Format the multi bulk entry */ 454 tmp = cliFormatReplyTTY(r->element[i],_prefix); 455 out = sdscatlen(out,tmp,sdslen(tmp)); 456 sdsfree(tmp); 457 } 458 sdsfree(_prefix); 459 } 460 break; 461 default: 462 fprintf(stderr,"Unknown reply type: %d\n", r->type); 463 exit(1); 464 } 465 return out; 466 } 467 468 static sds cliFormatReplyRaw(redisReply *r) { 469 sds out = sdsempty(), tmp; 470 size_t i; 471 472 switch (r->type) { 473 case REDIS_REPLY_NIL: 474 /* Nothing... */ 475 break; 476 case REDIS_REPLY_ERROR: 477 out = sdscatlen(out,r->str,r->len); 478 out = sdscatlen(out,"\n",1); 479 break; 480 case REDIS_REPLY_STATUS: 481 case REDIS_REPLY_STRING: 482 out = sdscatlen(out,r->str,r->len); 483 break; 484 case REDIS_REPLY_INTEGER: 485 out = sdscatprintf(out,"%lld",r->integer); 486 break; 487 case REDIS_REPLY_ARRAY: 488 for (i = 0; i < r->elements; i++) { 489 if (i > 0) out = sdscat(out,config.mb_delim); 490 tmp = cliFormatReplyRaw(r->element[i]); 491 out = sdscatlen(out,tmp,sdslen(tmp)); 492 sdsfree(tmp); 493 } 494 break; 495 default: 496 fprintf(stderr,"Unknown reply type: %d\n", r->type); 497 exit(1); 498 } 499 return out; 500 } 501 502 static sds cliFormatReplyCSV(redisReply *r) { 503 unsigned int i; 504 505 sds out = sdsempty(); 506 switch (r->type) { 507 case REDIS_REPLY_ERROR: 508 out = sdscat(out,"ERROR,"); 509 out = sdscatrepr(out,r->str,strlen(r->str)); 510 break; 511 case REDIS_REPLY_STATUS: 512 out = sdscatrepr(out,r->str,r->len); 513 break; 514 case REDIS_REPLY_INTEGER: 515 out = sdscatprintf(out,"%lld",r->integer); 516 break; 517 case REDIS_REPLY_STRING: 518 out = sdscatrepr(out,r->str,r->len); 519 break; 520 case REDIS_REPLY_NIL: 521 out = sdscat(out,"NIL\n"); 522 break; 523 case REDIS_REPLY_ARRAY: 524 for (i = 0; i < r->elements; i++) { 525 sds tmp = cliFormatReplyCSV(r->element[i]); 526 out = sdscatlen(out,tmp,sdslen(tmp)); 527 if (i != r->elements-1) out = sdscat(out,","); 528 sdsfree(tmp); 529 } 530 break; 531 default: 532 fprintf(stderr,"Unknown reply type: %d\n", r->type); 533 exit(1); 534 } 535 return out; 536 } 537 538 static int cliReadReply(int output_raw_strings) { 539 void *_reply; 540 redisReply *reply; 541 sds out = NULL; 542 int output = 1; 543 544 if (redisGetReply(context,&_reply) != REDIS_OK) { 545 if (config.shutdown) { 546 redisFree(context); 547 context = NULL; 548 return REDIS_OK; 549 } 550 if (config.interactive) { 551 /* Filter cases where we should reconnect */ 552 if (context->err == REDIS_ERR_IO && 553 (errno == ECONNRESET || errno == EPIPE)) 554 return REDIS_ERR; 555 if (context->err == REDIS_ERR_EOF) 556 return REDIS_ERR; 557 } 558 cliPrintContextError(); 559 exit(1); 560 return REDIS_ERR; /* avoid compiler warning */ 561 } 562 563 reply = (redisReply*)_reply; 564 565 config.last_cmd_type = reply->type; 566 567 /* Check if we need to connect to a different node and reissue the 568 * request. */ 569 if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR && 570 (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK"))) 571 { 572 char *p = reply->str, *s; 573 int slot; 574 575 output = 0; 576 /* Comments show the position of the pointer as: 577 * 578 * [S] for pointer 's' 579 * [P] for pointer 'p' 580 */ 581 s = strchr(p,' '); /* MOVED[S]3999 127.0.0.1:6381 */ 582 p = strchr(s+1,' '); /* MOVED[S]3999[P]127.0.0.1:6381 */ 583 *p = '\0'; 584 slot = atoi(s+1); 585 s = strchr(p+1,':'); /* MOVED 3999[P]127.0.0.1[S]6381 */ 586 *s = '\0'; 587 sdsfree(config.hostip); 588 config.hostip = sdsnew(p+1); 589 config.hostport = atoi(s+1); 590 if (config.interactive) 591 printf("-> Redirected to slot [%d] located at %s:%d\n", 592 slot, config.hostip, config.hostport); 593 config.cluster_reissue_command = 1; 594 cliRefreshPrompt(); 595 } 596 597 if (output) { 598 if (output_raw_strings) { 599 out = cliFormatReplyRaw(reply); 600 } else { 601 if (config.output == OUTPUT_RAW) { 602 out = cliFormatReplyRaw(reply); 603 out = sdscat(out,"\n"); 604 } else if (config.output == OUTPUT_STANDARD) { 605 out = cliFormatReplyTTY(reply,""); 606 } else if (config.output == OUTPUT_CSV) { 607 out = cliFormatReplyCSV(reply); 608 out = sdscat(out,"\n"); 609 } 610 } 611 fwrite(out,sdslen(out),1,stdout); 612 sdsfree(out); 613 } 614 freeReplyObject(reply); 615 return REDIS_OK; 616 } 617 618 static int cliSendCommand(int argc, char **argv, int repeat) { 619 char *command = argv[0]; 620 size_t *argvlen; 621 int j, output_raw; 622 623 if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) { 624 cliOutputHelp(--argc, ++argv); 625 return REDIS_OK; 626 } 627 628 if (context == NULL) return REDIS_ERR; 629 630 output_raw = 0; 631 if (!strcasecmp(command,"info") || 632 (argc == 2 && !strcasecmp(command,"cluster") && 633 (!strcasecmp(argv[1],"nodes") || 634 !strcasecmp(argv[1],"info"))) || 635 (argc == 2 && !strcasecmp(command,"client") && 636 !strcasecmp(argv[1],"list")) || 637 (argc == 3 && !strcasecmp(command,"latency") && 638 !strcasecmp(argv[1],"graph")) || 639 (argc == 2 && !strcasecmp(command,"latency") && 640 !strcasecmp(argv[1],"doctor"))) 641 { 642 output_raw = 1; 643 } 644 645 if (!strcasecmp(command,"shutdown")) config.shutdown = 1; 646 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1; 647 if (!strcasecmp(command,"subscribe") || 648 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1; 649 if (!strcasecmp(command,"sync") || 650 !strcasecmp(command,"psync")) config.slave_mode = 1; 651 652 /* Setup argument length */ 653 argvlen = malloc(argc*sizeof(size_t)); 654 for (j = 0; j < argc; j++) 655 argvlen[j] = sdslen(argv[j]); 656 657 while(repeat--) { 658 redisAppendCommandArgv(context,argc,(const char**)argv,argvlen); 659 while (config.monitor_mode) { 660 if (cliReadReply(output_raw) != REDIS_OK) exit(1); 661 fflush(stdout); 662 } 663 664 if (config.pubsub_mode) { 665 if (config.output != OUTPUT_RAW) 666 printf("Reading messages... (press Ctrl-C to quit)\n"); 667 while (1) { 668 if (cliReadReply(output_raw) != REDIS_OK) exit(1); 669 } 670 } 671 672 if (config.slave_mode) { 673 printf("Entering slave output mode... (press Ctrl-C to quit)\n"); 674 slaveMode(); 675 config.slave_mode = 0; 676 free(argvlen); 677 return REDIS_ERR; /* Error = slaveMode lost connection to master */ 678 } 679 680 if (cliReadReply(output_raw) != REDIS_OK) { 681 free(argvlen); 682 return REDIS_ERR; 683 } else { 684 /* Store database number when SELECT was successfully executed. */ 685 if (!strcasecmp(command,"select") && argc == 2) { 686 config.dbnum = atoi(argv[1]); 687 cliRefreshPrompt(); 688 } else if (!strcasecmp(command,"auth") && argc == 2) { 689 cliSelect(); 690 } 691 } 692 if (config.interval) usleep(config.interval); 693 fflush(stdout); /* Make it grep friendly */ 694 } 695 696 free(argvlen); 697 return REDIS_OK; 698 } 699 700 /* Send the INFO command, reconnecting the link if needed. */ 701 static redisReply *reconnectingInfo(void) { 702 redisContext *c = context; 703 redisReply *reply = NULL; 704 int tries = 0; 705 706 assert(!c->err); 707 while(reply == NULL) { 708 while (c->err & (REDIS_ERR_IO | REDIS_ERR_EOF)) { 709 printf("Reconnecting (%d)...\r", ++tries); 710 fflush(stdout); 711 712 redisFree(c); 713 c = redisConnect(config.hostip,config.hostport); 714 usleep(1000000); 715 } 716 717 reply = redisCommand(c,"INFO"); 718 if (c->err && !(c->err & (REDIS_ERR_IO | REDIS_ERR_EOF))) { 719 fprintf(stderr, "Error: %s\n", c->errstr); 720 exit(1); 721 } else if (tries > 0) { 722 printf("\n"); 723 } 724 } 725 726 context = c; 727 return reply; 728 } 729 730 /*------------------------------------------------------------------------------ 731 * User interface 732 *--------------------------------------------------------------------------- */ 733 734 static int parseOptions(int argc, char **argv) { 735 int i; 736 737 for (i = 1; i < argc; i++) { 738 int lastarg = i==argc-1; 739 740 if (!strcmp(argv[i],"-h") && !lastarg) { 741 sdsfree(config.hostip); 742 config.hostip = sdsnew(argv[++i]); 743 } else if (!strcmp(argv[i],"-h") && lastarg) { 744 usage(); 745 } else if (!strcmp(argv[i],"--help")) { 746 usage(); 747 } else if (!strcmp(argv[i],"-x")) { 748 config.stdinarg = 1; 749 } else if (!strcmp(argv[i],"-p") && !lastarg) { 750 config.hostport = atoi(argv[++i]); 751 } else if (!strcmp(argv[i],"-s") && !lastarg) { 752 config.hostsocket = argv[++i]; 753 } else if (!strcmp(argv[i],"-r") && !lastarg) { 754 config.repeat = strtoll(argv[++i],NULL,10); 755 } else if (!strcmp(argv[i],"-i") && !lastarg) { 756 double seconds = atof(argv[++i]); 757 config.interval = seconds*1000000; 758 } else if (!strcmp(argv[i],"-n") && !lastarg) { 759 config.dbnum = atoi(argv[++i]); 760 } else if (!strcmp(argv[i],"-a") && !lastarg) { 761 config.auth = argv[++i]; 762 } else if (!strcmp(argv[i],"--raw")) { 763 config.output = OUTPUT_RAW; 764 } else if (!strcmp(argv[i],"--no-raw")) { 765 config.output = OUTPUT_STANDARD; 766 } else if (!strcmp(argv[i],"--csv")) { 767 config.output = OUTPUT_CSV; 768 } else if (!strcmp(argv[i],"--latency")) { 769 config.latency_mode = 1; 770 } else if (!strcmp(argv[i],"--latency-history")) { 771 config.latency_mode = 1; 772 config.latency_history = 1; 773 } else if (!strcmp(argv[i],"--slave")) { 774 config.slave_mode = 1; 775 } else if (!strcmp(argv[i],"--stat")) { 776 config.stat_mode = 1; 777 } else if (!strcmp(argv[i],"--scan")) { 778 config.scan_mode = 1; 779 } else if (!strcmp(argv[i],"--pattern") && !lastarg) { 780 config.pattern = argv[++i]; 781 } else if (!strcmp(argv[i],"--intrinsic-latency") && !lastarg) { 782 config.intrinsic_latency_mode = 1; 783 config.intrinsic_latency_duration = atoi(argv[++i]); 784 } else if (!strcmp(argv[i],"--rdb") && !lastarg) { 785 config.getrdb_mode = 1; 786 config.rdb_filename = argv[++i]; 787 } else if (!strcmp(argv[i],"--pipe")) { 788 config.pipe_mode = 1; 789 } else if (!strcmp(argv[i],"--pipe-timeout") && !lastarg) { 790 config.pipe_timeout = atoi(argv[++i]); 791 } else if (!strcmp(argv[i],"--bigkeys")) { 792 config.bigkeys = 1; 793 } else if (!strcmp(argv[i],"--eval") && !lastarg) { 794 config.eval = argv[++i]; 795 } else if (!strcmp(argv[i],"-c")) { 796 config.cluster_mode = 1; 797 } else if (!strcmp(argv[i],"-d") && !lastarg) { 798 sdsfree(config.mb_delim); 799 config.mb_delim = sdsnew(argv[++i]); 800 } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) { 801 sds version = cliVersion(); 802 printf("redis-cli %s\n", version); 803 sdsfree(version); 804 exit(0); 805 } else { 806 if (argv[i][0] == '-') { 807 fprintf(stderr, 808 "Unrecognized option or bad number of args for: '%s'\n", 809 argv[i]); 810 exit(1); 811 } else { 812 /* Likely the command name, stop here. */ 813 break; 814 } 815 } 816 } 817 return i; 818 } 819 820 static sds readArgFromStdin(void) { 821 char buf[1024]; 822 sds arg = sdsempty(); 823 824 while(1) { 825 int nread = read(fileno(stdin),buf,1024); 826 827 if (nread == 0) break; 828 else if (nread == -1) { 829 perror("Reading from standard input"); 830 exit(1); 831 } 832 arg = sdscatlen(arg,buf,nread); 833 } 834 return arg; 835 } 836 837 static void usage(void) { 838 sds version = cliVersion(); 839 fprintf(stderr, 840 "redis-cli %s\n" 841 "\n" 842 "Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n" 843 " -h <hostname> Server hostname (default: 127.0.0.1).\n" 844 " -p <port> Server port (default: 6379).\n" 845 " -s <socket> Server socket (overrides hostname and port).\n" 846 " -a <password> Password to use when connecting to the server.\n" 847 " -r <repeat> Execute specified command N times.\n" 848 " -i <interval> When -r is used, waits <interval> seconds per command.\n" 849 " It is possible to specify sub-second times like -i 0.1.\n" 850 " -n <db> Database number.\n" 851 " -x Read last argument from STDIN.\n" 852 " -d <delimiter> Multi-bulk delimiter in for raw formatting (default: \\n).\n" 853 " -c Enable cluster mode (follow -ASK and -MOVED redirections).\n" 854 " --raw Use raw formatting for replies (default when STDOUT is\n" 855 " not a tty).\n" 856 " --no-raw Force formatted output even when STDOUT is not a tty.\n" 857 " --csv Output in CSV format.\n" 858 " --stat Print rolling stats about server: mem, clients, ...\n" 859 " --latency Enter a special mode continuously sampling latency.\n" 860 " --latency-history Like --latency but tracking latency changes over time.\n" 861 " Default time interval is 15 sec. Change it using -i.\n" 862 " --slave Simulate a slave showing commands received from the master.\n" 863 " --rdb <filename> Transfer an RDB dump from remote server to local file.\n" 864 " --pipe Transfer raw Redis protocol from stdin to server.\n" 865 " --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.\n" 866 " no reply is received within <n> seconds.\n" 867 " Default timeout: %d. Use 0 to wait forever.\n" 868 " --bigkeys Sample Redis keys looking for big keys.\n" 869 " --scan List all keys using the SCAN command.\n" 870 " --pattern <pat> Useful with --scan to specify a SCAN pattern.\n" 871 " --intrinsic-latency <sec> Run a test to measure intrinsic system latency.\n" 872 " The test will run for the specified amount of seconds.\n" 873 " --eval <file> Send an EVAL command using the Lua script at <file>.\n" 874 " --help Output this help and exit.\n" 875 " --version Output version and exit.\n" 876 "\n" 877 "Examples:\n" 878 " cat /etc/passwd | redis-cli -x set mypasswd\n" 879 " redis-cli get mypasswd\n" 880 " redis-cli -r 100 lpush mylist x\n" 881 " redis-cli -r 100 -i 1 info | grep used_memory_human:\n" 882 " redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n" 883 " redis-cli --scan --pattern '*:12345*'\n" 884 "\n" 885 " (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n" 886 "\n" 887 "When no command is given, redis-cli starts in interactive mode.\n" 888 "Type \"help\" in interactive mode for information on available commands.\n" 889 "\n", 890 version, REDIS_CLI_DEFAULT_PIPE_TIMEOUT); 891 sdsfree(version); 892 exit(1); 893 } 894 895 /* Turn the plain C strings into Sds strings */ 896 static char **convertToSds(int count, char** args) { 897 int j; 898 char **sds = zmalloc(sizeof(char*)*count); 899 900 for(j = 0; j < count; j++) 901 sds[j] = sdsnew(args[j]); 902 903 return sds; 904 } 905 906 static int issueCommandRepeat(int argc, char **argv, long repeat) { 907 while (1) { 908 config.cluster_reissue_command = 0; 909 if (cliSendCommand(argc,argv,repeat) != REDIS_OK) { 910 cliConnect(1); 911 912 /* If we still cannot send the command print error. 913 * We'll try to reconnect the next time. */ 914 if (cliSendCommand(argc,argv,repeat) != REDIS_OK) { 915 cliPrintContextError(); 916 return REDIS_ERR; 917 } 918 } 919 /* Issue the command again if we got redirected in cluster mode */ 920 if (config.cluster_mode && config.cluster_reissue_command) { 921 cliConnect(1); 922 } else { 923 break; 924 } 925 } 926 return REDIS_OK; 927 } 928 929 static int issueCommand(int argc, char **argv) { 930 return issueCommandRepeat(argc, argv, config.repeat); 931 } 932 933 static void repl(void) { 934 sds historyfile = NULL; 935 int history = 0; 936 char *line; 937 int argc; 938 sds *argv; 939 940 config.interactive = 1; 941 linenoiseSetMultiLine(1); 942 linenoiseSetCompletionCallback(completionCallback); 943 944 /* Only use history when stdin is a tty. */ 945 if (isatty(fileno(stdin))) { 946 historyfile = getHistoryPath(); 947 if (historyfile != NULL) { 948 history = 1; 949 linenoiseHistoryLoad(historyfile); 950 } 951 } 952 953 cliRefreshPrompt(); 954 while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) { 955 if (line[0] != '\0') { 956 argv = sdssplitargs(line,&argc); 957 if (history) linenoiseHistoryAdd(line); 958 if (historyfile) linenoiseHistorySave(historyfile); 959 960 if (argv == NULL) { 961 printf("Invalid argument(s)\n"); 962 free(line); 963 continue; 964 } else if (argc > 0) { 965 if (strcasecmp(argv[0],"quit") == 0 || 966 strcasecmp(argv[0],"exit") == 0) 967 { 968 exit(0); 969 } else if (argc == 3 && !strcasecmp(argv[0],"connect")) { 970 sdsfree(config.hostip); 971 config.hostip = sdsnew(argv[1]); 972 config.hostport = atoi(argv[2]); 973 cliRefreshPrompt(); 974 cliConnect(1); 975 } else if (argc == 1 && !strcasecmp(argv[0],"clear")) { 976 linenoiseClearScreen(); 977 } else { 978 long long start_time = mstime(), elapsed; 979 int repeat, skipargs = 0; 980 981 repeat = atoi(argv[0]); 982 if (argc > 1 && repeat) { 983 skipargs = 1; 984 } else { 985 repeat = 1; 986 } 987 988 issueCommandRepeat(argc-skipargs, argv+skipargs, repeat); 989 990 elapsed = mstime()-start_time; 991 if (elapsed >= 500) { 992 printf("(%.2fs)\n",(double)elapsed/1000); 993 } 994 } 995 } 996 /* Free the argument vector */ 997 sdsfreesplitres(argv,argc); 998 } 999 /* linenoise() returns malloc-ed lines like readline() */ 1000 free(line); 1001 } 1002 exit(0); 1003 } 1004 1005 static int noninteractive(int argc, char **argv) { 1006 int retval = 0; 1007 if (config.stdinarg) { 1008 argv = zrealloc(argv, (argc+1)*sizeof(char*)); 1009 argv[argc] = readArgFromStdin(); 1010 retval = issueCommand(argc+1, argv); 1011 } else { 1012 retval = issueCommand(argc, argv); 1013 } 1014 return retval; 1015 } 1016 1017 /*------------------------------------------------------------------------------ 1018 * Eval mode 1019 *--------------------------------------------------------------------------- */ 1020 1021 static int evalMode(int argc, char **argv) { 1022 sds script = sdsempty(); 1023 FILE *fp; 1024 char buf[1024]; 1025 size_t nread; 1026 char **argv2; 1027 int j, got_comma = 0, keys = 0; 1028 1029 /* Load the script from the file, as an sds string. */ 1030 fp = fopen(config.eval,"r"); 1031 if (!fp) { 1032 fprintf(stderr, 1033 "Can't open file '%s': %s\n", config.eval, strerror(errno)); 1034 exit(1); 1035 } 1036 while((nread = fread(buf,1,sizeof(buf),fp)) != 0) { 1037 script = sdscatlen(script,buf,nread); 1038 } 1039 fclose(fp); 1040 1041 /* Create our argument vector */ 1042 argv2 = zmalloc(sizeof(sds)*(argc+3)); 1043 argv2[0] = sdsnew("EVAL"); 1044 argv2[1] = script; 1045 for (j = 0; j < argc; j++) { 1046 if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) { 1047 got_comma = 1; 1048 continue; 1049 } 1050 argv2[j+3-got_comma] = sdsnew(argv[j]); 1051 if (!got_comma) keys++; 1052 } 1053 argv2[2] = sdscatprintf(sdsempty(),"%d",keys); 1054 1055 /* Call it */ 1056 return issueCommand(argc+3-got_comma, argv2); 1057 } 1058 1059 /*------------------------------------------------------------------------------ 1060 * Latency and latency history modes 1061 *--------------------------------------------------------------------------- */ 1062 1063 #define LATENCY_SAMPLE_RATE 10 /* milliseconds. */ 1064 #define LATENCY_HISTORY_DEFAULT_INTERVAL 15000 /* milliseconds. */ 1065 static void latencyMode(void) { 1066 redisReply *reply; 1067 long long start, latency, min = 0, max = 0, tot = 0, count = 0; 1068 long long history_interval = 1069 config.interval ? config.interval/1000 : 1070 LATENCY_HISTORY_DEFAULT_INTERVAL; 1071 double avg; 1072 long long history_start = mstime(); 1073 1074 if (!context) exit(1); 1075 while(1) { 1076 start = mstime(); 1077 reply = redisCommand(context,"PING"); 1078 if (reply == NULL) { 1079 fprintf(stderr,"\nI/O error\n"); 1080 exit(1); 1081 } 1082 latency = mstime()-start; 1083 freeReplyObject(reply); 1084 count++; 1085 if (count == 1) { 1086 min = max = tot = latency; 1087 avg = (double) latency; 1088 } else { 1089 if (latency < min) min = latency; 1090 if (latency > max) max = latency; 1091 tot += latency; 1092 avg = (double) tot/count; 1093 } 1094 printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)", 1095 min, max, avg, count); 1096 fflush(stdout); 1097 if (config.latency_history && mstime()-history_start > history_interval) 1098 { 1099 printf(" -- %.2f seconds range\n", (float)(mstime()-history_start)/1000); 1100 history_start = mstime(); 1101 min = max = tot = count = 0; 1102 } 1103 usleep(LATENCY_SAMPLE_RATE * 1000); 1104 } 1105 } 1106 1107 /*------------------------------------------------------------------------------ 1108 * Slave mode 1109 *--------------------------------------------------------------------------- */ 1110 1111 /* Sends SYNC and reads the number of bytes in the payload. Used both by 1112 * slaveMode() and getRDB(). */ 1113 unsigned long long sendSync(int fd) { 1114 /* To start we need to send the SYNC command and return the payload. 1115 * The hiredis client lib does not understand this part of the protocol 1116 * and we don't want to mess with its buffers, so everything is performed 1117 * using direct low-level I/O. */ 1118 char buf[4096], *p; 1119 ssize_t nread; 1120 1121 /* Send the SYNC command. */ 1122 if (write(fd,"SYNC\r\n",6) != 6) { 1123 fprintf(stderr,"Error writing to master\n"); 1124 exit(1); 1125 } 1126 1127 /* Read $<payload>\r\n, making sure to read just up to "\n" */ 1128 p = buf; 1129 while(1) { 1130 nread = read(fd,p,1); 1131 if (nread <= 0) { 1132 fprintf(stderr,"Error reading bulk length while SYNCing\n"); 1133 exit(1); 1134 } 1135 if (*p == '\n' && p != buf) break; 1136 if (*p != '\n') p++; 1137 } 1138 *p = '\0'; 1139 if (buf[0] == '-') { 1140 printf("SYNC with master failed: %s\n", buf); 1141 exit(1); 1142 } 1143 return strtoull(buf+1,NULL,10); 1144 } 1145 1146 static void slaveMode(void) { 1147 int fd = context->fd; 1148 unsigned long long payload = sendSync(fd); 1149 char buf[1024]; 1150 int original_output = config.output; 1151 1152 fprintf(stderr,"SYNC with master, discarding %llu " 1153 "bytes of bulk transfer...\n", payload); 1154 1155 /* Discard the payload. */ 1156 while(payload) { 1157 ssize_t nread; 1158 1159 nread = read(fd,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload); 1160 if (nread <= 0) { 1161 fprintf(stderr,"Error reading RDB payload while SYNCing\n"); 1162 exit(1); 1163 } 1164 payload -= nread; 1165 } 1166 fprintf(stderr,"SYNC done. Logging commands from master.\n"); 1167 1168 /* Now we can use hiredis to read the incoming protocol. */ 1169 config.output = OUTPUT_CSV; 1170 while (cliReadReply(0) == REDIS_OK); 1171 config.output = original_output; 1172 } 1173 1174 /*------------------------------------------------------------------------------ 1175 * RDB transfer mode 1176 *--------------------------------------------------------------------------- */ 1177 1178 /* This function implements --rdb, so it uses the replication protocol in order 1179 * to fetch the RDB file from a remote server. */ 1180 static void getRDB(void) { 1181 int s = context->fd; 1182 int fd; 1183 unsigned long long payload = sendSync(s); 1184 char buf[4096]; 1185 1186 fprintf(stderr,"SYNC sent to master, writing %llu bytes to '%s'\n", 1187 payload, config.rdb_filename); 1188 1189 /* Write to file. */ 1190 if (!strcmp(config.rdb_filename,"-")) { 1191 fd = STDOUT_FILENO; 1192 } else { 1193 fd = open(config.rdb_filename, O_CREAT|O_WRONLY, 0644); 1194 if (fd == -1) { 1195 fprintf(stderr, "Error opening '%s': %s\n", config.rdb_filename, 1196 strerror(errno)); 1197 exit(1); 1198 } 1199 } 1200 1201 while(payload) { 1202 ssize_t nread, nwritten; 1203 1204 nread = read(s,buf,(payload > sizeof(buf)) ? sizeof(buf) : payload); 1205 if (nread <= 0) { 1206 fprintf(stderr,"I/O Error reading RDB payload from socket\n"); 1207 exit(1); 1208 } 1209 nwritten = write(fd, buf, nread); 1210 if (nwritten != nread) { 1211 fprintf(stderr,"Error writing data to file: %s\n", 1212 strerror(errno)); 1213 exit(1); 1214 } 1215 payload -= nread; 1216 } 1217 close(s); /* Close the file descriptor ASAP as fsync() may take time. */ 1218 fsync(fd); 1219 fprintf(stderr,"Transfer finished with success.\n"); 1220 exit(0); 1221 } 1222 1223 /*------------------------------------------------------------------------------ 1224 * Bulk import (pipe) mode 1225 *--------------------------------------------------------------------------- */ 1226 1227 static void pipeMode(void) { 1228 int fd = context->fd; 1229 long long errors = 0, replies = 0, obuf_len = 0, obuf_pos = 0; 1230 char ibuf[1024*16], obuf[1024*16]; /* Input and output buffers */ 1231 char aneterr[ANET_ERR_LEN]; 1232 redisReader *reader = redisReaderCreate(); 1233 redisReply *reply; 1234 int eof = 0; /* True once we consumed all the standard input. */ 1235 int done = 0; 1236 char magic[20]; /* Special reply we recognize. */ 1237 time_t last_read_time = time(NULL); 1238 1239 srand(time(NULL)); 1240 1241 /* Use non blocking I/O. */ 1242 if (anetNonBlock(aneterr,fd) == ANET_ERR) { 1243 fprintf(stderr, "Can't set the socket in non blocking mode: %s\n", 1244 aneterr); 1245 exit(1); 1246 } 1247 1248 /* Transfer raw protocol and read replies from the server at the same 1249 * time. */ 1250 while(!done) { 1251 int mask = AE_READABLE; 1252 1253 if (!eof || obuf_len != 0) mask |= AE_WRITABLE; 1254 mask = aeWait(fd,mask,1000); 1255 1256 /* Handle the readable state: we can read replies from the server. */ 1257 if (mask & AE_READABLE) { 1258 ssize_t nread; 1259 1260 /* Read from socket and feed the hiredis reader. */ 1261 do { 1262 nread = read(fd,ibuf,sizeof(ibuf)); 1263 if (nread == -1 && errno != EAGAIN && errno != EINTR) { 1264 fprintf(stderr, "Error reading from the server: %s\n", 1265 strerror(errno)); 1266 exit(1); 1267 } 1268 if (nread > 0) { 1269 redisReaderFeed(reader,ibuf,nread); 1270 last_read_time = time(NULL); 1271 } 1272 } while(nread > 0); 1273 1274 /* Consume replies. */ 1275 do { 1276 if (redisReaderGetReply(reader,(void**)&reply) == REDIS_ERR) { 1277 fprintf(stderr, "Error reading replies from server\n"); 1278 exit(1); 1279 } 1280 if (reply) { 1281 if (reply->type == REDIS_REPLY_ERROR) { 1282 fprintf(stderr,"%s\n", reply->str); 1283 errors++; 1284 } else if (eof && reply->type == REDIS_REPLY_STRING && 1285 reply->len == 20) { 1286 /* Check if this is the reply to our final ECHO 1287 * command. If so everything was received 1288 * from the server. */ 1289 if (memcmp(reply->str,magic,20) == 0) { 1290 printf("Last reply received from server.\n"); 1291 done = 1; 1292 replies--; 1293 } 1294 } 1295 replies++; 1296 freeReplyObject(reply); 1297 } 1298 } while(reply); 1299 } 1300 1301 /* Handle the writable state: we can send protocol to the server. */ 1302 if (mask & AE_WRITABLE) { 1303 while(1) { 1304 /* Transfer current buffer to server. */ 1305 if (obuf_len != 0) { 1306 ssize_t nwritten = write(fd,obuf+obuf_pos,obuf_len); 1307 1308 if (nwritten == -1) { 1309 if (errno != EAGAIN && errno != EINTR) { 1310 fprintf(stderr, "Error writing to the server: %s\n", 1311 strerror(errno)); 1312 exit(1); 1313 } else { 1314 nwritten = 0; 1315 } 1316 } 1317 obuf_len -= nwritten; 1318 obuf_pos += nwritten; 1319 if (obuf_len != 0) break; /* Can't accept more data. */ 1320 } 1321 /* If buffer is empty, load from stdin. */ 1322 if (obuf_len == 0 && !eof) { 1323 ssize_t nread = read(STDIN_FILENO,obuf,sizeof(obuf)); 1324 1325 if (nread == 0) { 1326 /* The ECHO sequence starts with a "\r\n" so that if there 1327 * is garbage in the protocol we read from stdin, the ECHO 1328 * will likely still be properly formatted. 1329 * CRLF is ignored by Redis, so it has no effects. */ 1330 char echo[] = 1331 "\r\n*2\r\n$4\r\nECHO\r\n$20\r\n01234567890123456789\r\n"; 1332 int j; 1333 1334 eof = 1; 1335 /* Everything transferred, so we queue a special 1336 * ECHO command that we can match in the replies 1337 * to make sure everything was read from the server. */ 1338 for (j = 0; j < 20; j++) 1339 magic[j] = rand() & 0xff; 1340 memcpy(echo+21,magic,20); 1341 memcpy(obuf,echo,sizeof(echo)-1); 1342 obuf_len = sizeof(echo)-1; 1343 obuf_pos = 0; 1344 printf("All data transferred. Waiting for the last reply...\n"); 1345 } else if (nread == -1) { 1346 fprintf(stderr, "Error reading from stdin: %s\n", 1347 strerror(errno)); 1348 exit(1); 1349 } else { 1350 obuf_len = nread; 1351 obuf_pos = 0; 1352 } 1353 } 1354 if (obuf_len == 0 && eof) break; 1355 } 1356 } 1357 1358 /* Handle timeout, that is, we reached EOF, and we are not getting 1359 * replies from the server for a few seconds, nor the final ECHO is 1360 * received. */ 1361 if (eof && config.pipe_timeout > 0 && 1362 time(NULL)-last_read_time > config.pipe_timeout) 1363 { 1364 fprintf(stderr,"No replies for %d seconds: exiting.\n", 1365 config.pipe_timeout); 1366 errors++; 1367 break; 1368 } 1369 } 1370 redisReaderFree(reader); 1371 printf("errors: %lld, replies: %lld\n", errors, replies); 1372 if (errors) 1373 exit(1); 1374 else 1375 exit(0); 1376 } 1377 1378 /*------------------------------------------------------------------------------ 1379 * Find big keys 1380 *--------------------------------------------------------------------------- */ 1381 1382 #define TYPE_STRING 0 1383 #define TYPE_LIST 1 1384 #define TYPE_SET 2 1385 #define TYPE_HASH 3 1386 #define TYPE_ZSET 4 1387 #define TYPE_NONE 5 1388 1389 static redisReply *sendScan(unsigned long long *it) { 1390 redisReply *reply = redisCommand(context, "SCAN %llu", *it); 1391 1392 /* Handle any error conditions */ 1393 if(reply == NULL) { 1394 fprintf(stderr, "\nI/O error\n"); 1395 exit(1); 1396 } else if(reply->type == REDIS_REPLY_ERROR) { 1397 fprintf(stderr, "SCAN error: %s\n", reply->str); 1398 exit(1); 1399 } else if(reply->type != REDIS_REPLY_ARRAY) { 1400 fprintf(stderr, "Non ARRAY response from SCAN!\n"); 1401 exit(1); 1402 } else if(reply->elements != 2) { 1403 fprintf(stderr, "Invalid element count from SCAN!\n"); 1404 exit(1); 1405 } 1406 1407 /* Validate our types are correct */ 1408 assert(reply->element[0]->type == REDIS_REPLY_STRING); 1409 assert(reply->element[1]->type == REDIS_REPLY_ARRAY); 1410 1411 /* Update iterator */ 1412 *it = atoi(reply->element[0]->str); 1413 1414 return reply; 1415 } 1416 1417 static int getDbSize(void) { 1418 redisReply *reply; 1419 int size; 1420 1421 reply = redisCommand(context, "DBSIZE"); 1422 1423 if(reply == NULL || reply->type != REDIS_REPLY_INTEGER) { 1424 fprintf(stderr, "Couldn't determine DBSIZE!\n"); 1425 exit(1); 1426 } 1427 1428 /* Grab the number of keys and free our reply */ 1429 size = reply->integer; 1430 freeReplyObject(reply); 1431 1432 return size; 1433 } 1434 1435 static int toIntType(char *key, char *type) { 1436 if(!strcmp(type, "string")) { 1437 return TYPE_STRING; 1438 } else if(!strcmp(type, "list")) { 1439 return TYPE_LIST; 1440 } else if(!strcmp(type, "set")) { 1441 return TYPE_SET; 1442 } else if(!strcmp(type, "hash")) { 1443 return TYPE_HASH; 1444 } else if(!strcmp(type, "zset")) { 1445 return TYPE_ZSET; 1446 } else if(!strcmp(type, "none")) { 1447 return TYPE_NONE; 1448 } else { 1449 fprintf(stderr, "Unknown type '%s' for key '%s'\n", type, key); 1450 exit(1); 1451 } 1452 } 1453 1454 static void getKeyTypes(redisReply *keys, int *types) { 1455 redisReply *reply; 1456 unsigned int i; 1457 1458 /* Pipeline TYPE commands */ 1459 for(i=0;i<keys->elements;i++) { 1460 redisAppendCommand(context, "TYPE %s", keys->element[i]->str); 1461 } 1462 1463 /* Retrieve types */ 1464 for(i=0;i<keys->elements;i++) { 1465 if(redisGetReply(context, (void**)&reply)!=REDIS_OK) { 1466 fprintf(stderr, "Error getting type for key '%s' (%d: %s)\n", 1467 keys->element[i]->str, context->err, context->errstr); 1468 exit(1); 1469 } else if(reply->type != REDIS_REPLY_STATUS) { 1470 fprintf(stderr, "Invalid reply type (%d) for TYPE on key '%s'!\n", 1471 reply->type, keys->element[i]->str); 1472 exit(1); 1473 } 1474 1475 types[i] = toIntType(keys->element[i]->str, reply->str); 1476 freeReplyObject(reply); 1477 } 1478 } 1479 1480 static void getKeySizes(redisReply *keys, int *types, 1481 unsigned long long *sizes) 1482 { 1483 redisReply *reply; 1484 char *sizecmds[] = {"STRLEN","LLEN","SCARD","HLEN","ZCARD"}; 1485 unsigned int i; 1486 1487 /* Pipeline size commands */ 1488 for(i=0;i<keys->elements;i++) { 1489 /* Skip keys that were deleted */ 1490 if(types[i]==TYPE_NONE) 1491 continue; 1492 1493 redisAppendCommand(context, "%s %s", sizecmds[types[i]], 1494 keys->element[i]->str); 1495 } 1496 1497 /* Retreive sizes */ 1498 for(i=0;i<keys->elements;i++) { 1499 /* Skip keys that dissapeared between SCAN and TYPE */ 1500 if(types[i] == TYPE_NONE) { 1501 sizes[i] = 0; 1502 continue; 1503 } 1504 1505 /* Retreive size */ 1506 if(redisGetReply(context, (void**)&reply)!=REDIS_OK) { 1507 fprintf(stderr, "Error getting size for key '%s' (%d: %s)\n", 1508 keys->element[i]->str, context->err, context->errstr); 1509 exit(1); 1510 } else if(reply->type != REDIS_REPLY_INTEGER) { 1511 /* Theoretically the key could have been removed and 1512 * added as a different type between TYPE and SIZE */ 1513 fprintf(stderr, 1514 "Warning: %s on '%s' failed (may have changed type)\n", 1515 sizecmds[types[i]], keys->element[i]->str); 1516 sizes[i] = 0; 1517 } else { 1518 sizes[i] = reply->integer; 1519 } 1520 1521 freeReplyObject(reply); 1522 } 1523 } 1524 1525 static void findBigKeys(void) { 1526 unsigned long long biggest[5] = {0}, counts[5] = {0}, totalsize[5] = {0}; 1527 unsigned long long sampled = 0, total_keys, totlen=0, *sizes=NULL, it=0; 1528 sds maxkeys[5] = {0}; 1529 char *typename[] = {"string","list","set","hash","zset"}; 1530 char *typeunit[] = {"bytes","items","members","fields","members"}; 1531 redisReply *reply, *keys; 1532 unsigned int arrsize=0, i; 1533 int type, *types=NULL; 1534 double pct; 1535 1536 /* Total keys pre scanning */ 1537 total_keys = getDbSize(); 1538 1539 /* Status message */ 1540 printf("\n# Scanning the entire keyspace to find biggest keys as well as\n"); 1541 printf("# average sizes per key type. You can use -i 0.1 to sleep 0.1 sec\n"); 1542 printf("# per 100 SCAN commands (not usually needed).\n\n"); 1543 1544 /* New up sds strings to keep track of overall biggest per type */ 1545 for(i=0;i<TYPE_NONE; i++) { 1546 maxkeys[i] = sdsempty(); 1547 if(!maxkeys[i]) { 1548 fprintf(stderr, "Failed to allocate memory for largest key names!\n"); 1549 exit(1); 1550 } 1551 } 1552 1553 /* SCAN loop */ 1554 do { 1555 /* Calculate approximate percentage completion */ 1556 pct = 100 * (double)sampled/total_keys; 1557 1558 /* Grab some keys and point to the keys array */ 1559 reply = sendScan(&it); 1560 keys = reply->element[1]; 1561 1562 /* Reallocate our type and size array if we need to */ 1563 if(keys->elements > arrsize) { 1564 types = zrealloc(types, sizeof(int)*keys->elements); 1565 sizes = zrealloc(sizes, sizeof(unsigned long long)*keys->elements); 1566 1567 if(!types || !sizes) { 1568 fprintf(stderr, "Failed to allocate storage for keys!\n"); 1569 exit(1); 1570 } 1571 1572 arrsize = keys->elements; 1573 } 1574 1575 /* Retreive types and then sizes */ 1576 getKeyTypes(keys, types); 1577 getKeySizes(keys, types, sizes); 1578 1579 /* Now update our stats */ 1580 for(i=0;i<keys->elements;i++) { 1581 if((type = types[i]) == TYPE_NONE) 1582 continue; 1583 1584 totalsize[type] += sizes[i]; 1585 counts[type]++; 1586 totlen += keys->element[i]->len; 1587 sampled++; 1588 1589 if(biggest[type]<sizes[i]) { 1590 printf( 1591 "[%05.2f%%] Biggest %-6s found so far '%s' with %llu %s\n", 1592 pct, typename[type], keys->element[i]->str, sizes[i], 1593 typeunit[type]); 1594 1595 /* Keep track of biggest key name for this type */ 1596 maxkeys[type] = sdscpy(maxkeys[type], keys->element[i]->str); 1597 if(!maxkeys[type]) { 1598 fprintf(stderr, "Failed to allocate memory for key!\n"); 1599 exit(1); 1600 } 1601 1602 /* Keep track of the biggest size for this type */ 1603 biggest[type] = sizes[i]; 1604 } 1605 1606 /* Update overall progress */ 1607 if(sampled % 1000000 == 0) { 1608 printf("[%05.2f%%] Sampled %llu keys so far\n", pct, sampled); 1609 } 1610 } 1611 1612 /* Sleep if we've been directed to do so */ 1613 if(sampled && (sampled %100) == 0 && config.interval) { 1614 usleep(config.interval); 1615 } 1616 1617 freeReplyObject(reply); 1618 } while(it != 0); 1619 1620 if(types) zfree(types); 1621 if(sizes) zfree(sizes); 1622 1623 /* We're done */ 1624 printf("\n-------- summary -------\n\n"); 1625 1626 printf("Sampled %llu keys in the keyspace!\n", sampled); 1627 printf("Total key length in bytes is %llu (avg len %.2f)\n\n", 1628 totlen, totlen ? (double)totlen/sampled : 0); 1629 1630 /* Output the biggest keys we found, for types we did find */ 1631 for(i=0;i<TYPE_NONE;i++) { 1632 if(sdslen(maxkeys[i])>0) { 1633 printf("Biggest %6s found '%s' has %llu %s\n", typename[i], maxkeys[i], 1634 biggest[i], typeunit[i]); 1635 } 1636 } 1637 1638 printf("\n"); 1639 1640 for(i=0;i<TYPE_NONE;i++) { 1641 printf("%llu %ss with %llu %s (%05.2f%% of keys, avg size %.2f)\n", 1642 counts[i], typename[i], totalsize[i], typeunit[i], 1643 sampled ? 100 * (double)counts[i]/sampled : 0, 1644 counts[i] ? (double)totalsize[i]/counts[i] : 0); 1645 } 1646 1647 /* Free sds strings containing max keys */ 1648 for(i=0;i<TYPE_NONE;i++) { 1649 sdsfree(maxkeys[i]); 1650 } 1651 1652 /* Success! */ 1653 exit(0); 1654 } 1655 1656 /*------------------------------------------------------------------------------ 1657 * Stats mode 1658 *--------------------------------------------------------------------------- */ 1659 1660 /* Return the specified INFO field from the INFO command output "info". 1661 * A new buffer is allocated for the result, that needs to be free'd. 1662 * If the field is not found NULL is returned. */ 1663 static char *getInfoField(char *info, char *field) { 1664 char *p = strstr(info,field); 1665 char *n1, *n2; 1666 char *result; 1667 1668 if (!p) return NULL; 1669 p += strlen(field)+1; 1670 n1 = strchr(p,'\r'); 1671 n2 = strchr(p,','); 1672 if (n2 && n2 < n1) n1 = n2; 1673 result = malloc(sizeof(char)*(n1-p)+1); 1674 memcpy(result,p,(n1-p)); 1675 result[n1-p] = '\0'; 1676 return result; 1677 } 1678 1679 /* Like the above function but automatically convert the result into 1680 * a long. On error (missing field) LONG_MIN is returned. */ 1681 static long getLongInfoField(char *info, char *field) { 1682 char *value = getInfoField(info,field); 1683 long l; 1684 1685 if (!value) return LONG_MIN; 1686 l = strtol(value,NULL,10); 1687 free(value); 1688 return l; 1689 } 1690 1691 /* Convert number of bytes into a human readable string of the form: 1692 * 100B, 2G, 100M, 4K, and so forth. */ 1693 void bytesToHuman(char *s, long long n) { 1694 double d; 1695 1696 if (n < 0) { 1697 *s = '-'; 1698 s++; 1699 n = -n; 1700 } 1701 if (n < 1024) { 1702 /* Bytes */ 1703 sprintf(s,"%lluB",n); 1704 return; 1705 } else if (n < (1024*1024)) { 1706 d = (double)n/(1024); 1707 sprintf(s,"%.2fK",d); 1708 } else if (n < (1024LL*1024*1024)) { 1709 d = (double)n/(1024*1024); 1710 sprintf(s,"%.2fM",d); 1711 } else if (n < (1024LL*1024*1024*1024)) { 1712 d = (double)n/(1024LL*1024*1024); 1713 sprintf(s,"%.2fG",d); 1714 } 1715 } 1716 1717 static void statMode(void) { 1718 redisReply *reply; 1719 long aux, requests = 0; 1720 int i = 0; 1721 1722 while(1) { 1723 char buf[64]; 1724 int j; 1725 1726 reply = reconnectingInfo(); 1727 if (reply->type == REDIS_REPLY_ERROR) { 1728 printf("ERROR: %s\n", reply->str); 1729 exit(1); 1730 } 1731 1732 if ((i++ % 20) == 0) { 1733 printf( 1734 "------- data ------ --------------------- load -------------------- - child -\n" 1735 "keys mem clients blocked requests connections \n"); 1736 } 1737 1738 /* Keys */ 1739 aux = 0; 1740 for (j = 0; j < 20; j++) { 1741 long k; 1742 1743 sprintf(buf,"db%d:keys",j); 1744 k = getLongInfoField(reply->str,buf); 1745 if (k == LONG_MIN) continue; 1746 aux += k; 1747 } 1748 sprintf(buf,"%ld",aux); 1749 printf("%-11s",buf); 1750 1751 /* Used memory */ 1752 aux = getLongInfoField(reply->str,"used_memory"); 1753 bytesToHuman(buf,aux); 1754 printf("%-8s",buf); 1755 1756 /* Clients */ 1757 aux = getLongInfoField(reply->str,"connected_clients"); 1758 sprintf(buf,"%ld",aux); 1759 printf(" %-8s",buf); 1760 1761 /* Blocked (BLPOPPING) Clients */ 1762 aux = getLongInfoField(reply->str,"blocked_clients"); 1763 sprintf(buf,"%ld",aux); 1764 printf("%-8s",buf); 1765 1766 /* Requets */ 1767 aux = getLongInfoField(reply->str,"total_commands_processed"); 1768 sprintf(buf,"%ld (+%ld)",aux,requests == 0 ? 0 : aux-requests); 1769 printf("%-19s",buf); 1770 requests = aux; 1771 1772 /* Connections */ 1773 aux = getLongInfoField(reply->str,"total_connections_received"); 1774 sprintf(buf,"%ld",aux); 1775 printf(" %-12s",buf); 1776 1777 /* Children */ 1778 aux = getLongInfoField(reply->str,"bgsave_in_progress"); 1779 aux |= getLongInfoField(reply->str,"aof_rewrite_in_progress") << 1; 1780 switch(aux) { 1781 case 0: break; 1782 case 1: 1783 printf("SAVE"); 1784 break; 1785 case 2: 1786 printf("AOF"); 1787 break; 1788 case 3: 1789 printf("SAVE+AOF"); 1790 break; 1791 } 1792 1793 printf("\n"); 1794 freeReplyObject(reply); 1795 usleep(config.interval); 1796 } 1797 } 1798 1799 /*------------------------------------------------------------------------------ 1800 * Scan mode 1801 *--------------------------------------------------------------------------- */ 1802 1803 static void scanMode(void) { 1804 redisReply *reply; 1805 unsigned long long cur = 0; 1806 1807 do { 1808 if (config.pattern) 1809 reply = redisCommand(context,"SCAN %llu MATCH %s", 1810 cur,config.pattern); 1811 else 1812 reply = redisCommand(context,"SCAN %llu",cur); 1813 if (reply == NULL) { 1814 printf("I/O error\n"); 1815 exit(1); 1816 } else if (reply->type == REDIS_REPLY_ERROR) { 1817 printf("ERROR: %s\n", reply->str); 1818 exit(1); 1819 } else { 1820 unsigned int j; 1821 1822 cur = strtoull(reply->element[0]->str,NULL,10); 1823 for (j = 0; j < reply->element[1]->elements; j++) 1824 printf("%s\n", reply->element[1]->element[j]->str); 1825 } 1826 freeReplyObject(reply); 1827 } while(cur != 0); 1828 1829 exit(0); 1830 } 1831 1832 /*------------------------------------------------------------------------------ 1833 * Intrisic latency mode. 1834 * 1835 * Measure max latency of a running process that does not result from 1836 * syscalls. Basically this software should provide an hint about how much 1837 * time the kernel leaves the process without a chance to run. 1838 *--------------------------------------------------------------------------- */ 1839 1840 /* This is just some computation the compiler can't optimize out. 1841 * Should run in less than 100-200 microseconds even using very 1842 * slow hardware. Runs in less than 10 microseconds in modern HW. */ 1843 unsigned long compute_something_fast(void) { 1844 unsigned char s[256], i, j, t; 1845 int count = 1000, k; 1846 unsigned long output = 0; 1847 1848 for (k = 0; k < 256; k++) s[k] = k; 1849 1850 i = 0; 1851 j = 0; 1852 while(count--) { 1853 i++; 1854 j = j + s[i]; 1855 t = s[i]; 1856 s[i] = s[j]; 1857 s[j] = t; 1858 output += s[(s[i]+s[j])&255]; 1859 } 1860 return output; 1861 } 1862 1863 static void intrinsicLatencyModeStop(int s) { 1864 REDIS_NOTUSED(s); 1865 force_cancel_loop = 1; 1866 } 1867 1868 static void intrinsicLatencyMode(void) { 1869 long long test_end, run_time, max_latency = 0, runs = 0; 1870 1871 run_time = config.intrinsic_latency_duration*1000000; 1872 test_end = ustime() + run_time; 1873 signal(SIGINT, intrinsicLatencyModeStop); 1874 1875 while(1) { 1876 long long start, end, latency; 1877 1878 start = ustime(); 1879 compute_something_fast(); 1880 end = ustime(); 1881 latency = end-start; 1882 runs++; 1883 if (latency <= 0) continue; 1884 1885 /* Reporting */ 1886 if (latency > max_latency) { 1887 max_latency = latency; 1888 printf("Max latency so far: %lld microseconds.\n", max_latency); 1889 } 1890 1891 double avg_us = (double)run_time/runs; 1892 double avg_ns = avg_us * 10e3; 1893 if (force_cancel_loop || end > test_end) { 1894 printf("\n%lld total runs " 1895 "(avg latency: " 1896 "%.4f microseconds / %.2f nanoseconds per run).\n", 1897 runs, avg_us, avg_ns); 1898 printf("Worst run took %.0fx longer than the average latency.\n", 1899 max_latency / avg_us); 1900 exit(0); 1901 } 1902 } 1903 } 1904 1905 /*------------------------------------------------------------------------------ 1906 * Program main() 1907 *--------------------------------------------------------------------------- */ 1908 1909 int main(int argc, char **argv) { 1910 int firstarg; 1911 1912 config.hostip = sdsnew("127.0.0.1"); 1913 config.hostport = 6379; 1914 config.hostsocket = NULL; 1915 config.repeat = 1; 1916 config.interval = 0; 1917 config.dbnum = 0; 1918 config.interactive = 0; 1919 config.shutdown = 0; 1920 config.monitor_mode = 0; 1921 config.pubsub_mode = 0; 1922 config.latency_mode = 0; 1923 config.latency_history = 0; 1924 config.cluster_mode = 0; 1925 config.slave_mode = 0; 1926 config.getrdb_mode = 0; 1927 config.stat_mode = 0; 1928 config.scan_mode = 0; 1929 config.intrinsic_latency_mode = 0; 1930 config.pattern = NULL; 1931 config.rdb_filename = NULL; 1932 config.pipe_mode = 0; 1933 config.pipe_timeout = REDIS_CLI_DEFAULT_PIPE_TIMEOUT; 1934 config.bigkeys = 0; 1935 config.stdinarg = 0; 1936 config.auth = NULL; 1937 config.eval = NULL; 1938 config.last_cmd_type = -1; 1939 1940 if (!isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL)) 1941 config.output = OUTPUT_RAW; 1942 else 1943 config.output = OUTPUT_STANDARD; 1944 config.mb_delim = sdsnew("\n"); 1945 cliInitHelp(); 1946 1947 firstarg = parseOptions(argc,argv); 1948 argc -= firstarg; 1949 argv += firstarg; 1950 1951 /* Latency mode */ 1952 if (config.latency_mode) { 1953 if (cliConnect(0) == REDIS_ERR) exit(1); 1954 latencyMode(); 1955 } 1956 1957 /* Slave mode */ 1958 if (config.slave_mode) { 1959 if (cliConnect(0) == REDIS_ERR) exit(1); 1960 slaveMode(); 1961 } 1962 1963 /* Get RDB mode. */ 1964 if (config.getrdb_mode) { 1965 if (cliConnect(0) == REDIS_ERR) exit(1); 1966 getRDB(); 1967 } 1968 1969 /* Pipe mode */ 1970 if (config.pipe_mode) { 1971 if (cliConnect(0) == REDIS_ERR) exit(1); 1972 pipeMode(); 1973 } 1974 1975 /* Find big keys */ 1976 if (config.bigkeys) { 1977 if (cliConnect(0) == REDIS_ERR) exit(1); 1978 findBigKeys(); 1979 } 1980 1981 /* Stat mode */ 1982 if (config.stat_mode) { 1983 if (cliConnect(0) == REDIS_ERR) exit(1); 1984 if (config.interval == 0) config.interval = 1000000; 1985 statMode(); 1986 } 1987 1988 /* Scan mode */ 1989 if (config.scan_mode) { 1990 if (cliConnect(0) == REDIS_ERR) exit(1); 1991 scanMode(); 1992 } 1993 1994 /* Intrinsic latency mode */ 1995 if (config.intrinsic_latency_mode) intrinsicLatencyMode(); 1996 1997 /* Start interactive mode when no command is provided */ 1998 if (argc == 0 && !config.eval) { 1999 /* Ignore SIGPIPE in interactive mode to force a reconnect */ 2000 signal(SIGPIPE, SIG_IGN); 2001 2002 /* Note that in repl mode we don't abort on connection error. 2003 * A new attempt will be performed for every command send. */ 2004 cliConnect(0); 2005 repl(); 2006 } 2007 2008 /* Otherwise, we have some arguments to execute */ 2009 if (cliConnect(0) != REDIS_OK) exit(1); 2010 if (config.eval) { 2011 return evalMode(argc,argv); 2012 } else { 2013 return noninteractive(argc,convertToSds(argc,argv)); 2014 } 2015 } 2016