redis-cli.c 28.3 KB
Newer Older
A
antirez 已提交
1 2
/* Redis CLI (command line interface)
 *
3
 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
A
antirez 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

31
#include "fmacros.h"
32
#include "version.h"
33

A
antirez 已提交
34 35 36 37
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#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>
A
antirez 已提交
43

P
Pieter Noordhuis 已提交
44
#include "hiredis.h"
A
antirez 已提交
45 46
#include "sds.h"
#include "zmalloc.h"
47
#include "linenoise.h"
48
#include "help.h"
A
antirez 已提交
49 50 51

#define REDIS_NOTUSED(V) ((void) V)

P
Pieter Noordhuis 已提交
52
static redisContext *context;
A
antirez 已提交
53 54 55
static struct config {
    char *hostip;
    int hostport;
56
    char *hostsocket;
57
    long repeat;
58
    long interval;
I
ian 已提交
59
    int dbnum;
60
    int interactive;
61
    int shutdown;
62 63
    int monitor_mode;
    int pubsub_mode;
A
antirez 已提交
64
    int latency_mode;
65 66
    int cluster_mode;
    int cluster_reissue_command;
67
    int stdinarg; /* get last arg from stdin. (-x option) */
A
antirez 已提交
68
    char *auth;
P
Pieter Noordhuis 已提交
69 70
    int raw_output; /* output mode per command */
    sds mb_delim;
71
    char prompt[128];
A
antirez 已提交
72
    char *eval;
A
antirez 已提交
73 74
} config;

A
antirez 已提交
75
static void usage();
76
char *redisGitSHA1(void);
77
char *redisGitDirty(void);
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92
/*------------------------------------------------------------------------------
 * Utility functions
 *--------------------------------------------------------------------------- */

static long long mstime(void) {
    struct timeval tv;
    long long mst;

    gettimeofday(&tv, NULL);
    mst = ((long)tv.tv_sec)*1000;
    mst += tv.tv_usec/1000;
    return mst;
}

93
static void cliRefreshPrompt(void) {
94 95 96 97 98
    int len;

    if (config.hostsocket != NULL)
        len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
                       config.hostsocket);
99
    else
100 101 102 103 104 105 106
        len = snprintf(config.prompt,sizeof(config.prompt),"redis %s:%d",
                       config.hostip, config.hostport);
    /* Add [dbnum] if needed */
    if (config.dbnum != 0)
        len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
            config.dbnum);
    snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
107 108
}

109 110 111 112
/*------------------------------------------------------------------------------
 * Help functions
 *--------------------------------------------------------------------------- */

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
#define CLI_HELP_COMMAND 1
#define CLI_HELP_GROUP 2

typedef struct {
    int type;
    int argc;
    sds *argv;
    sds full;

    /* Only used for help on commands */
    struct commandHelp *org;
} helpEntry;

static helpEntry *helpEntries;
static int helpEntriesLen;

129 130 131 132 133 134 135 136 137 138 139 140 141 142
static sds cliVersion() {
    sds version;
    version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);

    /* Add git commit and working tree status when available */
    if (strtoll(redisGitSHA1(),NULL,16)) {
        version = sdscatprintf(version, " (git:%s", redisGitSHA1());
        if (strtoll(redisGitDirty(),NULL,10))
            version = sdscatprintf(version, "-dirty");
        version = sdscat(version, ")");
    }
    return version;
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
static void cliInitHelp() {
    int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
    int groupslen = sizeof(commandGroups)/sizeof(char*);
    int i, len, pos = 0;
    helpEntry tmp;

    helpEntriesLen = len = commandslen+groupslen;
    helpEntries = malloc(sizeof(helpEntry)*len);

    for (i = 0; i < groupslen; i++) {
        tmp.argc = 1;
        tmp.argv = malloc(sizeof(sds));
        tmp.argv[0] = sdscatprintf(sdsempty(),"@%s",commandGroups[i]);
        tmp.full = tmp.argv[0];
        tmp.type = CLI_HELP_GROUP;
        tmp.org = NULL;
        helpEntries[pos++] = tmp;
    }

    for (i = 0; i < commandslen; i++) {
        tmp.argv = sdssplitargs(commandHelp[i].name,&tmp.argc);
        tmp.full = sdsnew(commandHelp[i].name);
        tmp.type = CLI_HELP_COMMAND;
        tmp.org = &commandHelp[i];
        helpEntries[pos++] = tmp;
    }
}

