pdclient.cpp 16.0 KB
Newer Older
W
wangguibao 已提交
1 2 3 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 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 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 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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
// Copyright (c) 2014 baidu-rpc authors.
// 
// 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.

// A client sending requests to server every 1 second.
//
#include <fstream>

#include "dense_service.pb.h"
#include "image_classification.pb.h"
#include "sparse_service.pb.h"
#include "int64tensor_service.pb.h"

#include "common/utils.h"
#include "common/inner_common.h"
#include "common/constant.h"
#include "framework/logger.h"

DEFINE_string(attachment, "foo", "Carry this along with requests");
DEFINE_bool(auth, false, "Enable Giano authentication");
DEFINE_string(auth_group, "g_guest", "Giano Group");
DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in protocol/baidu/rpc/options.proto");
DEFINE_bool(compress, true, "Enable compression");
//DEFINE_string(protocol, "http", "Protocol type. Defined in protocol/baidu/rpc/options.proto");
DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(server, "0.0.0.0:8010", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 100, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)"); 
DEFINE_int32(interval_ms, 1000, "Milliseconds between consecutive requests");
DEFINE_string(http_content_type, "application/json", "Content type of http request");

using baidu::paddle_serving::predictor::FLAGS_logger_path;
using baidu::paddle_serving::predictor::FLAGS_logger_file;
using baidu::paddle_serving::predictor::LoggerWrapper;

namespace dense_format {

using baidu::paddle_serving::predictor::dense_service::BuiltinDenseFormatService_Stub;
using baidu::paddle_serving::predictor::dense_service::Request;
using baidu::paddle_serving::predictor::dense_service::Response;

using baidu::paddle_serving::predictor::format::DenseInstance;
using baidu::paddle_serving::predictor::format::DensePrediction;

void send_dense_format(BuiltinDenseFormatService_Stub& stub, int log_id) {
    baidu::rpc::Controller cntl;

    // We will receive response synchronously, safe to put variables
    // on stack.
    baidu::paddle_serving::predictor::TimerFlow timer("dense");

    Request dense_request;
    Response dense_response;

    // set request header
    DenseInstance* ins = NULL;
    ins = dense_request.mutable_instances()->Add();
    ins->add_features(1.5);
    ins->add_features(16.0);
    ins->add_features(14.0);
    ins->add_features(23.0);

    timer.check("fill");

    cntl.set_log_id(log_id ++);  // set by user
    if (FLAGS_protocol != "http" && FLAGS_protocol != "h2c")  {
        // Set attachment which is wired to network directly instead of 
        // being serialized into protobuf messages.
        cntl.request_attachment().append(FLAGS_attachment);
    } else {
        cntl.http_request().set_content_type(FLAGS_http_content_type);
    }

    if (FLAGS_compress) {
        cntl.set_request_compress_type(baidu::rpc::COMPRESS_TYPE_SNAPPY);
    }

    timer.check("compress");

    // Because `done'(last parameter) is NULL, this function waits until
    // the response comes back or error occurs(including timedout).
    stub.debug(&cntl, &dense_request, &dense_response, NULL);

    timer.check("inference");
    if (!cntl.Failed()) {
        if (cntl.response_attachment().empty()) {
            LOG(INFO) << "Received response from " << cntl.remote_side()
                      << " to " << cntl.local_side()
                      << ": " << dense_response.ShortDebugString()
                      << " latency=" << cntl.latency_us() << "us" << noflush;
        } else {
            LOG(INFO) << "Received response from " << cntl.remote_side()
                      << " to " << cntl.local_side()
                      << ": " << dense_response.ShortDebugString()
                      << " (attached=" << cntl.response_attachment() << ")"
                      << " latency=" << cntl.latency_us() << "us " << noflush;
        }
    } else {
        LOG(WARNING) << cntl.ErrorText();
    }
    timer.check("dump");
}
} // namespace dense_format


