redis_cli.cpp 5.27 KB
Newer Older
gejun's avatar
gejun committed
1
// Copyright (c) 2014 Baidu, Inc.
gejun's avatar
gejun committed
2 3 4 5 6 7 8 9 10 11 12 13
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
gejun's avatar
gejun committed
14

gejun's avatar
gejun committed
15
// A brpc based command-line interface to talk with redis-server
gejun's avatar
gejun committed
16

17
#include <signal.h>
gejun's avatar
gejun committed
18 19 20 21
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <gflags/gflags.h>
22
#include <butil/logging.h>
gejun's avatar
gejun committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#include <brpc/channel.h>
#include <brpc/redis.h>

DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(server, "127.0.0.1:6379", "IP Address of server");
DEFINE_int32(timeout_ms, 1000, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)"); 

namespace brpc {
const char* logo();
}

// Send `command' to redis-server via `channel'
static bool access_redis(brpc::Channel& channel, const char* command) {
    brpc::RedisRequest request;
    if (!request.AddCommand(command)) {
        LOG(ERROR) << "Fail to add command";
        return false;
    }
    brpc::RedisResponse response;
    brpc::Controller cntl;
    channel.CallMethod(NULL, &cntl, &request, &response, NULL);
    if (cntl.Failed()) {
        LOG(ERROR) << "Fail to access redis, " << cntl.ErrorText();
        return false;
    } else {
        std::cout << response << std::endl;
        return true;
    }
}

// For freeing the memory returned by readline().
struct Freer {
    void operator()(char* mem) {
        free(mem);
    }
};

static void dummy_handler(int) {}

// The getc for readline. The default getc retries reading when meeting
// EINTR, which is not what we want.
static bool g_canceled = false;
static int cli_getc(FILE *stream) {
    int c = getc(stream);
    if (c == EOF && errno == EINTR) {
        g_canceled = true;
        return '\n';
    }
    return c;
}

int main(int argc, char* argv[]) {
    // Parse gflags. We recommend you to use gflags as well.
77
    GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
gejun's avatar
gejun committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

    // A Channel represents a communication line to a Server. Notice that 
    // Channel is thread-safe and can be shared by all threads in your program.
    brpc::Channel channel;
    
    // Initialize the channel, NULL means using default options.
    brpc::ChannelOptions options;
    options.protocol = brpc::PROTOCOL_REDIS;
    options.connection_type = FLAGS_connection_type;
    options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
    options.max_retry = FLAGS_max_retry;
    if (channel.Init(FLAGS_server.c_str(), &options) != 0) {
        LOG(ERROR) << "Fail to initialize channel";
        return -1;
    }

    if (argc <= 1) {  // interactive mode
        // We need this dummy signal hander to interrupt getc (and returning
        // EINTR), SIG_IGN did not work.
        signal(SIGINT, dummy_handler);
        
        // Hook getc of readline.
        rl_getc_function = cli_getc;

        // Print welcome information.
        printf("%s\n", brpc::logo());
        printf("This command-line tool mimics the look-n-feel of official "
gejun's avatar
gejun committed
105
               "redis-cli, as a demostration of brpc's capability of"
gejun's avatar
gejun committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
               " talking to redis-server. The output and behavior is "
               "not exactly same with the official one.\n\n");

        for (;;) {
            char prompt[64];
            snprintf(prompt, sizeof(prompt), "redis %s> ", FLAGS_server.c_str());
            std::unique_ptr<char, Freer> command(readline(prompt));
            if (command == NULL || *command == '\0') {
                if (g_canceled) {
                    // No input after the prompt and user pressed Ctrl-C,
                    // quit the CLI.
                    return 0;
                }
                // User entered an empty command by just pressing Enter.
                continue;
            }
            if (g_canceled) {
                // User entered sth. and pressed Ctrl-C, start a new prompt.
                g_canceled = false;
                continue;
            }
            // Add user's command to history so that it's browse-able by
            // UP-key and search-able by Ctrl-R.
            add_history(command.get());

            if (!strcmp(command.get(), "help")) {
gejun's avatar
gejun committed
132
                printf("This is a redis CLI written in brpc.\n");
gejun's avatar
gejun committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
                continue;
            }
            if (!strcmp(command.get(), "quit")) {
                // Although quit is a valid redis command, it does not make
                // too much sense to run it in this CLI, just quit.
                return 0;
            }
            access_redis(channel, command.get());
        }
    } else {
        std::string command;
        command.reserve(argc * 16);
        for (int i = 1; i < argc; ++i) {
            if (i != 1) {
                command.push_back(' ');
            }
            command.append(argv[i]);
        }
        if (!access_redis(channel, command.c_str())) {
            return -1;
        }
    }
    return 0;
}