171
/* Output command help to stdout. */
172 173 174 175 176 177 178
static void cliOutputCommandHelp(struct commandHelp *help, int group) {
    printf("\r\n  \x1b[1m%s\x1b[0m \x1b[90m%s\x1b[0m\r\n", help->name, help->params);
    printf("  \x1b[33msummary:\x1b[0m %s\r\n", help->summary);
    printf("  \x1b[33msince:\x1b[0m %s\r\n", help->since);
    if (group) {
        printf("  \x1b[33mgroup:\x1b[0m %s\r\n", commandGroups[help->group]);
    }
179 180
}

181 182
/* Print generic help. */
static void cliOutputGenericHelp() {
183
    sds version = cliVersion();
184 185 186 187 188 189
    printf(
        "redis-cli %s\r\n"
        "Type: \"help @<group>\" to get a list of commands in <group>\r\n"
        "      \"help <command>\" for help on <command>\r\n"
        "      \"help <tab>\" to get a list of possible help topics\r\n"
        "      \"quit\" to exit\r\n",
190
        version
191
    );
192
    sdsfree(version);
193 194 195
}

/* Output all command help, filtering by group or command name. */
196
static void cliOutputHelp(int argc, char **argv) {
197
    int i, j, len;
198
    int group = -1;
199 200
    helpEntry *entry;
    struct commandHelp *help;
201

202 203
    if (argc == 0) {
        cliOutputGenericHelp();
204
        return;
205 206 207 208 209 210 211 212
    } else if (argc > 0 && argv[0][0] == '@') {
        len = sizeof(commandGroups)/sizeof(char*);
        for (i = 0; i < len; i++) {
            if (strcasecmp(argv[0]+1,commandGroups[i]) == 0) {
                group = i;
                break;
            }
        }
213 214
    }

215
    assert(argc > 0);
216 217 218 219 220
    for (i = 0; i < helpEntriesLen; i++) {
        entry = &helpEntries[i];
        if (entry->type != CLI_HELP_COMMAND) continue;

        help = entry->org;
221
        if (group == -1) {
222 223 224 225 226 227 228 229
            /* Compare all arguments */
            if (argc == entry->argc) {
                for (j = 0; j < argc; j++) {
                    if (strcasecmp(argv[j],entry->argv[j]) != 0) break;
                }
                if (j == argc) {
                    cliOutputCommandHelp(help,1);
                }
230 231 232
            }
        } else {
            if (group == help->group) {
233
                cliOutputCommandHelp(help,0);
234 235 236
            }
        }
    }
237 238 239 240 241 242 243 244
    printf("\r\n");
}

static void completionCallback(const char *buf, linenoiseCompletions *lc) {
    size_t startpos = 0;
    int mask;
    int i;
    size_t matchlen;
245
    sds tmp;
246 247 248 249

    if (strncasecmp(buf,"help ",5) == 0) {
        startpos = 5;
        while (isspace(buf[startpos])) startpos++;
250
        mask = CLI_HELP_COMMAND | CLI_HELP_GROUP;
251
    } else {
252
        mask = CLI_HELP_COMMAND;
253 254
    }

255 256
    for (i = 0; i < helpEntriesLen; i++) {
        if (!(helpEntries[i].type & mask)) continue;
257 258

        matchlen = strlen(buf+startpos);
259 260 261
        if (strncasecmp(buf+startpos,helpEntries[i].full,matchlen) == 0) {
            tmp = sdsnewlen(buf,startpos);
            tmp = sdscat(tmp,helpEntries[i].full);
262
            linenoiseAddCompletion(lc,tmp);
263
            sdsfree(tmp);
264 265
        }
    }
266 267
}

268 269 270 271
/*------------------------------------------------------------------------------
 * Networking / parsing
 *--------------------------------------------------------------------------- */

P
Pieter Noordhuis 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
/* Send AUTH command to the server */
static int cliAuth() {
    redisReply *reply;
    if (config.auth == NULL) return REDIS_OK;

    reply = redisCommand(context,"AUTH %s",config.auth);
    if (reply != NULL) {
        freeReplyObject(reply);
        return REDIS_OK;
    }
    return REDIS_ERR;
}

