brpc_hulu_pbrpc_protocol_unittest.cpp 12.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

18
// brpc - A framework to host and access services throughout Baidu.
gejun's avatar
gejun committed
19 20 21 22 23 24 25 26 27

// Date: Sun Jul 13 15:04:18 CST 2014

#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <gtest/gtest.h>
#include <gflags/gflags.h>
#include <google/protobuf/descriptor.h>
28 29
#include "butil/time.h"
#include "butil/macros.h"
30
#include "butil/gperftools_profiler.h"
gejun's avatar
gejun committed
31 32 33 34 35 36 37
#include "brpc/socket.h"
#include "brpc/acceptor.h"
#include "brpc/server.h"
#include "brpc/policy/hulu_pbrpc_meta.pb.h"
#include "brpc/policy/hulu_pbrpc_protocol.h"
#include "brpc/policy/most_common_message.h"
#include "brpc/controller.h"
38
#include "echo.pb.h"
gejun's avatar
gejun committed
39 40 41

int main(int argc, char* argv[]) {
    testing::InitGoogleTest(&argc, argv);
42
    GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
gejun's avatar
gejun committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    return RUN_ALL_TESTS();
}

namespace {

static const std::string EXP_REQUEST = "hello";
static const std::string EXP_RESPONSE = "world";

static const std::string MOCK_CREDENTIAL = "mock credential";
static const std::string MOCK_USER = "mock user";

class MyAuthenticator : public brpc::Authenticator {
public:
    MyAuthenticator() {}

    int GenerateCredential(std::string* auth_str) const {
        *auth_str = MOCK_CREDENTIAL;
        return 0;
    }

    int VerifyCredential(const std::string& auth_str,
64
                         const butil::EndPoint&,
gejun's avatar
gejun committed
65 66 67 68 69 70 71 72 73 74 75 76 77 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 105 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 132 133 134 135 136 137 138 139 140 141 142 143
                         brpc::AuthContext* ctx) const {
        EXPECT_EQ(MOCK_CREDENTIAL, auth_str);
        ctx->set_user(MOCK_USER);
        return 0;
    }
};

class MyEchoService : public ::test::EchoService {
    void Echo(::google::protobuf::RpcController* cntl_base,
              const ::test::EchoRequest* req,
              ::test::EchoResponse* res,
              ::google::protobuf::Closure* done) {
        brpc::Controller* cntl =
            static_cast<brpc::Controller*>(cntl_base);
        brpc::ClosureGuard done_guard(done);

        if (req->close_fd()) {
            cntl->CloseConnection("Close connection according to request");
            return;
        }
        if (cntl->auth_context()) {
            EXPECT_EQ(MOCK_USER, cntl->auth_context()->user());
        }
        EXPECT_EQ(EXP_REQUEST, req->message());
        if (!cntl->request_attachment().empty()) {
            EXPECT_EQ(EXP_REQUEST, cntl->request_attachment().to_string());
            cntl->response_attachment().append(EXP_RESPONSE);
        }
        res->set_message(EXP_RESPONSE);
    }
};
    
class HuluTest : public ::testing::Test{
protected:
    HuluTest() {
        EXPECT_EQ(0, _server.AddService(
            &_svc, brpc::SERVER_DOESNT_OWN_SERVICE));
        // Hack: Regard `_server' as running 
        _server._status = brpc::Server::RUNNING;
        _server._options.auth = &_auth;
        
        EXPECT_EQ(0, pipe(_pipe_fds));

        brpc::SocketId id;
        brpc::SocketOptions options;
        options.fd = _pipe_fds[1];
        EXPECT_EQ(0, brpc::Socket::Create(options, &id));
        EXPECT_EQ(0, brpc::Socket::Address(id, &_socket));
    };

    virtual ~HuluTest() {};
    virtual void SetUp() {};
    virtual void TearDown() {};

    void VerifyMessage(brpc::InputMessageBase* msg) {
        if (msg->_socket == NULL) {
            _socket->ReAddress(&msg->_socket);
        }
        msg->_arg = &_server;
        EXPECT_TRUE(brpc::policy::VerifyHuluRequest(msg));
    }

    void ProcessMessage(void (*process)(brpc::InputMessageBase*),
                        brpc::InputMessageBase* msg, bool set_eof) {
        if (msg->_socket == NULL) {
            _socket.get()->ReAddress(&msg->_socket);
        }
        msg->_arg = &_server;
        _socket->PostponeEOF();
        if (set_eof) {
            _socket->SetEOF();
        }
        (*process)(msg);
    }

    brpc::policy::MostCommonMessage* MakeRequestMessage(
        const brpc::policy::HuluRpcRequestMeta& meta) {
        brpc::policy::MostCommonMessage* msg =
                brpc::policy::MostCommonMessage::Get();
144
        butil::IOBufAsZeroCopyOutputStream meta_stream(&msg->meta);
gejun's avatar
gejun committed
145 146 147 148
        EXPECT_TRUE(meta.SerializeToZeroCopyStream(&meta_stream));

        test::EchoRequest req;
        req.set_message(EXP_REQUEST);
149
        butil::IOBufAsZeroCopyOutputStream req_stream(&msg->payload);
gejun's avatar
gejun committed
150 151 152 153 154 155 156 157
        EXPECT_TRUE(req.SerializeToZeroCopyStream(&req_stream));
        return msg;
    }