namespace sparse_format {

using baidu::paddle_serving::predictor::sparse_service::BuiltinSparseFormatService_Stub;
using baidu::paddle_serving::predictor::sparse_service::Request;
using baidu::paddle_serving::predictor::sparse_service::Response;

using baidu::paddle_serving::predictor::format::SparseInstance;
using baidu::paddle_serving::predictor::format::SparsePrediction;

void send_sparse_format(BuiltinSparseFormatService_Stub& stub, int log_id) {
    baidu::rpc::Controller cntl;

    // We will receive response synchronously, safe to put variables
    // on stack.
    baidu::paddle_serving::predictor::TimerFlow timer("sparse");

    Request sparse_request;
    Response sparse_response;

    // set request body
    SparseInstance* ins = NULL;
    ins = sparse_request.mutable_instances()->Add();
    ins->add_keys(26);
    ins->add_keys(182);
    ins->add_keys(232);
    ins->add_keys(243);
    ins->add_keys(431);

    ins->add_shape(2000);

    ins->add_values(1);
    ins->add_values(1);
    ins->add_values(1);
    ins->add_values(4);
    ins->add_values(14);

    ins = sparse_request.mutable_instances()->Add();
    ins->add_keys(0);
    ins->add_keys(182);
    ins->add_keys(232);
    ins->add_keys(243);
    ins->add_keys(431);

    ins->add_shape(2000);

    ins->add_values(13);
    ins->add_values(1);
    ins->add_values(1);
    ins->add_values(4);
    ins->add_values(1);

    timer.check("fill");

    cntl.set_log_id(log_id ++);  // set by user
    if (FLAGS_protocol != "http" && FLAGS_protocol != "h2c")  {
        // Set attachment which is wired to network directly instead of 
        // being serialized into protobuf messages.
        cntl.request_attachment().append(FLAGS_attachment);
    } else {
        cntl.http_request().set_content_type(FLAGS_http_content_type);
    }

    if (FLAGS_compress) {
        cntl.set_request_compress_type(baidu::rpc::COMPRESS_TYPE_SNAPPY);
    }

    timer.check("compress");

    // Because `done'(last parameter) is NULL, this function waits until
    // the response comes back or error occurs(including timedout).
    stub.inference(&cntl, &sparse_request, &sparse_response, NULL);

    timer.check("inference");
    if (!cntl.Failed()) {
        if (cntl.response_attachment().empty()) {
            LOG(INFO) << "Received response from " << cntl.remote_side()
                      << " to " << cntl.local_side()
                      << ": " << sparse_response.ShortDebugString()
                      << " latency=" << cntl.latency_us() << "us" << noflush;
        } else {
            LOG(INFO) << "Received response from " << cntl.remote_side()
                      << " to " << cntl.local_side()
                      << ": " << sparse_response.ShortDebugString()
                      << " (attached=" << cntl.response_attachment() << ")"
                      << " latency=" << cntl.latency_us() << "us" << noflush;
        }
    } else {
        LOG(WARNING) << cntl.ErrorText();
    }
    timer.check("dump");
}
}