/* Send SELECT dbnum to the server */
static int cliSelect() {
    redisReply *reply;
    if (config.dbnum == 0) return REDIS_OK;

290
    reply = redisCommand(context,"SELECT %d",config.dbnum);
P
Pieter Noordhuis 已提交
291 292 293 294 295 296 297
    if (reply != NULL) {
        freeReplyObject(reply);
        return REDIS_OK;
    }
    return REDIS_ERR;
}

298 299 300
/* Connect to the client. If force is not zero the connection is performed
 * even if there is already a connected socket. */
static int cliConnect(int force) {
P
Pieter Noordhuis 已提交
301 302 303
    if (context == NULL || force) {
        if (context != NULL)
            redisFree(context);
A
antirez 已提交
304

305
        if (config.hostsocket == NULL) {
P
Pieter Noordhuis 已提交
306
            context = redisConnect(config.hostip,config.hostport);
307
        } else {
P
Pieter Noordhuis 已提交
308
            context = redisConnectUnix(config.hostsocket);
309
        }
P
Pieter Noordhuis 已提交
310 311

        if (context->err) {
312 313
            fprintf(stderr,"Could not connect to Redis at ");
            if (config.hostsocket == NULL)
P
Pieter Noordhuis 已提交
314
                fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,context->errstr);
315
            else
P
Pieter Noordhuis 已提交
316 317 318 319
                fprintf(stderr,"%s: %s\n",config.hostsocket,context->errstr);
            redisFree(context);
            context = NULL;
            return REDIS_ERR;
320
        }
A
antirez 已提交
321

P
Pieter Noordhuis 已提交
322 323 324 325 326
        /* Do AUTH and select the right DB. */
        if (cliAuth() != REDIS_OK)
            return REDIS_ERR;
        if (cliSelect() != REDIS_OK)
            return REDIS_ERR;
A
antirez 已提交
327
    }
P
Pieter Noordhuis 已提交
328
    return REDIS_OK;
A
antirez 已提交
329 330
}

331
static void cliPrintContextError() {
P
Pieter Noordhuis 已提交
332 333
    if (context == NULL) return;
    fprintf(stderr,"Error: %s\n",context->errstr);
A
antirez 已提交
334 335
}

P
Pieter Noordhuis 已提交
336
static sds cliFormatReplyTTY(redisReply *r, char *prefix) {
P
Pieter Noordhuis 已提交
337 338 339
    sds out = sdsempty();
    switch (r->type) {
    case REDIS_REPLY_ERROR:
P
Pieter Noordhuis 已提交
340
        out = sdscatprintf(out,"(error) %s\n", r->str);
P
Pieter Noordhuis 已提交
341 342 343 344 345 346
    break;
    case REDIS_REPLY_STATUS:
        out = sdscat(out,r->str);
        out = sdscat(out,"\n");
    break;
    case REDIS_REPLY_INTEGER:
P
Pieter Noordhuis 已提交
347
        out = sdscatprintf(out,"(integer) %lld\n",r->integer);
P
Pieter Noordhuis 已提交
348 349
    break;
    case REDIS_REPLY_STRING:
P
Pieter Noordhuis 已提交
350 351 352 353
        /* If you are producing output for the standard output we want
        * a more interesting output with quoted characters and so forth */
        out = sdscatrepr(out,r->str,r->len);
        out = sdscat(out,"\n");
P
Pieter Noordhuis 已提交
354 355 356 357 358 359 360
    break;
    case REDIS_REPLY_NIL:
        out = sdscat(out,"(nil)\n");
    break;
    case REDIS_REPLY_ARRAY:
        if (r->elements == 0) {
            out = sdscat(out,"(empty list or set)\n");
361
        } else {
362 363 364 365
            unsigned int i, idxlen = 0;
            char _prefixlen[16];
            char _prefixfmt[16];
            sds _prefix;
P
Pieter Noordhuis 已提交
366 367
            sds tmp;

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
            /* Calculate chars needed to represent the largest index */
            i = r->elements;
            do {
                idxlen++;
                i /= 10;
            } while(i);

            /* Prefix for nested multi bulks should grow with idxlen+2 spaces */
            memset(_prefixlen,' ',idxlen+2);
            _prefixlen[idxlen+2] = '\0';
            _prefix = sdscat(sdsnew(prefix),_prefixlen);

            /* Setup prefix format for every entry */
            snprintf(_prefixfmt,sizeof(_prefixfmt),"%%s%%%dd) ",idxlen);

P
Pieter Noordhuis 已提交
383
            for (i = 0; i < r->elements; i++) {
384 385 386 387 388
                /* Don't use the prefix for the first element, as the parent
                 * caller already prepended the index number. */
                out = sdscatprintf(out,_prefixfmt,i == 0 ? "" : prefix,i+1);

                /* Format the multi bulk entry */
P
Pieter Noordhuis 已提交
389
                tmp = cliFormatReplyTTY(r->element[i],_prefix);
P
Pieter Noordhuis 已提交
390 391 392
                out = sdscatlen(out,tmp,sdslen(tmp));
                sdsfree(tmp);
            }
393
            sdsfree(_prefix);
394
        }
P
Pieter Noordhuis 已提交
395
    break;
396
    default:
P
Pieter Noordhuis 已提交
397 398
        fprintf(stderr,"Unknown reply type: %d\n", r->type);
        exit(1);
399
    }
P
Pieter Noordhuis 已提交
400
    return out;
401 402
}