    brpc::policy::MostCommonMessage* MakeResponseMessage(
        const brpc::policy::HuluRpcResponseMeta& meta) {
        brpc::policy::MostCommonMessage* msg =
                brpc::policy::MostCommonMessage::Get();
158
        butil::IOBufAsZeroCopyOutputStream meta_stream(&msg->meta);
gejun's avatar
gejun committed
159 160 161 162
        EXPECT_TRUE(meta.SerializeToZeroCopyStream(&meta_stream));

        test::EchoResponse res;
        res.set_message(EXP_RESPONSE);
163
        butil::IOBufAsZeroCopyOutputStream res_stream(&msg->payload);
gejun's avatar
gejun committed
164 165 166 167 168 169 170 171 172 173 174 175 176
        EXPECT_TRUE(res.SerializeToZeroCopyStream(&res_stream));
        return msg;
    }

    void CheckResponseCode(bool expect_empty, int expect_code) {
        int bytes_in_pipe = 0;
        ioctl(_pipe_fds[0], FIONREAD, &bytes_in_pipe);
        if (expect_empty) {
            EXPECT_EQ(0, bytes_in_pipe);
            return;
        }

        EXPECT_GT(bytes_in_pipe, 0);
177
        butil::IOPortal buf;
gejun's avatar
gejun committed
178 179 180 181 182 183 184 185
        EXPECT_EQ((ssize_t)bytes_in_pipe,
                  buf.append_from_file_descriptor(_pipe_fds[0], 1024));
        brpc::ParseResult pr = brpc::policy::ParseHuluMessage(&buf, NULL, false, NULL);
        EXPECT_EQ(brpc::PARSE_OK, pr.error());
        brpc::policy::MostCommonMessage* msg =
            static_cast<brpc::policy::MostCommonMessage*>(pr.message());

        brpc::policy::HuluRpcResponseMeta meta;
186
        butil::IOBufAsZeroCopyInputStream meta_stream(msg->meta);
gejun's avatar
gejun committed
187 188 189 190 191
        EXPECT_TRUE(meta.ParseFromZeroCopyStream(&meta_stream));
        EXPECT_EQ(expect_code, meta.error_code());
    }

    void TestHuluCompress(brpc::CompressType type) {
192 193
        butil::IOBuf request_buf;
        butil::IOBuf total_buf;
gejun's avatar
gejun committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
        brpc::Controller cntl;
        test::EchoRequest req;
        test::EchoResponse res;
        cntl._response = &res;

        req.set_message(EXP_REQUEST);
        cntl.set_request_compress_type(type);
        brpc::SerializeRequestDefault(&request_buf, &cntl, &req);
        ASSERT_FALSE(cntl.Failed());
        brpc::policy::PackHuluRequest(
            &total_buf, NULL, cntl.call_id().value,
            test::EchoService::descriptor()->method(0),
            &cntl, request_buf, &_auth);
        ASSERT_FALSE(cntl.Failed());

        brpc::ParseResult req_pr =
                brpc::policy::ParseHuluMessage(&total_buf, NULL, false, NULL);
        ASSERT_EQ(brpc::PARSE_OK, req_pr.error());
        brpc::InputMessageBase* req_msg = req_pr.message();
        ProcessMessage(brpc::policy::ProcessHuluRequest, req_msg, false);
        CheckResponseCode(false, 0);
    }

    int _pipe_fds[2];
    brpc::SocketUniquePtr _socket;
    brpc::Server _server;

