stub_impl.h 8.9 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
#include "core/sdk-cpp/include/common.h"
#include "core/sdk-cpp/include/endpoint_config.h"
D
dongdaxiang 已提交
22
#include "core/sdk-cpp/include/macros.h"
G
guru4elephant 已提交
23 24
#include "core/sdk-cpp/include/predictor.h"
#include "core/sdk-cpp/include/stub.h"
W
sdk-cpp  
wangguibao 已提交
25 26 27 28 29

namespace baidu {
namespace paddle_serving {
namespace sdk_cpp {

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

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

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

class MetricScope {
W
wangguibao 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
 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 已提交
57 58 59
};

class TracePackScope {
W
wangguibao 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
 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 已提交
75
    }
W
wangguibao 已提交
76
  }
W
sdk-cpp  
wangguibao 已提交
77

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

class TagFilter : public brpc::NamingServiceFilter {
W
wangguibao 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
 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 已提交
106 107
        }

W
wangguibao 已提交
108 109 110 111
        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 已提交
112 113
        }

W
wangguibao 已提交
114 115 116 117
        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 已提交
118 119
    }

W
wangguibao 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132
    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 已提交
133 134
    }

W
wangguibao 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
   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 已提交
152 153 154
};

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

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

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

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

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

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

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

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

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

struct StubTLS {
W
wangguibao 已提交
191 192 193 194 195 196 197 198 199
  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 已提交
200 201
};

W
wangguibao 已提交
202
template <typename T, typename C, typename R, typename I, typename O>
W
sdk-cpp  
wangguibao 已提交
203
class StubImpl : public Stub {
W
wangguibao 已提交
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
 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() {
D
dongdaxiang 已提交
249
    return static_cast<StubTLS*>(THREAD_GETSPECIFIC(_bthread_key));
W
wangguibao 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
  }

 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
D
dongdaxiang 已提交
266 267
  // bthread_key_t _bthread_key;
  THREAD_KEY_T _bthread_key;
W
wangguibao 已提交
268 269 270 271 272

  // 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 已提交
273 274

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

W
wangguibao 已提交
278 279 280 281 282 283 284 285 286 287
  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 已提交
288 289 290 291

#undef DECLARE_LATENCY

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

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

#undef DECLARE_AVERAGE

W
wangguibao 已提交
302 303 304 305 306 307 308
 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 已提交
309 310
    }

W
wangguibao 已提交
311 312 313 314 315 316 317 318 319
    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 已提交
320
    }
W
wangguibao 已提交
321 322 323

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

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

#include "stub_impl.hpp"