P
Pieter Noordhuis 已提交
403 404 405 406 407 408 409
static sds cliFormatReplyRaw(redisReply *r) {
    sds out = sdsempty(), tmp;
    size_t i;

    switch (r->type) {
    case REDIS_REPLY_NIL:
        /* Nothing... */
A
antirez 已提交
410
        break;
P
Pieter Noordhuis 已提交
411
    case REDIS_REPLY_ERROR:
A
antirez 已提交
412 413 414
        out = sdscatlen(out,r->str,r->len);
        out = sdscatlen(out,"\n",1);
        break;
P
Pieter Noordhuis 已提交
415 416 417
    case REDIS_REPLY_STATUS:
    case REDIS_REPLY_STRING:
        out = sdscatlen(out,r->str,r->len);
A
antirez 已提交
418
        break;
P
Pieter Noordhuis 已提交
419 420
    case REDIS_REPLY_INTEGER:
        out = sdscatprintf(out,"%lld",r->integer);
A
antirez 已提交
421
        break;
P
Pieter Noordhuis 已提交
422 423 424 425 426 427 428
    case REDIS_REPLY_ARRAY:
        for (i = 0; i < r->elements; i++) {
            if (i > 0) out = sdscat(out,config.mb_delim);
            tmp = cliFormatReplyRaw(r->element[i]);
            out = sdscatlen(out,tmp,sdslen(tmp));
            sdsfree(tmp);
        }
A
antirez 已提交
429
        break;
P
Pieter Noordhuis 已提交
430 431 432 433 434 435 436 437
    default:
        fprintf(stderr,"Unknown reply type: %d\n", r->type);
        exit(1);
    }
    return out;
}

static int cliReadReply(int output_raw_strings) {
438
    void *_reply;
P
Pieter Noordhuis 已提交
439 440
    redisReply *reply;
    sds out;
441
    int output = 1;
P
Pieter Noordhuis 已提交
442

443
    if (redisGetReply(context,&_reply) != REDIS_OK) {
P
Pieter Noordhuis 已提交
444 445 446 447 448 449 450 451 452
        if (config.shutdown)
            return REDIS_OK;
        if (config.interactive) {
            /* Filter cases where we should reconnect */
            if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
                return REDIS_ERR;
            if (context->err == REDIS_ERR_EOF)
                return REDIS_ERR;
        }
453 454
        cliPrintContextError();
        exit(1);
P
Pieter Noordhuis 已提交
455
        return REDIS_ERR; /* avoid compiler warning */
I
ian 已提交
456
    }
P
Pieter Noordhuis 已提交
457

458
    reply = (redisReply*)_reply;
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

    /* Check if we need to connect to a different node and reissue the request. */
    if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR &&
        (!strncmp(reply->str,"MOVED",5) || !strcmp(reply->str,"ASK")))
    {
        char *p = reply->str, *s;
        int slot;

        output = 0;
        /* Comments show the position of the pointer as:
         *
         * [S] for pointer 's'
         * [P] for pointer 'p'
         */
        s = strchr(p,' ');      /* MOVED[S]3999 127.0.0.1:6381 */
        p = strchr(s+1,' ');    /* MOVED[S]3999[P]127.0.0.1:6381 */
        *p = '\0';
        slot = atoi(s+1);
        s = strchr(p+1,':');    /* MOVED 3999[P]127.0.0.1[S]6381 */
        *s = '\0';
        sdsfree(config.hostip);
        config.hostip = sdsnew(p+1);
        config.hostport = atoi(s+1);
        if (config.interactive)
            printf("-> Redirected to slot [%d] located at %s:%d\n",
                slot, config.hostip, config.hostport);
        config.cluster_reissue_command = 1;
    }

    if (output) {
        if (output_raw_strings) {
P
Pieter Noordhuis 已提交
490 491
            out = cliFormatReplyRaw(reply);
        } else {
492 493 494 495 496 497
            if (config.raw_output) {
                out = cliFormatReplyRaw(reply);
                out = sdscat(out,"\n");
            } else {
                out = cliFormatReplyTTY(reply,"");
            }
P
Pieter Noordhuis 已提交
498
        }
499 500
        fwrite(out,sdslen(out),1,stdout);
        sdsfree(out);
P
Pieter Noordhuis 已提交
501 502
    }
    freeReplyObject(reply);
