stub_impl.h 8.8 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// 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.

#pragma once
#include <map>
#include <string>
#include <utility>
#include <vector>
G
guru4elephant 已提交
20 21 22 23
#include "core/sdk-cpp/include/common.h"
#include "core/sdk-cpp/include/endpoint_config.h"
#include "core/sdk-cpp/include/predictor.h"
#include "core/sdk-cpp/include/stub.h"
W
sdk-cpp  
wangguibao 已提交
24 25 26 27 28

namespace baidu {
namespace paddle_serving {
namespace sdk_cpp {

W
wangguibao 已提交
29 30
static const char* AVG_PREFIX = "avg_";
static const char* LTC_PREFIX = "ltc_";
W
sdk-cpp  
wangguibao 已提交
31 32

class Predictor;
W
wangguibao 已提交
33
template <typename T>
W
sdk-cpp  
wangguibao 已提交
34 35 36 37 38 39
class PredictorImpl;

static const char* INFERENCE_METHOD_NAME = "inference";
static const char* DEBUG_METHOD_NAME = "debug";

class MetricScope {
W
wangguibao 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 public:
  MetricScope(Stub* stub, const char* routine)
      : _stub(stub), _tt(butil::Timer::STARTED), _routine(routine) {
    TRACEPRINTF("enter %s", routine);
  }

  ~MetricScope() {
    TRACEPRINTF("exit %s", _routine.c_str());
    _tt.stop();
    _stub->update_latency(_tt.u_elapsed(), _routine.c_str());
  }

 private:
  Stub* _stub;
  butil::Timer _tt;
  std::string _routine;
W
sdk-cpp  
wangguibao 已提交
56 57 58
};

class TracePackScope {
W
wangguibao 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
 public:
  explicit TracePackScope(const char* routine) : _routine(routine), _index(-1) {
    TRACEPRINTF("start pack: %s", routine);
  }

  TracePackScope(const char* routine, int index)
      : _routine(routine), _index(index) {
    TRACEPRINTF("start pack: %s, index: %d", routine, index);
  }

  ~TracePackScope() {
    if (_index >= 0) {
      TRACEPRINTF("finish pack: %s, index: %d", _routine.c_str(), _index);
    } else {
      TRACEPRINTF("finish pack: %s", _routine.c_str());
W
sdk-cpp  
wangguibao 已提交
74
    }
W
wangguibao 已提交
75
  }
W
sdk-cpp  
wangguibao 已提交
76

W
wangguibao 已提交
77 78 79
 private:
  std::string _routine;
  int _index;
W
sdk-cpp  
wangguibao 已提交
80 81 82
};

class TagFilter : public brpc::NamingServiceFilter {
W
wangguibao 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
 public:
  class TagHelper {
   public:
    explicit TagHelper(const std::string& kv_str) {
      if (kv_str.compare("") == 0) {
        return;
      }

      static const char TAG_DELIM = ',';
      static const char KV_DELIM = ':';

      std::string::size_type start_pos = 0;
      std::string::size_type end_pos;

      do {
        end_pos = kv_str.find(TAG_DELIM, start_pos);
        std::string kv_pair_str;
        if (end_pos == std::string::npos) {
          kv_pair_str = kv_str.substr(start_pos);
        } else {
          kv_pair_str = kv_str.substr(start_pos, end_pos - start_pos);
          start_pos = end_pos + 1;
W
sdk-cpp  
wangguibao 已提交
105 106
        }

W
wangguibao 已提交
107 108 109 110
        std::string::size_type kv_delim_pos = kv_pair_str.find(KV_DELIM, 0);
        if (kv_delim_pos == std::string::npos) {
          LOG(ERROR) << "invalid kv pair: " << kv_pair_str.c_str();
          continue;
W
sdk-cpp  
wangguibao 已提交
111 112
        }

W
wangguibao 已提交
113 114 115 116
        std::string key = kv_pair_str.substr(0, kv_delim_pos);
        std::string value = kv_pair_str.substr(kv_delim_pos + 1);
        _kv_map.insert(std::pair<std::string, std::string>(key, value));
      } while (end_pos != std::string::npos);
W
sdk-cpp  
wangguibao 已提交
117 118
    }

W
wangguibao 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131
    bool container(const std::string& k, const std::string& v) const {
      std::map<std::string, std::string>::const_iterator found =
          _kv_map.find(k);
      if (found == _kv_map.end()) {
        // key not found
        return false;
      }

      if (v.compare(found->second) != 0) {
        // value not equals
        return false;
      }
      return true;
W
sdk-cpp  
wangguibao 已提交
132 133
    }

W
wangguibao 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
   private:
    std::map<std::string, std::string> _kv_map;
  };