    MyEchoService _svc;
    MyAuthenticator _auth;
};

TEST_F(HuluTest, process_request_failed_socket) {
    brpc::policy::HuluRpcRequestMeta meta;
    meta.set_service_name("EchoService");
    meta.set_method_index(0);
    brpc::policy::MostCommonMessage* msg = MakeRequestMessage(meta);
    _socket->SetFailed();
    ProcessMessage(brpc::policy::ProcessHuluRequest, msg, false);
232
    ASSERT_EQ(0ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
233 234 235 236 237 238 239 240 241 242
    CheckResponseCode(true, 0);
}

TEST_F(HuluTest, process_request_logoff) {
    brpc::policy::HuluRpcRequestMeta meta;
    meta.set_service_name("EchoService");
    meta.set_method_index(0);
    brpc::policy::MostCommonMessage* msg = MakeRequestMessage(meta);
    _server._status = brpc::Server::READY;
    ProcessMessage(brpc::policy::ProcessHuluRequest, msg, false);
243
    ASSERT_EQ(1ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
244 245 246 247 248 249 250 251 252
    CheckResponseCode(false, brpc::ELOGOFF);
}

TEST_F(HuluTest, process_request_wrong_method) {
    brpc::policy::HuluRpcRequestMeta meta;
    meta.set_service_name("EchoService");
    meta.set_method_index(10);
    brpc::policy::MostCommonMessage* msg = MakeRequestMessage(meta);
    ProcessMessage(brpc::policy::ProcessHuluRequest, msg, false);
253
    ASSERT_EQ(1ll, _server._nerror_bvar.get_value());
gejun's avatar
gejun committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    CheckResponseCode(false, brpc::ENOMETHOD);
}

TEST_F(HuluTest, process_response_after_eof) {
    brpc::policy::HuluRpcResponseMeta meta;
    test::EchoResponse res;
    brpc::Controller cntl;
    meta.set_correlation_id(cntl.call_id().value);
    cntl._response = &res;
    brpc::policy::MostCommonMessage* msg = MakeResponseMessage(meta);
    ProcessMessage(brpc::policy::ProcessHuluResponse, msg, true);
    ASSERT_EQ(EXP_RESPONSE, res.message());
    ASSERT_TRUE(_socket->Failed());
}

TEST_F(HuluTest, process_response_error_code) {
    const int ERROR_CODE = 12345;
    brpc::policy::HuluRpcResponseMeta meta;
    brpc::Controller cntl;
    meta.set_correlation_id(cntl.call_id().value);
    meta.set_error_code(ERROR_CODE);
    brpc::policy::MostCommonMessage* msg = MakeResponseMessage(meta);
    ProcessMessage(brpc::policy::ProcessHuluResponse, msg, false);
    ASSERT_EQ(ERROR_CODE, cntl.ErrorCode());
}

TEST_F(HuluTest, complete_flow) {
281 282
    butil::IOBuf request_buf;
    butil::IOBuf total_buf;
gejun's avatar
gejun committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    brpc::Controller cntl;
    test::EchoRequest req;
    test::EchoResponse res;
    cntl._response = &res;

    // Send request
    req.set_message(EXP_REQUEST);
    brpc::SerializeRequestDefault(&request_buf, &cntl, &req);
    ASSERT_FALSE(cntl.Failed());
    cntl.request_attachment().append(EXP_REQUEST);
    brpc::policy::PackHuluRequest(
        &total_buf, NULL, cntl.call_id().value,
        test::EchoService::descriptor()->method(0), &cntl, request_buf, &_auth);
    ASSERT_FALSE(cntl.Failed());

    // Verify and handle request
    brpc::ParseResult req_pr =
            brpc::policy::ParseHuluMessage(&total_buf, NULL, false, NULL);
    ASSERT_EQ(brpc::PARSE_OK, req_pr.error());
    brpc::InputMessageBase* req_msg = req_pr.message();
    VerifyMessage(req_msg);
    ProcessMessage(brpc::policy::ProcessHuluRequest, req_msg, false);

    // Read response from pipe
307
    butil::IOPortal response_buf;
gejun's avatar
gejun committed
308 309 310 311 312 313 314 315 316 317 318 319
    response_buf.append_from_file_descriptor(_pipe_fds[0], 1024);
    brpc::ParseResult res_pr =
            brpc::policy::ParseHuluMessage(&response_buf, NULL, false, NULL);
    ASSERT_EQ(brpc::PARSE_OK, res_pr.error());
    brpc::InputMessageBase* res_msg = res_pr.message();
    ProcessMessage(brpc::policy::ProcessHuluResponse, res_msg, false);

    ASSERT_FALSE(cntl.Failed());
    ASSERT_EQ(EXP_RESPONSE, res.message());
}

TEST_F(HuluTest, close_in_callback) {
320 321
    butil::IOBuf request_buf;
    butil::IOBuf total_buf;
gejun's avatar
gejun committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    brpc::Controller cntl;
    test::EchoRequest req;

    // Send request
    req.set_message(EXP_REQUEST);
    req.set_close_fd(true);
    brpc::SerializeRequestDefault(&request_buf, &cntl, &req);
    ASSERT_FALSE(cntl.Failed());
    brpc::policy::PackHuluRequest(
        &total_buf, NULL, cntl.call_id().value,
        test::EchoService::descriptor()->method(0), &cntl, request_buf, &_auth);
    ASSERT_FALSE(cntl.Failed());

    // Handle request
    brpc::ParseResult req_pr =
            brpc::policy::ParseHuluMessage(&total_buf, NULL, false, NULL);
    ASSERT_EQ(brpc::PARSE_OK, req_pr.error());
    brpc::InputMessageBase* req_msg = req_pr.message();
    ProcessMessage(brpc::policy::ProcessHuluRequest, req_msg, false);

    // Socket should be closed
    ASSERT_TRUE(_socket->Failed());
}

TEST_F(HuluTest, hulu_compress) {
    TestHuluCompress(brpc::COMPRESS_TYPE_SNAPPY);
    TestHuluCompress(brpc::COMPRESS_TYPE_GZIP);
    TestHuluCompress(brpc::COMPRESS_TYPE_ZLIB);
}
} //namespace