P
Pieter Noordhuis 已提交
503
    return REDIS_OK;
I
ian 已提交
504 505
}

506
static int cliSendCommand(int argc, char **argv, int repeat) {
507
    char *command = argv[0];
P
Pieter Noordhuis 已提交
508
    size_t *argvlen;
P
Pieter Noordhuis 已提交
509
    int j, output_raw;
A
antirez 已提交
510

511 512 513 514 515
    if (!strcasecmp(command,"help") || !strcasecmp(command,"?")) {
        cliOutputHelp(--argc, ++argv);
        return REDIS_OK;
    }

516
    if (context == NULL) return REDIS_ERR;
A
antirez 已提交
517

A
antirez 已提交
518 519 520 521
    output_raw = 0;
    if (!strcasecmp(command,"info") ||
        (argc == 2 && !strcasecmp(command,"cluster") &&
                      (!strcasecmp(argv[1],"nodes") ||
A
antirez 已提交
522 523 524 525
                       !strcasecmp(argv[1],"info"))) ||
        (argc == 2 && !strcasecmp(command,"client") &&
                       !strcasecmp(argv[1],"list")))

A
antirez 已提交
526 527 528 529
    {
        output_raw = 1;
    }

530 531 532 533
    if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
    if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
    if (!strcasecmp(command,"subscribe") ||
        !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
A
antirez 已提交
534

P
Pieter Noordhuis 已提交
535 536 537 538
    /* Setup argument length */
    argvlen = malloc(argc*sizeof(size_t));
    for (j = 0; j < argc; j++)
        argvlen[j] = sdslen(argv[j]);
539

540
    while(repeat--) {
P
Pieter Noordhuis 已提交
541
        redisAppendCommandArgv(context,argc,(const char**)argv,argvlen);
542
        while (config.monitor_mode) {
P
Pieter Noordhuis 已提交
543
            if (cliReadReply(output_raw) != REDIS_OK) exit(1);
544
            fflush(stdout);
545 546
        }

547
        if (config.pubsub_mode) {
P
Pieter Noordhuis 已提交
548 549
            if (!config.raw_output)
                printf("Reading messages... (press Ctrl-C to quit)\n");
550
            while (1) {
P
Pieter Noordhuis 已提交
551
                if (cliReadReply(output_raw) != REDIS_OK) exit(1);
552 553 554
            }
        }

555 556
        if (cliReadReply(output_raw) != REDIS_OK) {
            free(argvlen);
P
Pieter Noordhuis 已提交
557
            return REDIS_ERR;
558 559
        } else {
            /* Store database number when SELECT was successfully executed. */
560
            if (!strcasecmp(command,"select") && argc == 2) {
561
                config.dbnum = atoi(argv[1]);
562 563
                cliRefreshPrompt();
            }
564
        }
565 566
        if (config.interval) usleep(config.interval);
        fflush(stdout); /* Make it grep friendly */
A
antirez 已提交
567
    }
568 569

    free(argvlen);
P
Pieter Noordhuis 已提交
570
    return REDIS_OK;
A
antirez 已提交
571 572
}

573 574 575 576
/*------------------------------------------------------------------------------
 * User interface
 *--------------------------------------------------------------------------- */

A
antirez 已提交
577 578 579 580 581
static int parseOptions(int argc, char **argv) {
    int i;

    for (i = 1; i < argc; i++) {
        int lastarg = i==argc-1;
582

A
antirez 已提交
583
        if (!strcmp(argv[i],"-h") && !lastarg) {
A
antirez 已提交
584
            sdsfree(config.hostip);
A
antirez 已提交
585
            config.hostip = sdsnew(argv[++i]);
A
antirez 已提交
586 587
        } else if (!strcmp(argv[i],"-h") && lastarg) {
            usage();
588 589
        } else if (!strcmp(argv[i],"--help")) {
            usage();
590 591
        } else if (!strcmp(argv[i],"-x")) {
            config.stdinarg = 1;
A
antirez 已提交
592
        } else if (!strcmp(argv[i],"-p") && !lastarg) {
A
antirez 已提交
593
            config.hostport = atoi(argv[++i]);
594
        } else if (!strcmp(argv[i],"-s") && !lastarg) {
A
antirez 已提交
595
            config.hostsocket = argv[++i];
596
        } else if (!strcmp(argv[i],"-r") && !lastarg) {
A
antirez 已提交
597
            config.repeat = strtoll(argv[++i],NULL,10);
598
        } else if (!strcmp(argv[i],"-i") && !lastarg) {
A
antirez 已提交
599
            double seconds = atof(argv[++i]);
600
            config.interval = seconds*1000000;
I
ian 已提交
601
        } else if (!strcmp(argv[i],"-n") && !lastarg) {
A
antirez 已提交
602
            config.dbnum = atoi(argv[++i]);
603
        } else if (!strcmp(argv[i],"-a") && !lastarg) {
A
antirez 已提交
604
            config.auth = argv[++i];
P
Pieter Noordhuis 已提交
605 606
        } else if (!strcmp(argv[i],"--raw")) {
            config.raw_output = 1;
A
antirez 已提交
607 608
        } else if (!strcmp(argv[i],"--latency")) {
            config.latency_mode = 1;
A
antirez 已提交
609 610
        } else if (!strcmp(argv[i],"--eval") && !lastarg) {
            config.eval = argv[++i];
611 612
        } else if (!strcmp(argv[i],"-c")) {
            config.cluster_mode = 1;
613 614
        } else if (!strcmp(argv[i],"-d") && !lastarg) {
            sdsfree(config.mb_delim);
A
antirez 已提交
615
            config.mb_delim = sdsnew(argv[++i]);
616 617 618 619
        } else if (!strcmp(argv[i],"-v") || !strcmp(argv[i], "--version")) {
            sds version = cliVersion();
            printf("redis-cli %s\n", version);
            sdsfree(version);
620
            exit(0);
A
antirez 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
        } else {
            break;
        }
    }
    return i;
}

static sds readArgFromStdin(void) {
    char buf[1024];
    sds arg = sdsempty();

    while(1) {
        int nread = read(fileno(stdin),buf,1024);

        if (nread == 0) break;
        else if (nread == -1) {
            perror("Reading from standard input");
            exit(1);
        }
        arg = sdscatlen(arg,buf,nread);
    }
    return arg;
}

A
antirez 已提交
645
static void usage() {
646 647 648 649 650 651 652 653 654 655
    sds version = cliVersion();
    fprintf(stderr,
"redis-cli %s\n"
"\n"
"Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]\n"
"  -h <hostname>    Server hostname (default: 127.0.0.1)\n"
"  -p <port>        Server port (default: 6379)\n"
"  -s <socket>      Server socket (overrides hostname and port)\n"
"  -a <password>    Password to use when connecting to the server\n"
"  -r <repeat>      Execute specified command N times\n"
656 657
"  -i <interval>    When -r is used, waits <interval> seconds per command.\n"
"                   It is possible to specify sub-second times like -i 0.1.\n"
658 659
"  -n <db>          Database number\n"
"  -x               Read last argument from STDIN\n"
660
"  -d <delimiter>   Multi-bulk delimiter in for raw formatting (default: \\n)\n"
661
"  -c               Enable cluster mode (follow -ASK and -MOVED redirections)\n"
P
Pieter Noordhuis 已提交
662
"  --raw            Use raw formatting for replies (default when STDOUT is not a tty)\n"
A
antirez 已提交
663
"  --latency        Enter a special mode continuously sampling latency.\n"
A
antirez 已提交
664
"  --eval <file>    Send an EVAL command using the Lua script at <file>.\n"
665 666 667 668 669 670 671
"  --help           Output this help and exit\n"
"  --version        Output version and exit\n"
"\n"
"Examples:\n"
"  cat /etc/passwd | redis-cli -x set mypasswd\n"
"  redis-cli get mypasswd\n"
"  redis-cli -r 100 lpush mylist x\n"
672
"  redis-cli -r 100 -i 1 info | grep used_memory_human:\n"
A
antirez 已提交
673 674
"  redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3\n"
"  (Note: when using --eval the comma separates KEYS[] from ARGV[] items)\n"
675 676 677 678 679 680
"\n"
"When no command is given, redis-cli starts in interactive mode.\n"
"Type \"help\" in interactive mode for information on available commands.\n"
"\n",
        version);
    sdsfree(version);
A
antirez 已提交
681 682 683
    exit(1);
}

684 685 686
/* Turn the plain C strings into Sds strings */
static char **convertToSds(int count, char** args) {
  int j;
687
  char **sds = zmalloc(sizeof(char*)*count);
688 689 690 691 692 693 694

  for(j = 0; j < count; j++)
    sds[j] = sdsnew(args[j]);

  return sds;
}

695
#define LINE_BUFLEN 4096
696
static void repl() {
697 698
    sds historyfile = NULL;
    int history = 0;
699
    char *line;
700
    int argc;
701
    sds *argv;
702

703
    config.interactive = 1;
704
    linenoiseSetCompletionCallback(completionCallback);
705

706 707 708 709 710 711 712 713 714 715
    /* Only use history when stdin is a tty. */
    if (isatty(fileno(stdin))) {
        history = 1;

        if (getenv("HOME") != NULL) {
            historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
            linenoiseHistoryLoad(historyfile);
        }
    }

716 717
    cliRefreshPrompt();
    while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
718
        if (line[0] != '\0') {
719
            argv = sdssplitargs(line,&argc);
720 721 722
            if (history) linenoiseHistoryAdd(line);
            if (historyfile) linenoiseHistorySave(historyfile);

723 724
            if (argv == NULL) {
                printf("Invalid argument(s)\n");
A
antirez 已提交
725
                free(line);
726 727
                continue;
            } else if (argc > 0) {
728 729
                if (strcasecmp(argv[0],"quit") == 0 ||
                    strcasecmp(argv[0],"exit") == 0)
730 731
                {
                    exit(0);
A
antirez 已提交
732 733 734 735 736
                } else if (argc == 3 && !strcasecmp(argv[0],"connect")) {
                    sdsfree(config.hostip);
                    config.hostip = sdsnew(argv[1]);
                    config.hostport = atoi(argv[2]);
                    cliConnect(1);
737 738
                } else if (argc == 1 && !strcasecmp(argv[0],"clear")) {
                    linenoiseClearScreen();
739
                } else {
740
                    long long start_time = mstime(), elapsed;
741
                    int repeat, skipargs = 0;
742

743
                    repeat = atoi(argv[0]);
744
                    if (argc > 1 && repeat) {
745 746 747 748 749
                        skipargs = 1;
                    } else {
                        repeat = 1;
                    }

750 751
                    while (1) {
                        config.cluster_reissue_command = 0;
752 753
                        if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
                            != REDIS_OK)
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
                        {
                            cliConnect(1);

                            /* If we still cannot send the command print error.
                             * We'll try to reconnect the next time. */
                            if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
                                != REDIS_OK)
                                cliPrintContextError();
                        }
                        /* Issue the command again if we got redirected in cluster mode */
                        if (config.cluster_mode && config.cluster_reissue_command) {
                            cliConnect(1);
                        } else {
                            break;
                        }
769
                    }
770
                    elapsed = mstime()-start_time;
P
Pieter Noordhuis 已提交
771 772 773
                    if (elapsed >= 500) {
                        printf("(%.2fs)\n",(double)elapsed/1000);
                    }
774
                }
775 776
            }
            /* Free the argument vector */
777
            while(argc--) sdsfree(argv[argc]);
778
            zfree(argv);
779
        }