  TagFilter(const std::string& key, const std::string& val) {
    _key = key;
    _value = val;
  }

  bool Accept(const brpc::ServerNode& server) const {
    TagHelper helper(server.tag);
    return helper.container(_key, _value);
  }

 private:
  std::string _key;
  std::string _value;
W
sdk-cpp  
wangguibao 已提交
151 152 153
};

class BvarWrapper {
W
wangguibao 已提交
154 155 156
 public:
  virtual void update_latency(int64_t acc) = 0;
  virtual void update_average(int64_t acc) = 0;
W
sdk-cpp  
wangguibao 已提交
157 158 159
};

class LatencyWrapper : public BvarWrapper {
W
wangguibao 已提交
160 161
 public:
  explicit LatencyWrapper(const std::string& name) : _ltc(name + "_ltc") {}
W
sdk-cpp  
wangguibao 已提交
162

W
wangguibao 已提交
163
  void update_latency(int64_t acc) { _ltc << acc; }
W
sdk-cpp  
wangguibao 已提交
164

W
wangguibao 已提交
165 166 167
  void update_average(int64_t acc) {
    LOG(ERROR) << "Cannot update average to a LatencyRecorder";
  }
W
sdk-cpp  
wangguibao 已提交
168

W
wangguibao 已提交
169 170
 private:
  bvar::LatencyRecorder _ltc;
W
sdk-cpp  
wangguibao 已提交
171 172 173
};

class AverageWrapper : public BvarWrapper {
W
wangguibao 已提交
174 175 176
 public:
  explicit AverageWrapper(const std::string& name)
      : _win(name + "_avg", &_avg, ::bvar::FLAGS_bvar_dump_interval) {}
W
sdk-cpp  
wangguibao 已提交
177

W
wangguibao 已提交
178 179 180
  void update_latency(int64_t acc) {
    LOG(ERROR) << "Cannot update latency to a AverageWrapper";
  }
W
sdk-cpp  
wangguibao 已提交
181

W
wangguibao 已提交
182
  void update_average(int64_t acc) { _avg << acc; }
W
sdk-cpp  
wangguibao 已提交
183

W
wangguibao 已提交
184 185 186
 private:
  bvar::IntRecorder _avg;
  bvar::Window<bvar::IntRecorder> _win;
W
sdk-cpp  
wangguibao 已提交
187 188 189
};

struct StubTLS {
W
wangguibao 已提交
190 191 192 193 194 195 196 197 198
  StubTLS() {
    predictor_pools.clear();
    request_pools.clear();
    response_pools.clear();
  }

  std::vector<Predictor*> predictor_pools;
  std::vector<google::protobuf::Message*> request_pools;
  std::vector<google::protobuf::Message*> response_pools;
W
sdk-cpp  
wangguibao 已提交
199 200
};

W
wangguibao 已提交
201
template <typename T, typename C, typename R, typename I, typename O>
W
sdk-cpp  
wangguibao 已提交
202
class StubImpl : public Stub {
W
wangguibao 已提交
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
 public:
  typedef google::protobuf::Message Message;

  StubImpl()
      : _channel(NULL),
        _pchannel(NULL),
        _gchannel(NULL),
        _service_stub(NULL),
        _infer(NULL),
        _debug(NULL) {}
  ~StubImpl() {}

  int initialize(const VariantInfo& var,
                 const std::string& ep,
                 const std::string* tag,
                 const std::string* tag_value);

  Predictor* fetch_predictor();
  int return_predictor(Predictor* predictor);
  int return_predictor(Predictor* predictor) const;

  Message* fetch_request();
  int return_request(Message* request);
  int return_request(Message* request) const;

  Message* fetch_response();
  int return_response(Message* response);
  int return_response(Message* response) const;

  int thrd_initialize();
  int thrd_clear();
  int thrd_finalize();

  const std::string& which_endpoint() const { return _endpoint; }