namespace fluid_format {

using baidu::paddle_serving::predictor::int64tensor_service::BuiltinFluidService_Stub;
using baidu::paddle_serving::predictor::int64tensor_service::Request;
using baidu::paddle_serving::predictor::int64tensor_service::Response;

using baidu::paddle_serving::predictor::format::Int64TensorInstance;
using baidu::paddle_serving::predictor::format::Float32TensorPredictor;

void send_fluid_format(BuiltinFluidService_Stub& stub, int log_id) {
    baidu::rpc::Controller cntl;

    // We will receive response synchronously, safe to put variables
    // on stack.
    baidu::paddle_serving::predictor::TimerFlow timer("fluid");

    Request fluid_request;
    Response fluid_response;

    // set request header
    Int64TensorInstance* ins = NULL;
    ins = fluid_request.mutable_instances()->Add();
    ins->add_data(15);
    ins->add_data(160);
    ins->add_data(14);
    ins->add_data(23);
    ins->add_data(18);
    ins->add_data(39);
    ins->add_shape(2);
    ins->add_shape(3);

    timer.check("fill");

    cntl.set_log_id(log_id);  // set by user
    if (FLAGS_protocol != "http" && FLAGS_protocol != "h2c")  {
        // Set attachment which is wired to network directly instead of 
        // being serialized into protobuf messages.
        cntl.request_attachment().append(FLAGS_attachment);
    } else {
        cntl.http_request().set_content_type(FLAGS_http_content_type);
    }

    if (FLAGS_compress) {
        cntl.set_request_compress_type(baidu::rpc::COMPRESS_TYPE_SNAPPY);
    }

    timer.check("compress");

    // Because `done'(last parameter) is NULL, this function waits until
    // the response comes back or error occurs(including timedout).
    stub.debug(&cntl, &fluid_request, &fluid_response, NULL);

    timer.check("inference");
    if (!cntl.Failed()) {
        if (cntl.response_attachment().empty()) {
            LOG(INFO) << "Received response from " << cntl.remote_side()
                      << " to " << cntl.local_side()
                      << ": " << fluid_response.ShortDebugString()
                      << " latency=" << cntl.latency_us() << "us" << noflush;
        } else {
            LOG(INFO) << "Received response from " << cntl.remote_side()
                      << " to " << cntl.local_side()
                      << ": " << fluid_response.ShortDebugString()
                      << " (attached=" << cntl.response_attachment() << ")"
                      << " latency=" << cntl.latency_us() << "us " << noflush;
        }
    } else {
        LOG(WARNING) << cntl.ErrorText();
    }
    timer.check("dump");
}
} // namespace fluid_format

namespace ximage_format {

char* g_image_buffer = NULL;
size_t g_image_size = 0;
std::string g_image_path = "./data/images/what.jpg";

using baidu::paddle_serving::predictor::image_classification::ImageClassifyService_Stub;
using baidu::paddle_serving::predictor::image_classification::Request;
using baidu::paddle_serving::predictor::image_classification::Response;

using baidu::paddle_serving::predictor::format::XImageReqInstance;
using baidu::paddle_serving::predictor::format::XImageResInstance;

void send_ximage_format(ImageClassifyService_Stub& stub, int log_id) {
    baidu::rpc::Controller cntl;

    // We will receive response synchronously, safe to put variables
    // on stack.
    baidu::paddle_serving::predictor::TimerFlow timer("ximage");

    Request ximage_request;
    Response ximage_response;

    // set request header
    std::ifstream fin(g_image_path.c_str(), std::ios::binary);
    fin.seekg(0, std::ios::end);
    int isize = fin.tellg();
    if (g_image_size < isize || !g_image_buffer) {
        g_image_buffer = new (std::nothrow) char[isize];
        g_image_size = isize;
    }

    fin.seekg(0, std::ios::beg);  
    fin.read(g_image_buffer, sizeof(char) * isize);  
    fin.close();

    timer.check("read");

    XImageReqInstance* ins = ximage_request.mutable_instances()->Add();
    ins->set_image_binary(g_image_buffer, isize);
    ins->set_image_length(isize);
    timer.check("fill");

    cntl.set_log_id(log_id ++);  // set by user
    if (FLAGS_protocol != "http" && FLAGS_protocol != "h2c")  {
        // Set attachment which is wired to network directly instead of 
        // being serialized into protobuf messages.
        cntl.request_attachment().append(FLAGS_attachment);
    } else {
        cntl.http_request().set_content_type(FLAGS_http_content_type);
    }

    if (FLAGS_compress) {
        cntl.set_request_compress_type(baidu::rpc::COMPRESS_TYPE_SNAPPY);
    }

    timer.check("compress");

    // Because `done'(last parameter) is NULL, this function waits until
    // the response comes back or error occurs(including timedout).
    stub.inference(&cntl, &ximage_request, &ximage_response, NULL);
    timer.check("inference");
    if (!cntl.Failed()) {
        if (cntl.response_attachment().empty()) {
            LOG(INFO) << "Received response from " << cntl.remote_side()
                      << " to " << cntl.local_side()
                      << ": " << ximage_response.ShortDebugString()
                      << " latency=" << cntl.latency_us() << "us" << noflush;
        } else {
            LOG(INFO) << "Received response from " << cntl.remote_side()
                      << " to " << cntl.local_side()
                      << ": " << ximage_response.ShortDebugString()
                      << " (attached=" << cntl.response_attachment() << ")"
                      << " latency=" << cntl.latency_us() << "us " << noflush;
        }
    } else {
        LOG(WARNING) << cntl.ErrorText();
    }
    timer.check("dump");
    if (g_image_buffer) {
        delete[] g_image_buffer;
        g_image_buffer = NULL;
    }

}
} // namespace ximage_format