780
        /* linenoise() returns malloc-ed lines like readline() */
781
        free(line);
782 783 784 785
    }
    exit(0);
}

786 787
static int noninteractive(int argc, char **argv) {
    int retval = 0;
788
    if (config.stdinarg) {
789 790 791 792 793 794 795 796 797 798
        argv = zrealloc(argv, (argc+1)*sizeof(char*));
        argv[argc] = readArgFromStdin();
        retval = cliSendCommand(argc+1, argv, config.repeat);
    } else {
        /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
        retval = cliSendCommand(argc, argv, config.repeat);
    }
    return retval;
}

A
antirez 已提交
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
static int evalMode(int argc, char **argv) {
    sds script = sdsempty();
    FILE *fp;
    char buf[1024];
    size_t nread;
    char **argv2;
    int j, got_comma = 0, keys = 0;

    /* Load the script from the file, as an sds string. */
    fp = fopen(config.eval,"r");
    if (!fp) {
        fprintf(stderr,
            "Can't open file '%s': %s\n", config.eval, strerror(errno));
        exit(1);
    }
    while((nread = fread(buf,1,sizeof(buf),fp)) != 0) {
        script = sdscatlen(script,buf,nread);
    }
    fclose(fp);

    /* Create our argument vector */
    argv2 = zmalloc(sizeof(sds)*(argc+3));
    argv2[0] = sdsnew("EVAL");
    argv2[1] = script;
    for (j = 0; j < argc; j++) {
        if (!got_comma && argv[j][0] == ',' && argv[j][1] == 0) {
            got_comma = 1;
            continue;
        }
        argv2[j+3-got_comma] = sdsnew(argv[j]);
        if (!got_comma) keys++;
    }
    argv2[2] = sdscatprintf(sdsempty(),"%d",keys);

    /* Call it */
    return cliSendCommand(argc+3-got_comma, argv2, config.repeat);
}