 private:
  google::protobuf::RpcChannel* init_channel(
      const VariantInfo& var, brpc::NamingServiceFilter* filter = NULL);

  brpc::ParallelChannel* init_pchannel(brpc::Channel* sub_channel,
                                       uint32_t channel_count,
                                       uint32_t package_size,
                                       const brpc::ChannelOptions& options);

  StubTLS* get_tls() {
    return static_cast<StubTLS*>(bthread_getspecific(_bthread_key));
  }

 private:
  brpc::Channel* _channel;
  brpc::ParallelChannel* _pchannel;
  google::protobuf::RpcChannel* _gchannel;
  T* _service_stub;
  const google::protobuf::MethodDescriptor* _infer;
  const google::protobuf::MethodDescriptor* _debug;
  std::string _endpoint;
  RpcParameters _options;
  std::string _tag;
  uint32_t _max_channel;
  uint32_t _package_size;

  // tls handlers
  bthread_key_t _bthread_key;

  // bvar variables
  std::map<std::string, BvarWrapper*> _ltc_bvars;
  std::map<std::string, BvarWrapper*> _avg_bvars;
  mutable butil::Mutex _bvar_mutex;
W
sdk-cpp  
wangguibao 已提交
271 272

#ifndef DECLARE_LATENCY
W
wangguibao 已提交
273
#define DECLARE_LATENCY(item) LatencyWrapper* _ltc_##item;
W
sdk-cpp  
wangguibao 已提交
274 275
#endif

W
wangguibao 已提交
276 277 278 279 280 281 282 283 284 285
  DECLARE_LATENCY(infer_sync);    // 同步请求
  DECLARE_LATENCY(infer_async);   // 异步请求
  DECLARE_LATENCY(infer_send);    // 半同步send
  DECLARE_LATENCY(infer_recv);    // 半同步recv
  DECLARE_LATENCY(infer_cancel);  // 半同步cancel
  DECLARE_LATENCY(debug);         // 调试请求
  DECLARE_LATENCY(rpc_init);      // rpc reset
  DECLARE_LATENCY(thrd_clear);    // thrd clear
  DECLARE_LATENCY(pack_map);      // thrd clear
  DECLARE_LATENCY(pack_merge);    // thrd clear
W
sdk-cpp  
wangguibao 已提交
286 287 288 289

#undef DECLARE_LATENCY

#ifndef DECLARE_AVERAGE
W
wangguibao 已提交
290
#define DECLARE_AVERAGE(item) AverageWrapper* _avg_##item;
W
sdk-cpp  
wangguibao 已提交
291 292
#endif

W
wangguibao 已提交
293 294 295 296
  DECLARE_AVERAGE(failure);    // 失败请求数
  DECLARE_AVERAGE(item_size);  // 单次请求item数
  DECLARE_AVERAGE(pack);       // 单次请求分包数
  DECLARE_AVERAGE(pack_fail);  // 单次请求分包失败数
W
sdk-cpp  
wangguibao 已提交
297 298 299

#undef DECLARE_AVERAGE

W
wangguibao 已提交
300 301 302 303 304 305 306
 public:
  void update_average(int64_t acc, const char* name) {
    std::map<std::string, BvarWrapper*>::iterator iter =
        _avg_bvars.find(std::string(AVG_PREFIX) + name);
    if (iter == _avg_bvars.end()) {
      LOG(ERROR) << "Not found average record:avg_" << name;
      return;
W
sdk-cpp  
wangguibao 已提交
307 308
    }

W
wangguibao 已提交
309 310 311 312 313 314 315 316 317
    iter->second->update_average(acc);
  }

  void update_latency(int64_t acc, const char* name) {
    std::map<std::string, BvarWrapper*>::iterator iter =
        _ltc_bvars.find(std::string(LTC_PREFIX) + name);
    if (iter == _ltc_bvars.end()) {
      LOG(ERROR) << "Not found latency record:ltc_" << name;
      return;
W
sdk-cpp  
wangguibao 已提交
318
    }
W
wangguibao 已提交
319 320 321

    iter->second->update_latency(acc);
  }
W
sdk-cpp  
wangguibao 已提交
322 323
};

W
wangguibao 已提交
324 325 326
}  // namespace sdk_cpp
}  // namespace paddle_serving
}  // namespace baidu
W
sdk-cpp  
wangguibao 已提交
327 328

#include "stub_impl.hpp"