int main(int argc, char* argv[]) {
    // Parse gflags. We recommend you to use gflags as well.
    google::ParseCommandLineFlags(&argc, &argv, true);

    // initialize logger instance
    if (LoggerWrapper::instance().initialize(
                FLAGS_logger_path, FLAGS_logger_file) != 0) {
        LOG(ERROR) << "Failed initialize logger, conf:" 
            << FLAGS_logger_path << "/" << FLAGS_logger_file;
        return -1;
    }
    
    // Login to get `CredentialGenerator' (see baas-lib-c/baas.h for more
    // information) and then pass it to `GianoAuthenticator'. 
    std::unique_ptr<baidu::rpc::policy::GianoAuthenticator> auth;
    if (FLAGS_auth) {
        if (baas::BAAS_Init() != 0) {
            LOG(ERROR) << "Fail to init BAAS";
            return -1;
        }
        baas::CredentialGenerator gen = baas::ClientUtility::Login(FLAGS_auth_group);
        auth.reset(new baidu::rpc::policy::GianoAuthenticator(&gen, NULL));
    }

    // 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.
    baidu::rpc::Channel channel;
    
    // Initialize the channel, NULL means using default options.
    baidu::rpc::ChannelOptions options;
    options.protocol = FLAGS_protocol;
    options.connection_type = FLAGS_connection_type;
    options.auth = auth.get();
    options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
    options.max_retry = FLAGS_max_retry;
    if (channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) {
        LOG(ERROR) << "Fail to initialize channel";
        return -1;
    }

    // Normally, you should not call a Channel directly, but instead construct
    // a stub Service wrapping it. stub can be shared by all threads as well.
    baidu::paddle_serving::predictor::sparse_service::BuiltinSparseFormatService_Stub
        stub1(&channel);

    baidu::paddle_serving::predictor::dense_service::BuiltinDenseFormatService_Stub
        stub2(&channel);

    baidu::paddle_serving::predictor::int64tensor_service::BuiltinFluidService_Stub
        stub3(&channel);

    baidu::paddle_serving::predictor::image_classification::ImageClassifyService_Stub
        stub4(&channel);

    // Send a request and wait for the response every 1 second.
    int log_id = 0;
    while (!baidu::rpc::IsAskedToQuit()) {
        // We will receive response synchronously, safe to put variables
        // on stack.
        log_id++;
        sparse_format::send_sparse_format(stub1, log_id);
        usleep(FLAGS_interval_ms * 1000L);
        log_id++;
        dense_format::send_dense_format(stub2, log_id);
        usleep(FLAGS_interval_ms * 1000L);
        //log_id++;
        //fluid_format::send_fluid_format(stub3, log_id);
        //usleep(FLAGS_interval_ms * 1000L);
        log_id++;
        ximage_format::send_ximage_format(stub4, log_id);
        usleep(FLAGS_interval_ms * 1000L);
    }

    LOG(INFO) << "Pdserving Client is going to quit";
    return 0;
}