A
antirez 已提交
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
static void latencyMode(void) {
    redisReply *reply;
    long long start, latency, min, max, tot, count = 0;
    double avg;

    if (!context) exit(1);
    while(1) {
        start = mstime();
        reply = redisCommand(context,"PING");
        if (reply == NULL) {
            fprintf(stderr,"\nI/O error\n");
            exit(1);
        }
        latency = mstime()-start;
        freeReplyObject(reply);
        count++;
        if (count == 1) {
            min = max = tot = latency;
            avg = (double) latency;
        } else {
            if (latency < min) min = latency;
            if (latency > max) max = latency;
859
            tot += latency;
A
antirez 已提交
860 861 862 863 864 865 866 867 868
            avg = (double) tot/count;
        }
        printf("\x1b[0G\x1b[2Kmin: %lld, max: %lld, avg: %.2f (%lld samples)",
            min, max, avg, count);
        fflush(stdout);
        usleep(10000);
    }
}

A
antirez 已提交
869
int main(int argc, char **argv) {
870
    int firstarg;
A
antirez 已提交
871

A
antirez 已提交
872
    config.hostip = sdsnew("127.0.0.1");
A
antirez 已提交
873
    config.hostport = 6379;
874
    config.hostsocket = NULL;
875
    config.repeat = 1;
876
    config.interval = 0;
I
ian 已提交
877
    config.dbnum = 0;
878
    config.interactive = 0;
879
    config.shutdown = 0;
880 881
    config.monitor_mode = 0;
    config.pubsub_mode = 0;
A
antirez 已提交
882
    config.latency_mode = 0;
883
    config.cluster_mode = 0;
884
    config.stdinarg = 0;
A
antirez 已提交
885
    config.auth = NULL;
A
antirez 已提交
886
    config.eval = NULL;
P
Pieter Noordhuis 已提交
887 888
    config.raw_output = !isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL);
    config.mb_delim = sdsnew("\n");
889
    cliInitHelp();
890

A
antirez 已提交
891 892 893 894
    firstarg = parseOptions(argc,argv);
    argc -= firstarg;
    argv += firstarg;

A
antirez 已提交
895 896 897 898 899 900
    /* Start in latency mode if appropriate */
    if (config.latency_mode) {
        cliConnect(0);
        latencyMode();
    }

901
    /* Start interactive mode when no command is provided */
A
antirez 已提交
902
    if (argc == 0 && !config.eval) {
903 904 905 906 907 908
        /* Note that in repl mode we don't abort on connection error.
         * A new attempt will be performed for every command send. */
        cliConnect(0);
        repl();
    }

909
    /* Otherwise, we have some arguments to execute */
910
    if (cliConnect(0) != REDIS_OK) exit(1);
A
antirez 已提交
911 912 913 914 915
    if (config.eval) {
        return evalMode(argc,argv);
    } else {
        return noninteractive(argc,convertToSds(argc,argv));
    }
A
antirez 已提交
916
}