编译mac版brpc静态库

This commit is contained in:
yangzuhao
2022-12-14 19:05:52 +08:00
commit fd6441d247
1001 changed files with 228056 additions and 0 deletions
+148
View File
@@ -0,0 +1,148 @@
# 测试demo cmakelist
```cmakelist
# 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.
cmake_minimum_required(VERSION 2.8.10)
project(echo_c++ C CXX)
option(LINK_SO "Whether examples are linked dynamically" OFF)
execute_process(
COMMAND bash -c "find ${PROJECT_SOURCE_DIR}/../.. -type d -regex \".*output/include$\" | head -n1 | xargs dirname | tr -d '\n'"
OUTPUT_VARIABLE OUTPUT_PATH
)
set(CMAKE_PREFIX_PATH ${OUTPUT_PATH})
include(FindThreads)
include(FindProtobuf)
protobuf_generate_cpp(PROTO_SRC PROTO_HEADER echo.proto)
# include PROTO_HEADER
include_directories(${CMAKE_CURRENT_BINARY_DIR})
# Search for libthrift* by best effort. If it is not found and brpc is
# compiled with thrift protocol enabled, a link error would be reported.
find_library(THRIFT_LIB NAMES thrift)
if (NOT THRIFT_LIB)
set(THRIFT_LIB "")
endif()
find_library(THRIFTNB_LIB NAMES thriftnb)
if (NOT THRIFTNB_LIB)
set(THRIFTNB_LIB "")
endif()
find_path(BRPC_INCLUDE_PATH NAMES brpc/server.h)
if(LINK_SO)
find_library(BRPC_LIB NAMES brpc)
else()
find_library(BRPC_LIB NAMES libbrpc.a brpc)
endif()
if((NOT BRPC_INCLUDE_PATH) OR (NOT BRPC_LIB))
message(FATAL_ERROR "Fail to find brpc")
endif()
include_directories(${BRPC_INCLUDE_PATH})
find_path(GFLAGS_INCLUDE_PATH gflags/gflags.h)
find_library(GFLAGS_LIBRARY NAMES gflags libgflags)
if((NOT GFLAGS_INCLUDE_PATH) OR (NOT GFLAGS_LIBRARY))
message(FATAL_ERROR "Fail to find gflags")
endif()
include_directories(${GFLAGS_INCLUDE_PATH})
execute_process(
COMMAND bash -c "grep \"namespace [_A-Za-z0-9]\\+ {\" ${GFLAGS_INCLUDE_PATH}/gflags/gflags_declare.h | head -1 | awk '{print $2}' | tr -d '\n'"
OUTPUT_VARIABLE GFLAGS_NS
)
if(${GFLAGS_NS} STREQUAL "GFLAGS_NAMESPACE")
execute_process(
COMMAND bash -c "grep \"#define GFLAGS_NAMESPACE [_A-Za-z0-9]\\+\" ${GFLAGS_INCLUDE_PATH}/gflags/gflags_declare.h | head -1 | awk '{print $3}' | tr -d '\n'"
OUTPUT_VARIABLE GFLAGS_NS
)
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
include(CheckFunctionExists)
CHECK_FUNCTION_EXISTS(clock_gettime HAVE_CLOCK_GETTIME)
if(NOT HAVE_CLOCK_GETTIME)
set(DEFINE_CLOCK_GETTIME "-DNO_CLOCK_GETTIME_IN_MAC")
endif()
endif()
set(CMAKE_CPP_FLAGS "${DEFINE_CLOCK_GETTIME} -DGFLAGS_NS=${GFLAGS_NS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CPP_FLAGS} -DNDEBUG -O2 -D__const__=__unused__ -pipe -W -Wall -Wno-unused-parameter -fPIC -fno-omit-frame-pointer")
if(CMAKE_VERSION VERSION_LESS "3.1.3")
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif()
else()
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
endif()
find_path(LEVELDB_INCLUDE_PATH NAMES leveldb/db.h)
find_library(LEVELDB_LIB NAMES leveldb)
if ((NOT LEVELDB_INCLUDE_PATH) OR (NOT LEVELDB_LIB))
message(FATAL_ERROR "Fail to find leveldb")
endif()
include_directories(${LEVELDB_INCLUDE_PATH})
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
set(OPENSSL_ROOT_DIR
"/usr/local/opt/openssl" # Homebrew installed OpenSSL
)
endif()
find_package(OpenSSL)
include_directories(${OPENSSL_INCLUDE_DIR})
set(DYNAMIC_LIB
${CMAKE_THREAD_LIBS_INIT}
${GFLAGS_LIBRARY}
${PROTOBUF_LIBRARIES}
${LEVELDB_LIB}
${OPENSSL_CRYPTO_LIBRARY}
${OPENSSL_SSL_LIBRARY}
${THRIFT_LIB}
${THRIFTNB_LIB}
dl
)
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
set(DYNAMIC_LIB ${DYNAMIC_LIB}
pthread
"-framework CoreFoundation"
"-framework CoreGraphics"
"-framework CoreData"
"-framework CoreText"
"-framework Security"
"-framework Foundation"
"-Wl,-U,_MallocExtension_ReleaseFreeMemory"
"-Wl,-U,_ProfilerStart"
"-Wl,-U,_ProfilerStop")
endif()
add_executable(echo_client client.cpp ${PROTO_SRC} ${PROTO_HEADER})
add_executable(echo_server server.cpp ${PROTO_SRC} ${PROTO_HEADER})
target_link_libraries(echo_client ${BRPC_LIB} ${DYNAMIC_LIB})
target_link_libraries(echo_server ${BRPC_LIB} ${DYNAMIC_LIB})
```
BIN
View File
Binary file not shown.
+118
View File
@@ -0,0 +1,118 @@
// 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.
#ifndef BRPC_ACCEPTOR_H
#define BRPC_ACCEPTOR_H
#include "bthread/bthread.h" // bthread_t
#include "butil/synchronization/condition_variable.h"
#include "butil/containers/flat_map.h"
#include "brpc/input_messenger.h"
namespace brpc {
struct ConnectStatistics {
};
// Accept connections from a specific port and then
// process messages from which it reads
class Acceptor : public InputMessenger {
friend class Server;
public:
typedef butil::FlatMap<SocketId, ConnectStatistics> SocketMap;
enum Status {
UNINITIALIZED = 0,
READY = 1,
RUNNING = 2,
STOPPING = 3,
};
public:
explicit Acceptor(bthread_keytable_pool_t* pool = NULL);
~Acceptor();
// [thread-safe] Accept connections from `listened_fd'. Ownership of
// `listened_fd' is also transferred to `Acceptor'. Can be called
// multiple times if the last `StartAccept' has been completely stopped
// by calling `StopAccept' and `Join'. Connections that has no data
// transmission for `idle_timeout_sec' will be closed automatically iff
// `idle_timeout_sec' > 0
// Return 0 on success, -1 otherwise.
int StartAccept(int listened_fd, int idle_timeout_sec,
const std::shared_ptr<SocketSSLContext>& ssl_ctx);
// [thread-safe] Stop accepting connections.
// `closewait_ms' is not used anymore.
void StopAccept(int /*closewait_ms*/);
// Wait until all existing Sockets(defined in socket.h) are recycled.
void Join();
// The parameter to StartAccept. Negative when acceptor is stopped.
int listened_fd() const { return _listened_fd; }
// Get number of existing connections.
size_t ConnectionCount() const;
// Clear `conn_list' and append all connections into it.
void ListConnections(std::vector<SocketId>* conn_list);
// Clear `conn_list' and append all most `max_copied' connections into it.
void ListConnections(std::vector<SocketId>* conn_list, size_t max_copied);
Status status() const { return _status; }
private:
// Accept connections.
static void OnNewConnectionsUntilEAGAIN(Socket* m);
static void OnNewConnections(Socket* m);
static void* CloseIdleConnections(void* arg);
// Initialize internal structure.
int Initialize();
// Remove the accepted socket `sock' from inside
void BeforeRecycle(Socket* sock) override;
bthread_keytable_pool_t* _keytable_pool; // owned by Server
Status _status;
int _idle_timeout_sec;
bthread_t _close_idle_tid;
int _listened_fd;
// The Socket tso accept connections.
SocketId _acception_id;
butil::Mutex _map_mutex;
butil::ConditionVariable _empty_cond;
// The map containing all the accepted sockets
SocketMap _socket_map;
std::shared_ptr<SocketSSLContext> _ssl_ctx;
// Whether to use rdma or not
bool _use_rdma;
};
} // namespace brpc
#endif // BRPC_ACCEPTOR_H
+70
View File
@@ -0,0 +1,70 @@
// 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.
#ifndef BRPC_ADAPTIVE_CONNECTION_TYPE_H
#define BRPC_ADAPTIVE_CONNECTION_TYPE_H
// To brpc developers: This is a header included by user, don't depend
// on internal structures, use opaque pointers instead.
#include "butil/strings/string_piece.h"
#include "brpc/options.pb.h"
namespace brpc {
// Convert a case-insensitive string to corresponding ConnectionType
// Possible options are: short, pooled, single
// Returns: CONNECTION_TYPE_UNKNOWN on error.
ConnectionType StringToConnectionType(const butil::StringPiece& type,
bool print_log_on_unknown);
inline ConnectionType StringToConnectionType(const butil::StringPiece& type)
{ return StringToConnectionType(type, true); }
// Convert a ConnectionType to a c-style string.
const char* ConnectionTypeToString(ConnectionType);
// Assignable by both ConnectionType and names.
class AdaptiveConnectionType {
public:
AdaptiveConnectionType() : _type(CONNECTION_TYPE_UNKNOWN), _error(false) {}
AdaptiveConnectionType(ConnectionType type) : _type(type), _error(false) {}
~AdaptiveConnectionType() {}
void operator=(ConnectionType type) {
_type = type;
_error = false;
}
void operator=(const butil::StringPiece& name);
operator ConnectionType() const { return _type; }
const char* name() const { return ConnectionTypeToString(_type); }
bool has_error() const { return _error; }
private:
ConnectionType _type;
// Since this structure occupies 8 bytes in 64-bit machines anyway,
// we add a field to mark if last operator=(name) failed so that
// channel can print a error log before re-selecting a valid
// ConnectionType for user.
bool _error;
};
} // namespace brpc
#endif // BRPC_ADAPTIVE_CONNECTION_TYPE_H
+92
View File
@@ -0,0 +1,92 @@
// 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.
#ifndef BRPC_ADAPTIVE_MAX_CONCURRENCY_H
#define BRPC_ADAPTIVE_MAX_CONCURRENCY_H
// To brpc developers: This is a header included by user, don't depend
// on internal structures, use opaque pointers instead.
#include "butil/strings/string_piece.h"
#include "brpc/options.pb.h"
namespace brpc {
class AdaptiveMaxConcurrency{
public:
explicit AdaptiveMaxConcurrency();
explicit AdaptiveMaxConcurrency(int max_concurrency);
explicit AdaptiveMaxConcurrency(const butil::StringPiece& value);
// Non-trivial destructor to prevent AdaptiveMaxConcurrency from being
// passed to variadic arguments without explicit type conversion.
// eg:
// printf("%d", options.max_concurrency) // compile error
// printf("%s", options.max_concurrency.value().c_str()) // ok
~AdaptiveMaxConcurrency() {}
void operator=(int max_concurrency);
void operator=(const butil::StringPiece& value);
// 0 for type="unlimited"
// >0 for type="constant"
// <0 for type="user-defined"
operator int() const { return _max_concurrency; }
// "unlimited" for type="unlimited"
// "10" "20" "30" for type="constant"
// "user-defined" for type="user-defined"
const std::string& value() const { return _value; }
// "unlimited", "constant" or "user-defined"
const std::string& type() const;
// Get strings filled with "unlimited" and "constant"
static const std::string& UNLIMITED();
static const std::string& CONSTANT();
private:
std::string _value;
int _max_concurrency;
};
inline std::ostream& operator<<(std::ostream& os, const AdaptiveMaxConcurrency& amc) {
return os << amc.value();
}
bool operator==(const AdaptiveMaxConcurrency& adaptive_concurrency,
const butil::StringPiece& concurrency);
inline bool operator==(const butil::StringPiece& concurrency,
const AdaptiveMaxConcurrency& adaptive_concurrency) {
return adaptive_concurrency == concurrency;
}
inline bool operator!=(const AdaptiveMaxConcurrency& adaptive_concurrency,
const butil::StringPiece& concurrency) {
return !(adaptive_concurrency == concurrency);
}
inline bool operator!=(const butil::StringPiece& concurrency,
const AdaptiveMaxConcurrency& adaptive_concurrency) {
return !(adaptive_concurrency == concurrency);
}
} // namespace brpc
#endif // BRPC_ADAPTIVE_MAX_CONCURRENCY_H
+92
View File
@@ -0,0 +1,92 @@
// 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.
#ifndef BRPC_ADAPTIVE_PROTOCOL_TYPE_H
#define BRPC_ADAPTIVE_PROTOCOL_TYPE_H
// To brpc developers: This is a header included by user, don't depend
// on internal structures, use opaque pointers instead.
#include "butil/strings/string_piece.h"
#include "brpc/options.pb.h"
namespace brpc {
// NOTE: impl. are in brpc/protocol.cpp
// Convert a case-insensitive string to corresponding ProtocolType which is
// defined in src/brpc/options.proto
// Returns: PROTOCOL_UNKNOWN on error.
ProtocolType StringToProtocolType(const butil::StringPiece& type,
bool print_log_on_unknown);
inline ProtocolType StringToProtocolType(const butil::StringPiece& type)
{ return StringToProtocolType(type, true); }
// Convert a ProtocolType to a c-style string.
const char* ProtocolTypeToString(ProtocolType);
// Assignable by both ProtocolType and names.
class AdaptiveProtocolType {
public:
explicit AdaptiveProtocolType() : _type(PROTOCOL_UNKNOWN) {}
explicit AdaptiveProtocolType(ProtocolType type) : _type(type) {}
~AdaptiveProtocolType() {}
void operator=(ProtocolType type) {
_type = type;
_name.clear();
_param.clear();
}
void operator=(butil::StringPiece name) {
butil::StringPiece param;
const size_t pos = name.find(':');
if (pos != butil::StringPiece::npos) {
param = name.substr(pos + 1);
name.remove_suffix(name.size() - pos);
}
_type = StringToProtocolType(name);
if (_type == PROTOCOL_UNKNOWN) {
_name.assign(name.data(), name.size());
} else {
_name.clear();
}
if (!param.empty()) {
_param.assign(param.data(), param.size());
} else {
_param.clear();
}
};
operator ProtocolType() const { return _type; }
const char* name() const {
return _name.empty() ? ProtocolTypeToString(_type) : _name.c_str();
}
bool has_param() const { return !_param.empty(); }
const std::string& param() const { return _param; }
private:
ProtocolType _type;
std::string _name;
std::string _param;
};
} // namespace brpc
#endif // BRPC_ADAPTIVE_PROTOCOL_TYPE_H
+304
View File
@@ -0,0 +1,304 @@
// 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.
#ifndef BRPC_AMF_H
#define BRPC_AMF_H
#include <map>
#include <deque>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/message.h>
#include "butil/sys_byteorder.h"
#include "butil/strings/string_piece.h"
namespace brpc {
// For parsing and serializing Action Message Format used throughout RTMP.
// Buffer ZeroCopyInputStream as efficient input of parsing AMF.
class AMFInputStream {
public:
AMFInputStream(google::protobuf::io::ZeroCopyInputStream* stream)
: _good(true)
, _size(0)
, _data(NULL)
, _zc_stream(stream)
, _popped_bytes(0)
{}
~AMFInputStream() { }
// Cut off at-most n bytes from front side and copy to `out'.
// Returns bytes cut.
size_t cutn(void* out, size_t n);
size_t cut_u8(uint8_t* u16);
size_t cut_u16(uint16_t* u16);
size_t cut_u32(uint32_t* u32);
size_t cut_u64(uint64_t* u64);
// Returns bytes popped and cut since creation of this stream.
size_t popped_bytes() const { return _popped_bytes; }
// Returns false if error occurred in other consuming functions.
bool good() const { return _good; }
// If the error prevents parsing from going on, call this method.
// This method is also called in other functions in this class.
void set_bad() { _good = false; }
// Return true if the stream is empty. Notice that this function
// may update _data and _size.
bool check_emptiness();
private:
bool _good;
int _size;
const void* _data;
google::protobuf::io::ZeroCopyInputStream* _zc_stream;
size_t _popped_bytes;
};
// Buffer serialize data of AMF to ZeroCopyOutputStream
class AMFOutputStream {
public:
AMFOutputStream(google::protobuf::io::ZeroCopyOutputStream* stream)
: _good(true)
, _size(0)
, _data(NULL)
, _zc_stream(stream)
, _pushed_bytes(0)
{}
~AMFOutputStream() { done(); }
// Append n bytes.
void putn(const void* data, int n);
void put_u8(uint8_t u16);
void put_u16(uint16_t u16);
void put_u32(uint32_t u32);
void put_u64(uint64_t u64);
// Returns bytes pushed and cut since creation of this stream.
size_t pushed_bytes() const { return _pushed_bytes; }
// Returns false if error occurred during serialization.
bool good() { return _good; }
void set_bad() { _good = false; }
// Optionally called to backup buffered bytes to zero-copy stream.
void done();
private:
bool _good;
int _size;
void* _data;
google::protobuf::io::ZeroCopyOutputStream* _zc_stream;
size_t _pushed_bytes;
};
// There are 16 core type markers in AMF 0. A type marker is one byte in
// length and describes the kind of encoded data that may follow.
enum AMFMarker {
AMF_MARKER_NUMBER = 0x00,
AMF_MARKER_BOOLEAN = 0x01,
AMF_MARKER_STRING = 0x02,
AMF_MARKER_OBJECT = 0x03,
AMF_MARKER_MOVIECLIP = 0x04,
AMF_MARKER_NULL = 0x05,
AMF_MARKER_UNDEFINED = 0x06,
AMF_MARKER_REFERENCE = 0x07,
AMF_MARKER_ECMA_ARRAY = 0x08,
AMF_MARKER_OBJECT_END = 0x09,
AMF_MARKER_STRICT_ARRAY = 0x0A,
AMF_MARKER_DATE = 0x0B,
AMF_MARKER_LONG_STRING = 0x0C,
AMF_MARKER_UNSUPPORTED = 0x0D,
AMF_MARKER_RECORDSET = 0x0E,
AMF_MARKER_XML_DOCUMENT = 0x0F,
AMF_MARKER_TYPED_OBJECT = 0x10,
AMF_MARKER_AVMPLUS_OBJECT = 0x11
};
const char* marker2str(AMFMarker marker);
const char* marker2str(uint8_t marker);
class AMFObject;
class AMFArray;
// A field inside a AMF object.
class AMFField {
friend class AMFObject;
public:
static const size_t SSO_LIMIT = 8;
AMFField();
AMFField(const AMFField&);
AMFField& operator=(const AMFField&);
~AMFField() { Clear(); }
void Clear() { if (_type != AMF_MARKER_UNDEFINED) { SlowerClear(); } }
AMFMarker type() const { return (AMFMarker)_type; }
bool IsString() const
{ return _type == AMF_MARKER_STRING || _type == AMF_MARKER_LONG_STRING; }
bool IsBool() const { return _type == AMF_MARKER_BOOLEAN; }
bool IsNumber() const { return _type == AMF_MARKER_NUMBER; }
bool IsObject() const
{ return _type == AMF_MARKER_OBJECT || _type == AMF_MARKER_ECMA_ARRAY; }
bool IsArray() const { return _type == AMF_MARKER_STRICT_ARRAY; }
butil::StringPiece AsString() const
{ return butil::StringPiece((_is_shortstr ? _shortstr : _str), _strsize); }
bool AsBool() const { return _b; }
double AsNumber() const { return _num; }
const AMFObject& AsObject() const { return *_obj; }
const AMFArray& AsArray() const { return *_arr; }
void SetString(const butil::StringPiece& str);
void SetBool(bool val);
void SetNumber(double val);
void SetNull();
void SetUndefined();
void SetUnsupported();
AMFObject* MutableObject();
AMFArray* MutableArray();
private:
void SlowerClear();
uint8_t _type;
bool _is_shortstr;
uint32_t _strsize;
union {
double _num;
char* _str;
char _shortstr[SSO_LIMIT]; // SSO
bool _b;
AMFObject* _obj;
AMFArray* _arr;
};
};
std::ostream& operator<<(std::ostream& os, const AMFField& field);
// A general AMF object.
class AMFObject {
public:
typedef std::map<std::string, AMFField>::iterator iterator;
typedef std::map<std::string, AMFField>::const_iterator const_iterator;
const AMFField* Find(const char* name) const;
void Remove(const std::string& name) { _fields.erase(name); }
void Clear() { _fields.clear(); }
void SetString(const std::string& name, const butil::StringPiece& val);
void SetBool(const std::string& name, bool val);
void SetNumber(const std::string& name, double val);
void SetNull(const std::string& name);
void SetUndefined(const std::string& name);
void SetUnsupported(const std::string& name);
AMFObject* MutableObject(const std::string& name);
AMFArray* MutableArray(const std::string& name);
iterator begin() { return _fields.begin(); }
const_iterator begin() const { return _fields.begin(); }
iterator end() { return _fields.end(); }
const_iterator end() const { return _fields.end(); }
private:
std::map<std::string, AMFField> _fields;
};
std::ostream& operator<<(std::ostream& os, const AMFObject&);
// An AMF strict array (not ecma array)
class AMFArray {
public:
AMFArray();
AMFArray(const AMFArray&);
AMFArray& operator=(const AMFArray&);
~AMFArray() { Clear(); }
void Clear();
const AMFField& operator[](size_t index) const;
AMFField& operator[](size_t index);
size_t size() const { return _size; }
void AddString(const butil::StringPiece& val) { AddField()->SetString(val); }
void AddBool(bool val) { AddField()->SetBool(val); }
void AddNumber(double val) { AddField()->SetNumber(val); }
void AddNull() { AddField()->SetNull(); }
void AddUndefined() { AddField()->SetUndefined(); }
void AddUnsupported() { AddField()->SetUnsupported(); }
AMFObject* AddObject() { return AddField()->MutableObject(); }
AMFArray* AddArray() { return AddField()->MutableArray(); }
private:
AMFField* AddField();
void RemoveLastField();
uint32_t _size;
AMFField _fields[4];
std::deque<AMFField> _morefields;
};
std::ostream& operator<<(std::ostream& os, const AMFArray&);
inline const AMFField& AMFArray::operator[](size_t index) const {
return (index < arraysize(_fields) ? _fields[index] :
_morefields[index - arraysize(_fields)]);
}
inline AMFField& AMFArray::operator[](size_t index) {
return (index < arraysize(_fields) ? _fields[index] :
_morefields[index - arraysize(_fields)]);
}
// Parse types of the stream.
bool ReadAMFString(std::string* val, AMFInputStream* stream);
bool ReadAMFBool(bool* val, AMFInputStream* stream);
bool ReadAMFNumber(double* val, AMFInputStream* stream);
bool ReadAMFUint32(uint32_t* val, AMFInputStream* stream);
bool ReadAMFNull(AMFInputStream* stream);
bool ReadAMFUndefined(AMFInputStream* stream);
bool ReadAMFUnsupported(AMFInputStream* stream);
// The pb version just loads known fields (defined in proto)
bool ReadAMFObject(google::protobuf::Message* msg, AMFInputStream* stream);
bool ReadAMFObject(AMFObject* obj, AMFInputStream* stream);
bool ReadAMFArray(AMFArray* arr, AMFInputStream* stream);
// Serialize types into the stream.
// Check stream->good() for successfulness after one or multiple WriteAMFxxx.
void WriteAMFString(const butil::StringPiece& val, AMFOutputStream* stream);
void WriteAMFBool(bool val, AMFOutputStream* stream);
void WriteAMFNumber(double val, AMFOutputStream* stream);
void WriteAMFUint32(uint32_t val, AMFOutputStream* stream);
void WriteAMFNull(AMFOutputStream* stream);
void WriteAMFUndefined(AMFOutputStream* stream);
void WriteAMFUnsupported(AMFOutputStream* stream);
void WriteAMFObject(const google::protobuf::Message& msg,
AMFOutputStream* stream);
void WriteAMFObject(const AMFObject& obj, AMFOutputStream* stream);
void WriteAMFArray(const AMFArray& arr, AMFOutputStream* stream);
} // namespace brpc
#include "brpc/amf_inl.h"
#endif // BRPC_AMF_H
+171
View File
@@ -0,0 +1,171 @@
// 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.
#ifndef BRPC_AMF_INL_H
#define BRPC_AMF_INL_H
void* fast_memcpy(void *__restrict dest, const void *__restrict src, size_t n);
namespace brpc {
inline size_t AMFInputStream::cutn(void* out, size_t n) {
const size_t saved_n = n;
do {
if (_size >= (int64_t)n) {
memcpy(out, _data, n);
_data = (const char*)_data + n;
_size -= n;
_popped_bytes += saved_n;
return saved_n;
}
if (_size) {
memcpy(out, _data, _size);
out = (char*)out + _size;
n -= _size;
}
} while (_zc_stream->Next(&_data, &_size));
_data = NULL;
_size = 0;
_popped_bytes += saved_n - n;
return saved_n - n;
}
inline bool AMFInputStream::check_emptiness() {
return _size == 0 && !_zc_stream->Next(&_data, &_size);
}
inline size_t AMFInputStream::cut_u8(uint8_t* val) {
if (_size >= 1) {
*val = *(uint8_t*)_data;
_data = (const char*)_data + 1;
_size -= 1;
_popped_bytes += 1;
return 1;
}
return cutn(val, 1);
}
inline size_t AMFInputStream::cut_u16(uint16_t* val) {
if (_size >= 2) {
const uint16_t netval = *(uint16_t*)_data;
*val = butil::NetToHost16(netval);
_data = (const char*)_data + 2;
_size -= 2;
_popped_bytes += 2;
return 2;
}
uint16_t netval = 0;
const size_t ret = cutn(&netval, 2);
*val = butil::NetToHost16(netval);
return ret;
}
inline size_t AMFInputStream::cut_u32(uint32_t* val) {
if (_size >= 4) {
const uint32_t netval = *(uint32_t*)_data;
*val = butil::NetToHost32(netval);
_data = (const char*)_data + 4;
_size -= 4;
_popped_bytes += 4;
return 4;
}
uint32_t netval = 0;
const size_t ret = cutn(&netval, 4);
*val = butil::NetToHost32(netval);
return ret;
}
inline size_t AMFInputStream::cut_u64(uint64_t* val) {
if (_size >= 8) {
const uint64_t netval = *(uint64_t*)_data;
*val = butil::NetToHost64(netval);
_data = (const char*)_data + 8;
_size -= 8;
_popped_bytes += 8;
return 8;
}
uint64_t netval = 0;
const size_t ret = cutn(&netval, 8);
*val = butil::NetToHost64(netval);
return ret;
}
inline void AMFOutputStream::done() {
if (_good && _size) {
_zc_stream->BackUp(_size);
_size = 0;
}
}
inline void AMFOutputStream::putn(const void* data, int n) {
const int saved_n = n;
do {
if (n <= _size) {
fast_memcpy(_data, data, n);
_data = (char*)_data + n;
_size -= n;
_pushed_bytes += saved_n;
return;
}
fast_memcpy(_data, data, _size);
data = (const char*)data + _size;
n -= _size;
} while (_zc_stream->Next(&_data, &_size));
_data = NULL;
_size = 0;
_pushed_bytes += (saved_n - n);
if (n) {
set_bad();
}
}
inline void AMFOutputStream::put_u8(uint8_t val) {
do {
if (_size > 0) {
*(uint8_t*)_data = val;
_data = (char*)_data + 1;
--_size;
++_pushed_bytes;
return;
}
} while (_zc_stream->Next(&_data, &_size));
_data = NULL;
_size = 0;
set_bad();
}
inline void AMFOutputStream::put_u16(uint16_t val) {
uint16_t netval = butil::HostToNet16(val);
return putn(&netval, sizeof(netval));
}
inline void AMFOutputStream::put_u32(uint32_t val) {
uint32_t netval = butil::HostToNet32(val);
return putn(&netval, sizeof(netval));
}
inline void AMFOutputStream::put_u64(uint64_t val) {
uint64_t netval = butil::HostToNet64(val);
return putn(&netval, sizeof(netval));
}
} // namespace brpc
#endif // BRPC_AMF_INL_H
+91
View File
@@ -0,0 +1,91 @@
// 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.
#ifndef BRPC_AUTHENTICATOR_H
#define BRPC_AUTHENTICATOR_H
#include <ostream>
#include "butil/endpoint.h" // butil::EndPoint
#include "butil/macros.h" // BAIDU_CONCAT
#include "brpc/extension.h" // Extension<T>
namespace brpc {
class AuthContext {
public:
AuthContext() : _is_service(false) {}
~AuthContext() {}
const std::string& user() const { return _user; }
void set_user(const std::string& user) { _user = user; }
const std::string& group() const { return _group; }
void set_group(const std::string& group) { _group = group; }
const std::string& roles() const { return _roles; }
void set_roles(const std::string& roles) { _roles = roles; }
const std::string& starter() const { return _starter; }
void set_starter(const std::string& starter) { _starter = starter; }
bool is_service() const { return _is_service; }
void set_is_service(bool is_service) { _is_service = is_service; }
private:
bool _is_service;
std::string _user;
std::string _group;
std::string _roles;
std::string _starter;
};
class Authenticator {
public:
virtual ~Authenticator() {}
// Implement this method to generate credential information
// into `auth_str' which will be sent to `VerifyCredential'
// at server side. This method will be called on client side.
// Returns 0 on success, error code otherwise
virtual int GenerateCredential(std::string* auth_str) const = 0;
// Implement this method to verify credential information
// `auth_str' from `client_addr'. You can fill credential
// context (result) into `*out_ctx' and later fetch this
// pointer from `Controller'.
// Returns 0 on success, error code otherwise
virtual int VerifyCredential(const std::string& auth_str,
const butil::EndPoint& client_addr,
AuthContext* out_ctx) const = 0;
};
inline std::ostream& operator<<(std::ostream& os, const AuthContext& ctx) {
return os << "[name=" << ctx.user() << " [This is a "
<< (ctx.is_service() ? "service" : "user")
<< "], group=" << ctx.group() << ", roles=" << ctx.roles()
<< ", starter=" << ctx.starter() << "]";
}
} // namespace brpc
#endif // BRPC_AUTHENTICATOR_H
+39
View File
@@ -0,0 +1,39 @@
// 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.
#ifndef BRPC_BADMETHOD_SERVICE_H
#define BRPC_BADMETHOD_SERVICE_H
#include "brpc/builtin_service.pb.h"
namespace brpc {
class BadMethodService : public badmethod {
public:
void no_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::BadMethodRequest* request,
::brpc::BadMethodResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_BADMETHOD_SERVICE_H
+38
View File
@@ -0,0 +1,38 @@
// 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.
#ifndef BRPC_BTHREADS_SERVICE_H
#define BRPC_BTHREADS_SERVICE_H
#include "brpc/builtin_service.pb.h"
namespace brpc {
class BthreadsService : public bthreads {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::BthreadsRequest* request,
::brpc::BthreadsResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_BTHREADS_SERVICE_H
+146
View File
@@ -0,0 +1,146 @@
// 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.
#ifndef BRPC_BUILTIN_COMMON_H
#define BRPC_BUILTIN_COMMON_H
#include <vector> // std::vector
#include <gflags/gflags_declare.h>
#include "butil/endpoint.h"
#include "brpc/http_header.h"
namespace brpc {
class Controller;
// These static strings are referenced more than once in brpc.
// Don't turn them to std::strings whose constructing sequences are undefined.
const char* const UNKNOWN_METHOD_STR = "unknown_method";
const char* const TRACE_ID_STR = "trace";
const char* const SPAN_ID_STR = "span";
const char* const TIME_STR = "time";
const char* const MAX_SCAN_STR = "max_scan";
const char* const MIN_LATENCY_STR = "min_latency";
const char* const MIN_REQUEST_SIZE_STR = "min_request_size";
const char* const MIN_RESPONSE_SIZE_STR = "min_response_size";
const char* const LOG_ID_STR = "log_id";
const char* const ERROR_CODE_STR = "error_code";
const char* const CONSOLE_STR = "console";
const char* const USER_AGENT_STR = "user-agent";
const char* const SETVALUE_STR = "setvalue";
const size_t MAX_READ = 1024 * 1024;
enum ProfilingType {
PROFILING_CPU = 0,
PROFILING_HEAP = 1,
PROFILING_GROWTH = 2,
PROFILING_CONTENTION = 3,
};
DECLARE_string(rpc_profiling_dir);
bool UseHTML(const HttpHeader& header);
bool MatchAnyWildcard(const std::string& name,
const std::vector<std::string>& wildcards);
void PrintRealDateTime(std::ostream& os, int64_t tm);
void PrintRealDateTime(std::ostream& os, int64_t tm, bool ignore_microseconds);
struct PrintedAsDateTime {
PrintedAsDateTime(int64_t realtime2) : realtime(realtime2) {}
int64_t realtime;
};
std::ostream& operator<<(std::ostream& os, const PrintedAsDateTime&);
struct Path {
static const butil::EndPoint *LOCAL;
Path(const char* uri2, const butil::EndPoint* html_addr2)
: uri(uri2), html_addr(html_addr2), text(NULL) {}
Path(const char* uri2, const butil::EndPoint* html_addr2, const char* text2)
: uri(uri2), html_addr(html_addr2), text(text2) {}
const char* uri;
const butil::EndPoint* html_addr;
const char* text;
};
std::ostream& operator<<(std::ostream& os, const Path& link);
// Append `filename' to `dir' according to unix directory rules:
// "foo/bar" + ".." -> "foo"
// "foo/bar/." + ".." -> "foo"
// "foo" + "." -> "foo"
// "foo/" + ".." -> ""
// "foo/../" + ".." -> ".."
// "/foo/../" + ".." -> "/"
// "foo/./" + ".." -> ""
void AppendFileName(std::string* dir, const std::string& filename);
// style of class=gridtable, wrapped with <style>
const char* gridtable_style();
// Put inside <head></head> of html to work with Tabbed.
const char* TabsHead();
// The logo ascii art.
const char* logo();
// Convert ProfilingType to its description.
const char* ProfilingType2String(ProfilingType t);
// Compute 128-bit checksum of the file at `file_path'.
// Return 0 on success.
int FileChecksum(const char* file_path, unsigned char* checksum);
// Get name of current program.
const char* GetProgramName();
// Get checksum of current program image.
const char* GetProgramChecksum();
// True if the http requester support gzip compression.
bool SupportGzip(Controller* cntl);
void Time2GMT(time_t t, char* buf, size_t size);
template <typename T>
struct MinWidth {
MinWidth(const T& obj2, size_t nspace2) : obj(&obj2), nspace(nspace2) {}
const T* obj;
size_t nspace;
};
template <typename T>
MinWidth<T> min_width(const T& obj, size_t nspace) {
return MinWidth<T>(obj, nspace);
}
template <typename T>
inline std::ostream& operator<<(std::ostream& os, const MinWidth<T>& fw) {
const std::streampos old_pos = os.tellp();
os << *fw.obj;
for (size_t i = os.tellp() - old_pos; i < fw.nspace; ++i) {
os << ' ';
}
return os;
}
} // namespace brpc
#endif // BRPC_BUILTIN_COMMON_H
@@ -0,0 +1,47 @@
// 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.
#ifndef BRPC_CONNECTIONS_SERVICE_H
#define BRPC_CONNECTIONS_SERVICE_H
#include "brpc/socket_id.h"
#include "brpc/builtin_service.pb.h"
#include "brpc/builtin/tabbed.h"
namespace brpc {
class Acceptor;
class ConnectionsService : public connections, public Tabbed {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::ConnectionsRequest* request,
::brpc::ConnectionsResponse* response,
::google::protobuf::Closure* done);
void GetTabInfo(TabInfoList* info_list) const;
private:
void PrintConnections(std::ostream& os, const std::vector<SocketId>& conns,
bool use_html, const Server*, bool need_local) const;
};
} // namespace brpc
#endif // BRPC_CONNECTIONS_SERVICE_H
+39
View File
@@ -0,0 +1,39 @@
// 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.
#ifndef BRPC_DIR_SERVICE_H
#define BRPC_DIR_SERVICE_H
#include "brpc/builtin_service.pb.h"
namespace brpc {
class DirService : public dir {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::DirRequest* request,
::brpc::DirResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_DIR_SERVICE_H
+46
View File
@@ -0,0 +1,46 @@
// 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.
#ifndef BRPC_FLAGS_SERVICE_H
#define BRPC_FLAGS_SERVICE_H
#include "brpc/builtin_service.pb.h"
#include "brpc/builtin/tabbed.h"
namespace brpc {
class FlagsService : public flags, public Tabbed {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::FlagsRequest* request,
::brpc::FlagsResponse* response,
::google::protobuf::Closure* done);
void GetTabInfo(TabInfoList* info_list) const;
private:
void set_value_page(Controller* cntl, ::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_FLAGS_SERVICE_H
+37
View File
@@ -0,0 +1,37 @@
// 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.
#ifndef BRPC_BUILTIN_FLOT_MIN_JS_H
#define BRPC_BUILTIN_FLOT_MIN_JS_H
#include "butil/iobuf.h"
namespace brpc {
// Get the flot.min.js as string or IOBuf.
// We need to pack all js inside C++ code so that builtin services can be
// accessed without external resources and network connection.
const char* flot_min_js();
const butil::IOBuf& flot_min_js_iobuf();
const butil::IOBuf& flot_min_js_iobuf_gzip();
} // namespace brpc
#endif // BRPC_BUILTIN_FLOT_MIN_JS_H
@@ -0,0 +1,37 @@
// 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.
#ifndef BRPC_GET_FAVICON_SERVICE_H
#define BRPC_GET_FAVICON_SERVICE_H
#include "brpc/get_favicon.pb.h"
namespace brpc {
class GetFaviconService : public ico {
public:
void default_method(::google::protobuf::RpcController* controller,
const GetFaviconRequest* request,
GetFaviconResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_GET_FAVICON_SERVICE_H
+56
View File
@@ -0,0 +1,56 @@
// 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.
#ifndef BRPC_GET_JAVASCRIPT_SERVICE_H
#define BRPC_GET_JAVASCRIPT_SERVICE_H
#include "brpc/get_js.pb.h"
namespace brpc {
// Get packed js.
// "/js/sorttable" : http://www.kryogenix.org/code/browser/sorttable/
// "/js/jquery_min" : jquery 1.8.3
// "/js/flot_min" : ploting library for jquery.
class GetJsService : public ::brpc::js {
public:
void sorttable(::google::protobuf::RpcController* controller,
const GetJsRequest* request,
GetJsResponse* response,
::google::protobuf::Closure* done);
void jquery_min(::google::protobuf::RpcController* controller,
const GetJsRequest* request,
GetJsResponse* response,
::google::protobuf::Closure* done);
void flot_min(::google::protobuf::RpcController* controller,
const GetJsRequest* request,
GetJsResponse* response,
::google::protobuf::Closure* done);
void viz_min(::google::protobuf::RpcController* controller,
const GetJsRequest* request,
GetJsResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_GET_JAVASCRIPT_SERVICE_H
+39
View File
@@ -0,0 +1,39 @@
// 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.
#ifndef BRPC_HEALTH_SERVICE_H
#define BRPC_HEALTH_SERVICE_H
#include <ostream>
#include "brpc/builtin_service.pb.h"
namespace brpc {
class HealthService : public health {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::HealthRequest* request,
::brpc::HealthResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif //BRPC_HEALTH_SERVICE_H
+80
View File
@@ -0,0 +1,80 @@
// 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.
#ifndef BRPC_HOTSPOTS_SERVICE_H
#define BRPC_HOTSPOTS_SERVICE_H
#include "brpc/builtin/common.h"
#include "brpc/builtin_service.pb.h"
#include "brpc/builtin/tabbed.h"
namespace brpc {
class Server;
class HotspotsService : public hotspots, public Tabbed {
public:
void cpu(::google::protobuf::RpcController* cntl_base,
const ::brpc::HotspotsRequest* request,
::brpc::HotspotsResponse* response,
::google::protobuf::Closure* done);
void heap(::google::protobuf::RpcController* cntl_base,
const ::brpc::HotspotsRequest* request,
::brpc::HotspotsResponse* response,
::google::protobuf::Closure* done);
void growth(::google::protobuf::RpcController* cntl_base,
const ::brpc::HotspotsRequest* request,
::brpc::HotspotsResponse* response,
::google::protobuf::Closure* done);
void contention(::google::protobuf::RpcController* cntl_base,
const ::brpc::HotspotsRequest* request,
::brpc::HotspotsResponse* response,
::google::protobuf::Closure* done);
void cpu_non_responsive(::google::protobuf::RpcController* cntl_base,
const ::brpc::HotspotsRequest* request,
::brpc::HotspotsResponse* response,
::google::protobuf::Closure* done);
void heap_non_responsive(::google::protobuf::RpcController* cntl_base,
const ::brpc::HotspotsRequest* request,
::brpc::HotspotsResponse* response,
::google::protobuf::Closure* done);
void growth_non_responsive(::google::protobuf::RpcController* cntl_base,
const ::brpc::HotspotsRequest* request,
::brpc::HotspotsResponse* response,
::google::protobuf::Closure* done);
void contention_non_responsive(::google::protobuf::RpcController* cntl_base,
const ::brpc::HotspotsRequest* request,
::brpc::HotspotsResponse* response,
::google::protobuf::Closure* done);
void GetTabInfo(brpc::TabInfoList*) const;
};
} // namespace brpc
#endif // BRPC_HOTSPOTS_SERVICE_H
+38
View File
@@ -0,0 +1,38 @@
// 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.
#ifndef BRPC_IDS_SERVICE_H
#define BRPC_IDS_SERVICE_H
#include "brpc/builtin_service.pb.h"
namespace brpc {
class IdsService: public ids {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::IdsRequest* request,
::brpc::IdsResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_IDS_SERVICE_H
+42
View File
@@ -0,0 +1,42 @@
// 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.
#ifndef BRPC_INDEX_SERVICE_H
#define BRPC_INDEX_SERVICE_H
#include <ostream>
#include "brpc/builtin_service.pb.h"
#include "brpc/builtin/tabbed.h"
namespace brpc {
class IndexService : public index, public Tabbed {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::IndexRequest* request,
::brpc::IndexResponse* response,
::google::protobuf::Closure* done);
void GetTabInfo(brpc::TabInfoList*) const;
};
} // namespace brpc
#endif //BRPC_INDEX_SERVICE_H
+37
View File
@@ -0,0 +1,37 @@
// 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.
#ifndef BRPC_BUILTIN_JQUERY_MIN_JS_H
#define BRPC_BUILTIN_JQUERY_MIN_JS_H
#include "butil/iobuf.h"
namespace brpc {
// Get the jquery.min.js as string or IOBuf.
// We need to pack all js inside C++ code so that builtin services can be
// accessed without external resources and network connection.
const char* jquery_min_js();
const butil::IOBuf& jquery_min_js_iobuf();
const butil::IOBuf& jquery_min_js_iobuf_gzip();
} // namespace brpc
#endif // BRPC_BUILTIN_JQUERY_MIN_JS_H
+44
View File
@@ -0,0 +1,44 @@
// 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.
#ifndef BRPC_LIST_SERVICE_H
#define BRPC_LIST_SERVICE_H
#include <ostream>
#include "brpc/builtin_service.pb.h"
namespace brpc {
class Server;
class ListService : public list {
public:
explicit ListService(Server* server) : _server(server) {}
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::ListRequest* request,
::brpc::ListResponse* response,
::google::protobuf::Closure* done);
private:
Server* _server;
};
} // namespace brpc
#endif //BRPC_LIST_SERVICE_H
+30
View File
@@ -0,0 +1,30 @@
// 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.
#ifndef BRPC_BUILTIN_PPROF_PERL_H
#define BRPC_BUILTIN_PPROF_PERL_H
namespace brpc {
const char* pprof_perl();
} // namespace brpc
#endif // BRPC_BUILTIN_PPROF_PERL_H
+62
View File
@@ -0,0 +1,62 @@
// 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.
#ifndef BRPC_PPROF_SERVICE_H
#define BRPC_PPROF_SERVICE_H
#include "brpc/builtin_service.pb.h"
namespace brpc {
class PProfService : public pprof {
public:
void profile(::google::protobuf::RpcController* controller,
const ::brpc::ProfileRequest* request,
::brpc::ProfileResponse* response,
::google::protobuf::Closure* done);
void contention(::google::protobuf::RpcController* controller,
const ::brpc::ProfileRequest* request,
::brpc::ProfileResponse* response,
::google::protobuf::Closure* done);
void heap(::google::protobuf::RpcController* controller,
const ::brpc::ProfileRequest* request,
::brpc::ProfileResponse* response,
::google::protobuf::Closure* done);
void growth(::google::protobuf::RpcController* controller,
const ::brpc::ProfileRequest* request,
::brpc::ProfileResponse* response,
::google::protobuf::Closure* done);
void symbol(::google::protobuf::RpcController* controller,
const ::brpc::ProfileRequest* request,
::brpc::ProfileResponse* response,
::google::protobuf::Closure* done);
void cmdline(::google::protobuf::RpcController* controller,
const ::brpc::ProfileRequest* request,
::brpc::ProfileResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif //BRPC_PPROF_SERVICE_H
@@ -0,0 +1,38 @@
// 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.
#ifndef BRPC_PROMETHEUS_METRICS_SERVICE_H
#define BRPC_PROMETHEUS_METRICS_SERVICE_H
#include "brpc/builtin_service.pb.h"
namespace brpc {
class PrometheusMetricsService : public brpc_metrics {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::MetricsRequest* request,
::brpc::MetricsResponse* response,
::google::protobuf::Closure* done) override;
};
int DumpPrometheusMetricsToIOBuf(butil::IOBuf* output);
} // namepace brpc
#endif // BRPC_PROMETHEUS_METRICS_SERVICE_H
+53
View File
@@ -0,0 +1,53 @@
// 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.
#ifndef BRPC_PROTOBUFS_SERVICE_H
#define BRPC_PROTOBUFS_SERVICE_H
#include <ostream>
#include "brpc/builtin_service.pb.h"
namespace brpc {
class Server;
// Show DebugString of protobuf messages used in the server.
// /protobufs : list all supported messages.
// /protobufs/<msg>/ : Show DebugString() of <msg>
class ProtobufsService : public protobufs {
public:
explicit ProtobufsService(Server* server);
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::ProtobufsRequest* request,
::brpc::ProtobufsResponse* response,
::google::protobuf::Closure* done);
private:
int Init();
Server* _server;
typedef std::map<std::string, std::string> Map;
Map _map;
};
} // namespace brpc
#endif //BRPC_PROTOBUFS_SERVICE_H
+66
View File
@@ -0,0 +1,66 @@
// 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.
#ifndef BRPC_RPCZ_SERVICE_H
#define BRPC_RPCZ_SERVICE_H
#include "brpc/builtin_service.pb.h"
#include "brpc/builtin/tabbed.h"
namespace brpc {
class RpczService : public rpcz, public Tabbed {
public:
void enable(::google::protobuf::RpcController* cntl_base,
const ::brpc::RpczRequest* request,
::brpc::RpczResponse* response,
::google::protobuf::Closure* done);
void disable(::google::protobuf::RpcController* cntl_base,
const ::brpc::RpczRequest* request,
::brpc::RpczResponse* response,
::google::protobuf::Closure* done);
void stats(::google::protobuf::RpcController* cntl_base,
const ::brpc::RpczRequest* request,
::brpc::RpczResponse* response,
::google::protobuf::Closure* done);
void hex_log_id(::google::protobuf::RpcController* cntl_base,
const ::brpc::RpczRequest* request,
::brpc::RpczResponse* response,
::google::protobuf::Closure* done);
void dec_log_id(::google::protobuf::RpcController* cntl_base,
const ::brpc::RpczRequest* request,
::brpc::RpczResponse* response,
::google::protobuf::Closure* done);
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::RpczRequest* request,
::brpc::RpczResponse* response,
::google::protobuf::Closure* done);
void GetTabInfo(brpc::TabInfoList*) const;
};
} // namespace brpc
#endif // BRPC_RPCZ_SERVICE_H
+38
View File
@@ -0,0 +1,38 @@
// 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.
#ifndef BRPC_SOCKETS_SERVICE_H
#define BRPC_SOCKETS_SERVICE_H
#include "brpc/builtin_service.pb.h"
namespace brpc {
class SocketsService : public sockets {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::SocketsRequest* request,
::brpc::SocketsResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_SOCKETS_SERVICE_H
+36
View File
@@ -0,0 +1,36 @@
// 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.
#ifndef BRPC_BUILTIN_SORTTABLE_JS_H
#define BRPC_BUILTIN_SORTTABLE_JS_H
#include "butil/iobuf.h"
namespace brpc {
// Get the sorttable.js as string or IOBuf.
// We need to pack all js inside C++ code so that builtin services can be
// accessed without external resources and network connection.
const char* sorttable_js();
const butil::IOBuf& sorttable_js_iobuf();
} // namespace brpc
#endif // BRPC_BUILTIN_SORTTABLE_JS_H
+43
View File
@@ -0,0 +1,43 @@
// 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.
#ifndef BRPC_STATUS_SERVICE_H
#define BRPC_STATUS_SERVICE_H
#include "brpc/builtin_service.pb.h"
#include "brpc/builtin/tabbed.h"
namespace brpc {
class Server;
class StatusService : public status, public Tabbed {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::StatusRequest* request,
::brpc::StatusResponse* response,
::google::protobuf::Closure* done);
void GetTabInfo(TabInfoList* info_list) const;
};
} // namespace brpc
#endif //BRPC_STATUS_SERVICE_H
+88
View File
@@ -0,0 +1,88 @@
// 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.
#ifndef BRPC_BUILTIN_TABBED_H
#define BRPC_BUILTIN_TABBED_H
#include <string>
#include <vector>
namespace brpc {
// Contain the information for showing a tab.
struct TabInfo {
std::string tab_name;
std::string path;
bool valid() const { return !tab_name.empty() && !path.empty(); }
};
// For appending TabInfo
class TabInfoList {
public:
TabInfoList() {}
TabInfo* add() {
_list.push_back(TabInfo());
return &_list[_list.size() - 1];
}
size_t size() const { return _list.size(); }
const TabInfo& operator[](size_t i) const { return _list[i]; }
void resize(size_t newsize) { _list.resize(newsize); }
private:
TabInfoList(const TabInfoList&);
void operator=(const TabInfoList&);
std::vector<TabInfo> _list;
};
// Inherit this class to show the service with one or more tabs.
// NOTE: tabbed services are not shown in /status.
// Example:
// #include <brpc/builtin/common.h>
// ...
// void MySerivce::GetTabInfo(brpc::TabInfoList* info_list) const {
// brpc::TabInfo* info = info_list->add();
// info->tab_name = "my_tab";
// info->path = "/MyService/MyMethod";
// }
// void MyService::MyMethod(::google::protobuf::RpcController* controller,
// const XXXRequest* request,
// XXXResponse* response,
// ::google::protobuf::Closure* done) {
// ...
// if (use_html) {
// os << "<!DOCTYPE html><html><head>\n"
// << "<script language=\"javascript\" type=\"text/javascript\" src=\"/js/jquery_min\"></script>\n"
// << brpc::TabsHead() << "</head><body>";
// cntl->server()->PrintTabsBody(os, "my_tab");
// }
// ...
// if (use_html) {
// os << "</body></html>";
// }
// }
// Note: don't forget the jquery.
class Tabbed {
public:
virtual ~Tabbed() = default;
virtual void GetTabInfo(TabInfoList* info_list) const = 0;
};
} // namespace brpc
#endif // BRPC_BUILTIN_TABBED_H
+39
View File
@@ -0,0 +1,39 @@
// 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.
#ifndef BRPC_THREADS_SERVICE_H
#define BRPC_THREADS_SERVICE_H
#include <ostream>
#include "brpc/builtin_service.pb.h"
namespace brpc {
class ThreadsService : public threads {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::ThreadsRequest* request,
::brpc::ThreadsResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif //BRPC_THREADS_SERVICE_H
+41
View File
@@ -0,0 +1,41 @@
// 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.
#ifndef BRPC_VARS_SERVICE_H
#define BRPC_VARS_SERVICE_H
#include "brpc/builtin_service.pb.h"
#include "brpc/builtin/tabbed.h"
namespace brpc {
class VarsService : public vars, public Tabbed {
public:
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::VarsRequest* request,
::brpc::VarsResponse* response,
::google::protobuf::Closure* done);
void GetTabInfo(TabInfoList* info_list) const;
};
} // namespace brpc
#endif // BRPC_VARS_SERVICE_H
+45
View File
@@ -0,0 +1,45 @@
// 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.
#ifndef BRPC_VERSION_SERVICE_H
#define BRPC_VERSION_SERVICE_H
#include <ostream>
#include "brpc/builtin_service.pb.h"
namespace brpc {
class Server;
class VersionService : public version {
public:
explicit VersionService(Server* server) : _server(server) {}
void default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::VersionRequest* request,
::brpc::VersionResponse* response,
::google::protobuf::Closure* done);
private:
Server* _server;
};
} // namespace brpc
#endif //BRPC_VERSION_SERVICE_H
+37
View File
@@ -0,0 +1,37 @@
// 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.
#ifndef BRPC_BUILTIN_VIZ_MIN_JS_H
#define BRPC_BUILTIN_VIZ_MIN_JS_H
#include "butil/iobuf.h"
namespace brpc {
// Get the viz.min.js as string or IOBuf.
// We need to pack all js inside C++ code so that builtin services can be
// accessed without external resources and network connection.
const char* viz_min_js();
const butil::IOBuf& viz_min_js_iobuf();
const butil::IOBuf& viz_min_js_iobuf_gzip();
} // namespace brpc
#endif // BRPC_BUILTIN_VIZ_MIN_JS_H
+42
View File
@@ -0,0 +1,42 @@
// 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.
#ifndef BRPC_VLOG_SERVICE_H
#define BRPC_VLOG_SERVICE_H
#if !BRPC_WITH_GLOG
#include <ostream>
#include "brpc/builtin_service.pb.h"
namespace brpc {
class VLogService : public vlog {
public:
void default_method(::google::protobuf::RpcController* controller,
const ::brpc::VLogRequest* request,
::brpc::VLogResponse* response,
::google::protobuf::Closure* done);
};
} // namespace brpc
#endif // BRPC_WITH_GLOG
#endif //BRPC_VLOG_SERVICE_H
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+246
View File
@@ -0,0 +1,246 @@
// 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.
#ifndef BRPC_CHANNEL_H
#define BRPC_CHANNEL_H
// To brpc developers: This is a header included by user, don't depend
// on internal structures, use opaque pointers instead.
#include <ostream> // std::ostream
#include "bthread/errno.h" // Redefine errno
#include "butil/intrusive_ptr.hpp" // butil::intrusive_ptr
#include "butil/ptr_container.h"
#include "brpc/ssl_options.h" // ChannelSSLOptions
#include "brpc/channel_base.h" // ChannelBase
#include "brpc/adaptive_protocol_type.h" // AdaptiveProtocolType
#include "brpc/adaptive_connection_type.h" // AdaptiveConnectionType
#include "brpc/socket_id.h" // SocketId
#include "brpc/controller.h" // brpc::Controller
#include "brpc/details/profiler_linker.h"
#include "brpc/retry_policy.h"
#include "brpc/naming_service_filter.h"
namespace brpc {
struct ChannelOptions {
// Constructed with default options.
ChannelOptions();
// Issue error when a connection is not established after so many
// milliseconds. -1 means wait indefinitely.
// Default: 200 (milliseconds)
// Maximum: 0x7fffffff (roughly 30 days)
int32_t connect_timeout_ms;
// Max duration of RPC over this Channel. -1 means wait indefinitely.
// Overridable by Controller.set_timeout_ms().
// Default: 500 (milliseconds)
// Maximum: 0x7fffffff (roughly 30 days)
int32_t timeout_ms;
// Send another request if RPC does not finish after so many milliseconds.
// Overridable by Controller.set_backup_request_ms().
// The request will be sent to a different server by best effort.
// If timeout_ms is set and backup_request_ms >= timeout_ms, backup request
// will never be sent.
// backup request does NOT imply server-side cancelation.
// Default: -1 (disabled)
// Maximum: 0x7fffffff (roughly 30 days)
int32_t backup_request_ms;
// Retry limit for RPC over this Channel. <=0 means no retry.
// Overridable by Controller.set_max_retry().
// Default: 3
// Maximum: INT_MAX
int max_retry;
// When the error rate of a server node is too high, isolate the node.
// Note that this isolation is GLOBAL, the node will become unavailable
// for all channels running in this process during the isolation.
// Default: false
bool enable_circuit_breaker;
// Serialization protocol, defined in src/brpc/options.proto
// NOTE: You can assign name of the protocol to this field as well, for
// Example: options.protocol = "baidu_std";
AdaptiveProtocolType protocol;
// Type of connection to server. If unset, use the default connection type
// of the protocol.
// NOTE: You can assign name of the type to this field as well, for
// Example: options.connection_type = "single";
// Possible values: "single", "pooled", "short".
AdaptiveConnectionType connection_type;
// Channel.Init() succeeds even if there's no server in the NamingService.
// E.g. the BNS directory is empty. All RPC over the channel will fail before
// new nodes being added to the NamingService.
// Default: true (false before r32470)
bool succeed_without_server;
// Print a log when above situation happens.
// Default: true.
bool log_succeed_without_server;
// SSL related options. Refer to `ChannelSSLOptions' for details
bool has_ssl_options() const { return _ssl_options != NULL; }
const ChannelSSLOptions& ssl_options() const { return *_ssl_options.get(); }
ChannelSSLOptions* mutable_ssl_options();
// Let this channel use rdma rather than tcp.
// Default: false
bool use_rdma;
// Turn on authentication for this channel if `auth' is not NULL.
// Note `auth' will not be deleted by channel and must remain valid when
// the channel is being used.
// Default: NULL
const Authenticator* auth;
// Customize the error code that should be retried. The interface is
// defined in src/brpc/retry_policy.h
// This object is NOT owned by channel and should remain valid when
// channel is used.
// Default: NULL
const RetryPolicy* retry_policy;
// Filter ServerNodes (i.e. based on `tag' field of `ServerNode')
// which are generated by NamingService. The interface is defined
// in src/brpc/naming_service_filter.h
// This object is NOT owned by channel and should remain valid when
// channel is used.
// Default: NULL
const NamingServiceFilter* ns_filter;
// Channels with same connection_group share connections.
// In other words, set to a different value to stop sharing connections.
// Case-sensitive, leading and trailing spaces are ignored.
// Default: ""
std::string connection_group;
private:
// SSLOptions is large and not often used, allocate it on heap to
// prevent ChannelOptions from being bloated in most cases.
butil::PtrContainer<ChannelSSLOptions> _ssl_options;
};
// A Channel represents a communication line to one server or multiple servers
// which can be used to call that Server's services. Servers may be running
// on another machines. Normally, you should not call a Channel directly, but
// instead construct a stub Service wrapping it.
// Example:
// brpc::Channel channel;
// channel.Init("bns://rdev.matrix.all", "rr", NULL/*default options*/);
// MyService_Stub stub(&channel);
// stub.MyMethod(&controller, &request, &response, NULL);
class Channel : public ChannelBase {
friend class Controller;
friend class SelectiveChannel;
public:
Channel(ProfilerLinker = ProfilerLinker());
~Channel();
// Connect this channel to a single server whose address is given by the
// first parameter. Use default options if `options' is NULL.
int Init(butil::EndPoint server_addr_and_port, const ChannelOptions* options);
int Init(const char* server_addr_and_port, const ChannelOptions* options);
int Init(const char* server_addr, int port, const ChannelOptions* options);
// Connect this channel to a group of servers whose addresses can be
// accessed via `naming_service_url' according to its protocol. Use the
// method specified by `load_balancer_name' to distribute traffic to
// servers. Use default options if `options' is NULL.
// Supported naming service("protocol://service_name"):
// bns://<node-name> # Baidu Naming Service
// file://<file-path> # load addresses from the file
// list://addr1,addr2,... # use the addresses separated by comma
// http://<url> # Domain Naming Service, aka DNS.
// Supported load balancer:
// rr # round robin, choose next server
// random # randomly choose a server
// la # locality aware
// c_murmurhash/c_md5 # consistent hashing with murmurhash3/md5
// "" or NULL # treat `naming_service_url' as `server_addr_and_port'
// # Init(xxx, "", options) and Init(xxx, NULL, options)
// # are exactly same with Init(xxx, options)
int Init(const char* naming_service_url,
const char* load_balancer_name,
const ChannelOptions* options);
// Call `method' of the remote service with `request' as input, and
// `response' as output. `controller' contains options and extra data.
// If `done' is not NULL, this method returns after request was sent
// and `done->Run()' will be called when the call finishes, otherwise
// caller blocks until the call finishes.
void CallMethod(const google::protobuf::MethodDescriptor* method,
google::protobuf::RpcController* controller,
const google::protobuf::Message* request,
google::protobuf::Message* response,
google::protobuf::Closure* done);
// Get current options.
const ChannelOptions& options() const { return _options; }
void Describe(std::ostream&, const DescribeOptions&) const;
// Sum of weights of servers that this channel connects to.
int Weight();
protected:
int CheckHealth();
bool SingleServer() const { return _lb.get() == NULL; }
// Pick a server using `lb' and then send RPC. Wait for response when
// sending synchronous RPC.
// NOTE: DO NOT directly use `controller' after this call when
// sending asynchronous RPC (controller->_done != NULL) since
// user callback `done' could be called when it returns and
// therefore destroy the `controller' inside `done'
static void CallMethodImpl(Controller* controller, SharedLoadBalancer* lb);
int InitChannelOptions(const ChannelOptions* options);
int InitSingle(const butil::EndPoint& server_addr_and_port,
const char* raw_server_address,
const ChannelOptions* options,
int raw_port = -1);
std::string _service_name;
std::string _scheme;
butil::EndPoint _server_address;
SocketId _server_id;
Protocol::SerializeRequest _serialize_request;
Protocol::PackRequest _pack_request;
Protocol::GetMethodName _get_method_name;
// This will be shared between channel and controllers that
// are in the middle of RPC procedure using this channel.
// It will be destroyed after channel's destruction and all
// the RPC above has finished
butil::intrusive_ptr<SharedLoadBalancer> _lb;
ChannelOptions _options;
int _preferred_index;
};
enum ChannelOwnership {
OWNS_CHANNEL,
DOESNT_OWN_CHANNEL
};
} // namespace brpc
#endif // BRPC_CHANNEL_H
+49
View File
@@ -0,0 +1,49 @@
// 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.
#ifndef BRPC_CHANNEL_BASE_H
#define BRPC_CHANNEL_BASE_H
#include <stdlib.h>
#include <ostream>
#include "butil/logging.h"
#include <google/protobuf/service.h> // google::protobuf::RpcChannel
#include "brpc/describable.h"
// To brpc developers: This is a header included by user, don't depend
// on internal structures, use opaque pointers instead.
namespace brpc {
// Base of all brpc channels.
class ChannelBase : public google::protobuf::RpcChannel/*non-copyable*/,
public Describable {
public:
virtual int Weight() {
CHECK(false) << "Not implemented";
abort();
};
virtual int CheckHealth() = 0;
};
} // namespace brpc
#endif // BRPC_CHANNEL_BASE_H
+94
View File
@@ -0,0 +1,94 @@
// 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.
#ifndef BRPC_CIRCUIT_BREAKER_H
#define BRPC_CIRCUIT_BREAKER_H
#include "butil/atomicops.h"
namespace brpc {
class CircuitBreaker {
public:
CircuitBreaker();
~CircuitBreaker() {}
// Sampling the current rpc. Returns false if a node needs to
// be isolated. Otherwise return true.
// error_code: Error_code of this call, 0 means success.
// latency: Time cost of this call.
// Note: Once OnCallEnd() determined that a node needs to be isolated,
// it will always return false until you call Reset(). Usually Reset()
// will be called in the health check thread.
bool OnCallEnd(int error_code, int64_t latency);
// Reset CircuitBreaker and clear history data. will erase the historical
// data and start sampling again. Before you call this method, you need to
// ensure that no one else is accessing CircuitBreaker.
void Reset();
// Mark the Socket as broken. Call this method when you want to isolate a
// node in advance. When this method is called multiple times in succession,
// only the first call will take effect.
void MarkAsBroken();
// Number of times marked as broken
int isolated_times() const {
return _isolated_times.load(butil::memory_order_relaxed);
}
// The duration that should be isolated when the socket fails in milliseconds.
// The higher the frequency of socket errors, the longer the duration.
int isolation_duration_ms() const {
return _isolation_duration_ms.load(butil::memory_order_relaxed);
}
private:
void UpdateIsolationDuration();
class EmaErrorRecorder {
public:
EmaErrorRecorder(int windows_size, int max_error_percent);
bool OnCallEnd(int error_code, int64_t latency);
void Reset();
private:
int64_t UpdateLatency(int64_t latency);
bool UpdateErrorCost(int64_t latency, int64_t ema_latency);
const int _window_size;
const int _max_error_percent;
const double _smooth;
butil::atomic<int32_t> _sample_count_when_initializing;
butil::atomic<int32_t> _error_count_when_initializing;
butil::atomic<int64_t> _ema_error_cost;
butil::atomic<int64_t> _ema_latency;
};
EmaErrorRecorder _long_window;
EmaErrorRecorder _short_window;
int64_t _last_reset_time_ms;
butil::atomic<int> _isolation_duration_ms;
butil::atomic<int> _isolated_times;
butil::atomic<bool> _broken;
};
} // namespace brpc
#endif // BRPC_CIRCUIT_BREAKER_H_
+74
View File
@@ -0,0 +1,74 @@
// 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.
#ifndef BRPC_CLOSURE_GUARD_H
#define BRPC_CLOSURE_GUARD_H
#include <google/protobuf/service.h>
#include "butil/macros.h"
namespace brpc {
// RAII: Call Run() of the closure on destruction.
class ClosureGuard {
public:
ClosureGuard() : _done(NULL) {}
// Constructed with a closure which will be Run() inside dtor.
explicit ClosureGuard(google::protobuf::Closure* done) : _done(done) {}
// Run internal closure if it's not NULL.
~ClosureGuard() {
if (_done) {
_done->Run();
}
}
// Run internal closure if it's not NULL and set it to `done'.
void reset(google::protobuf::Closure* done) {
if (_done) {
_done->Run();
}
_done = done;
}
// Return and set internal closure to NULL.
google::protobuf::Closure* release() {
google::protobuf::Closure* const prev_done = _done;
_done = NULL;
return prev_done;
}
// True if no closure inside.
bool empty() const { return _done == NULL; }
// Exchange closure with another guard.
void swap(ClosureGuard& other) { std::swap(_done, other._done); }
private:
// Copying this object makes no sense.
DISALLOW_COPY_AND_ASSIGN(ClosureGuard);
google::protobuf::Closure* _done;
};
} // namespace brpc
#endif // BRPC_CLOSURE_GUARD_H
+89
View File
@@ -0,0 +1,89 @@
// 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.
#ifndef BRPC_CLUSTER_RECOVER_POLICY
#define BRPC_CLUSTER_RECOVER_POLICY
#include <cstdint>
#include <memory>
#include "butil/synchronization/lock.h"
#include "butil/strings/string_piece.h"
#include "butil/strings/string_number_conversions.h"
namespace brpc {
struct ServerId;
// After all servers are down and health check happens, servers are
// online one by one. Once one server is up, all the request that should
// be sent to all servers, would be sent to one server, which may be a
// disastrous behaviour. In the worst case it would cause the server being down
// again if circuit breaker is enabled and the cluster would never recover.
// This class controls the amount of requests that sent to the revived
// servers when recovering from all servers are down.
class ClusterRecoverPolicy {
public:
virtual ~ClusterRecoverPolicy() {}
// Indicate that recover from all server being down is happening.
virtual void StartRecover() = 0;
// Return true if some customized policies are satisfied.
virtual bool DoReject(const std::vector<ServerId>& server_list) = 0;
// Stop recover state and do not reject the request if some condition is
// satisfied. Return true if the current state is still in recovering.
virtual bool StopRecoverIfNecessary() = 0;
};
// The default cluster recover policy. Once no servers are available, recover is start.
// If in recover state, the probability that a request is accepted is q/n, in
// which q is the number of current available server, n is the number of minimum
// working instances setting by user. If q is not changed during a given time,
// hold_seconds, then the cluster is considered recovered and all the request
// would be sent to the current available servers.
class DefaultClusterRecoverPolicy : public ClusterRecoverPolicy {
public:
DefaultClusterRecoverPolicy(int64_t min_working_instances, int64_t hold_seconds);
void StartRecover() override;
bool DoReject(const std::vector<ServerId>& server_list) override;
bool StopRecoverIfNecessary() override;
private:
uint64_t GetUsableServerCount(int64_t now_ms, const std::vector<ServerId>& server_list);
private:
bool _recovering;
int64_t _min_working_instances;
butil::Mutex _mutex;
uint64_t _last_usable;
int64_t _last_usable_change_time_ms;
int64_t _hold_seconds;
uint64_t _usable_cache;
int64_t _usable_cache_time_ms;
};
// Return a DefaultClusterRecoverPolicy object by params.
bool GetRecoverPolicyByParams(const butil::StringPiece& params,
std::shared_ptr<ClusterRecoverPolicy>* ptr_out);
} // namespace brpc
#endif
+66
View File
@@ -0,0 +1,66 @@
// 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.
#ifndef BRPC_COMPRESS_H
#define BRPC_COMPRESS_H
#include <google/protobuf/message.h> // Message
#include "butil/iobuf.h" // butil::IOBuf
#include "brpc/options.pb.h" // CompressType
namespace brpc {
struct CompressHandler {
// Compress serialized `msg' into `buf'.
// Returns true on success, false otherwise
bool (*Compress)(const google::protobuf::Message& msg, butil::IOBuf* buf);
// Parse decompressed `data' as `msg'.
// Returns true on success, false otherwise
bool (*Decompress)(const butil::IOBuf& data, google::protobuf::Message* msg);
// Name of the compression algorithm, must be string constant.
const char* name;
};
// [NOT thread-safe] Register `handler' using key=`type'
// Returns 0 on success, -1 otherwise
int RegisterCompressHandler(CompressType type, CompressHandler handler);
// Returns the `name' of the CompressType if registered
const char* CompressTypeToCStr(CompressType type);
// Put all registered handlers into `vec'.
void ListCompressHandler(std::vector<CompressHandler>* vec);
// Parse decompressed `data' as `msg' using registered `compress_type'.
// Returns true on success, false otherwise
bool ParseFromCompressedData(const butil::IOBuf& data,
google::protobuf::Message* msg,
CompressType compress_type);
// Compress serialized `msg' into `buf' using registered `compress_type'.
// Returns true on success, false otherwise
bool SerializeAsCompressedData(const google::protobuf::Message& msg,
butil::IOBuf* buf,
CompressType compress_type);
} // namespace brpc
#endif // BRPC_COMPRESS_H
+61
View File
@@ -0,0 +1,61 @@
// 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.
#ifndef BRPC_CONCURRENCY_LIMITER_H
#define BRPC_CONCURRENCY_LIMITER_H
#include "brpc/describable.h"
#include "brpc/destroyable.h"
#include "brpc/extension.h" // Extension<T>
#include "brpc/adaptive_max_concurrency.h" // AdaptiveMaxConcurrency
namespace brpc {
class ConcurrencyLimiter {
public:
virtual ~ConcurrencyLimiter() {}
// This method should be called each time a request comes in. It returns
// false when the concurrency reaches the upper limit, otherwise it
// returns true. Normally, when OnRequested returns false, you should
// return an ELIMIT error directly.
virtual bool OnRequested(int current_concurrency) = 0;
// Each request should call this method before responding.
// `error_code' : Error code obtained from the controller, 0 means success.
// `latency' : Microseconds taken by RPC.
// NOTE: Even if OnRequested returns false, after sending ELIMIT, you
// still need to call OnResponded.
virtual void OnResponded(int error_code, int64_t latency_us) = 0;
// Returns the latest max_concurrency.
// The return value is only for logging.
virtual int MaxConcurrency() = 0;
// Create an instance from the amc
// Caller is responsible for delete the instance after usage.
virtual ConcurrencyLimiter* New(const AdaptiveMaxConcurrency& amc) const = 0;
};
inline Extension<const ConcurrencyLimiter>* ConcurrencyLimiterExtension() {
return Extension<const ConcurrencyLimiter>::instance();
}
} // namespace brpc
#endif // BRPC_CONCURRENCY_LIMITER_H
+875
View File
@@ -0,0 +1,875 @@
// 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.
#ifndef BRPC_CONTROLLER_H
#define BRPC_CONTROLLER_H
// To brpc developers: This is a header included by user, don't depend
// on internal structures, use opaque pointers instead.
#include <gflags/gflags.h> // Users often need gflags
#include <string>
#include "butil/intrusive_ptr.hpp" // butil::intrusive_ptr
#include "bthread/errno.h" // Redefine errno
#include "butil/endpoint.h" // butil::EndPoint
#include "butil/iobuf.h" // butil::IOBuf
#include "bthread/types.h" // bthread_id_t
#include "brpc/options.pb.h" // CompressType
#include "brpc/errno.pb.h" // error code
#include "brpc/http_header.h" // HttpHeader
#include "brpc/authenticator.h" // AuthContext
#include "brpc/socket_id.h" // SocketId
#include "brpc/stream.h" // StreamId
#include "brpc/stream_creator.h" // StreamCreator
#include "brpc/protocol.h" // Protocol
#include "brpc/traceprintf.h"
#include "brpc/reloadable_flags.h"
#include "brpc/closure_guard.h" // User often needs this
#include "brpc/callback.h"
#include "brpc/progressive_attachment.h" // ProgressiveAttachment
#include "brpc/progressive_reader.h" // ProgressiveReader
#include "brpc/grpc.h"
#include "brpc/kvmap.h"
// EAUTH is defined in MAC
#ifndef EAUTH
#define EAUTH ERPCAUTH
#endif
extern "C" {
#ifndef USE_MESALINK
struct x509_st;
#else
#include <mesalink/openssl/x509.h>
#define x509_st X509
#endif
}
namespace brpc {
class Span;
class Server;
class SharedLoadBalancer;
class ExcludedServers;
class RPCSender;
class StreamSettings;
class SampledRequest;
class MongoContext;
class RetryPolicy;
class InputMessageBase;
class ThriftStub;
namespace policy {
class OnServerStreamCreated;
void ProcessMongoRequest(InputMessageBase*);
void ProcessThriftRequest(InputMessageBase*);
}
namespace schan {
class Sender;
class SubDone;
}
// For serializing/parsing from idl services.
struct IdlNames {
const char* request_name; // must be string-constant
const char* response_name; // must be string-constant
};
extern const IdlNames idl_single_req_single_res;
extern const IdlNames idl_single_req_multi_res;
extern const IdlNames idl_multi_req_single_res;
extern const IdlNames idl_multi_req_multi_res;
// The identifier to be associated with a RPC call.
typedef bthread_id_t CallId;
// Styles for stopping progressive attachment.
enum StopStyle {
FORCE_STOP,
WAIT_FOR_STOP,
};
const int32_t UNSET_MAGIC_NUM = -123456789;
// A Controller mediates a single method call. The primary purpose of
// the controller is to provide a way to manipulate settings per RPC-call
// and to find out about RPC-level errors.
class Controller : public google::protobuf::RpcController/*non-copyable*/ {
friend class Channel;
friend class ParallelChannel;
friend class ParallelChannelDone;
friend class ControllerPrivateAccessor;
friend class ServerPrivateAccessor;
friend class SelectiveChannel;
friend class ThriftStub;
friend class schan::Sender;
friend class schan::SubDone;
friend class policy::OnServerStreamCreated;
friend int StreamCreate(StreamId*, Controller&, const StreamOptions*);
friend int StreamAccept(StreamId*, Controller&, const StreamOptions*);
friend void policy::ProcessMongoRequest(InputMessageBase*);
friend void policy::ProcessThriftRequest(InputMessageBase*);
// << Flags >>
static const uint32_t FLAGS_IGNORE_EOVERCROWDED = 1;
static const uint32_t FLAGS_SECURITY_MODE = (1 << 1);
static const uint32_t FLAGS_ADDED_CONCURRENCY = (1 << 2);
static const uint32_t FLAGS_READ_PROGRESSIVELY = (1 << 3);
static const uint32_t FLAGS_PROGRESSIVE_READER = (1 << 4);
static const uint32_t FLAGS_BACKUP_REQUEST = (1 << 5);
// Let _done delete the correlation_id, used by combo channels to
// make lifetime of the correlation_id more flexible.
static const uint32_t FLAGS_DESTROY_CID_IN_DONE = (1 << 7);
static const uint32_t FLAGS_CLOSE_CONNECTION = (1 << 8);
static const uint32_t FLAGS_LOG_ID = (1 << 9); // log_id is set
static const uint32_t FLAGS_REQUEST_CODE = (1 << 10);
static const uint32_t FLAGS_PB_BYTES_TO_BASE64 = (1 << 11);
static const uint32_t FLAGS_ALLOW_DONE_TO_RUN_IN_PLACE = (1 << 12);
static const uint32_t FLAGS_USED_BY_RPC = (1 << 13);
static const uint32_t FLAGS_PB_JSONIFY_EMPTY_ARRAY = (1 << 16);
static const uint32_t FLAGS_ENABLED_CIRCUIT_BREAKER = (1 << 17);
static const uint32_t FLAGS_ALWAYS_PRINT_PRIMITIVE_FIELDS = (1 << 18);
static const uint32_t FLAGS_HEALTH_CHECK_CALL = (1 << 19);
static const uint32_t FLAGS_PB_SINGLE_REPEATED_TO_ARRAY = (1 << 20);
static const uint32_t FLAGS_MANAGE_HTTP_BODY_ON_ERROR = (1 << 21);
public:
struct Inheritable {
Inheritable() : log_id(0) {}
void Reset() {
log_id = 0;
request_id.clear();
}
uint64_t log_id;
std::string request_id;
};
public:
Controller();
Controller(const Inheritable& parent_ctx);
~Controller();
// ------------------------------------------------------------------
// Client-side methods
// These calls shall be made from the client side only. Their results
// are undefined on the server side (may crash).
// ------------------------------------------------------------------
// Set/get timeout in milliseconds for the RPC call. Use
// ChannelOptions.timeout_ms on unset.
void set_timeout_ms(int64_t timeout_ms);
int64_t timeout_ms() const { return _timeout_ms; }
// Set/get the delay to send backup request in milliseconds. Use
// ChannelOptions.backup_request_ms on unset.
void set_backup_request_ms(int64_t timeout_ms);
int64_t backup_request_ms() const { return _backup_request_ms; }
// Set/get maximum times of retrying. Use ChannelOptions.max_retry on unset.
// <=0 means no retry.
// Conditions of retrying:
// * The connection is broken. No retry if the connection is still on.
// Use backup_request if you want to issue another request after some
// time.
// * Not timed out.
// * retried_count() < max_retry().
// * Retry may work for the error. E.g. No retry when the request is
// incorrect (EREQUEST), retrying is pointless.
void set_max_retry(int max_retry);
int max_retry() const { return _max_retry; }
// Get number of retries.
int retried_count() const { return _current_call.nretry; }
// True if a backup request was sent during the RPC.
bool has_backup_request() const { return has_flag(FLAGS_BACKUP_REQUEST); }
// This function has different meanings in client and server side.
// In client side it gets latency of the RPC call. While in server side,
// it gets queue time before server processes the RPC call.
int64_t latency_us() const {
if (_end_time_us == UNSET_MAGIC_NUM) {
return butil::cpuwide_time_us() - _begin_time_us;
}
return _end_time_us - _begin_time_us;
}
// Response of the RPC call (passed to CallMethod)
google::protobuf::Message* response() const { return _response; }
// An identifier to send to server along with request. This is widely used
// throughout baidu's servers to tag a searching session (a series of
// queries following the topology of servers) with a same log_id.
void set_log_id(uint64_t log_id);
void set_request_id(std::string request_id) { _inheritable.request_id = request_id; }
// Set type of service: http://en.wikipedia.org/wiki/Type_of_service
// Current implementation has limits: If the connection is already
// established, this setting has no effect until the connection is broken
// and re-connected. And because of connection sharing, setting different
// tos to a single connection is undefined.
void set_type_of_service(short tos) { _tos = tos; }
// Set type of connections for sending RPC.
// Use ChannelOptions.connection_type on unset.
void set_connection_type(ConnectionType type) { _connection_type = type; }
// Set compression method for request.
void set_request_compress_type(CompressType t) { _request_compress_type = t; }
// Required by some load balancers.
void set_request_code(uint64_t request_code) {
add_flag(FLAGS_REQUEST_CODE);
_request_code = request_code;
}
bool has_request_code() const { return has_flag(FLAGS_REQUEST_CODE); }
uint64_t request_code() const { return _request_code; }
// Mutable header of http request.
HttpHeader& http_request() {
if (_http_request == NULL) {
_http_request = new HttpHeader;
}
return *_http_request;
}
bool has_http_request() const { return _http_request; }
HttpHeader* release_http_request() {
HttpHeader* const tmp = _http_request;
_http_request = NULL;
return tmp;
}
// User attached data or body of http request, which is wired to network
// directly instead of being serialized into protobuf messages.
butil::IOBuf& request_attachment() { return _request_attachment; }
ConnectionType connection_type() const { return _connection_type; }
// Get the called method. May-be NULL for non-pb services.
const google::protobuf::MethodDescriptor* method() const { return _method; }
// Get the controllers for accessing sub channels in combo channels.
// Ordinary channel:
// sub_count() is 0 and sub() is always NULL.
// ParallelChannel/PartitionChannel:
// sub_count() is #sub-channels and sub(i) is the controller for
// accessing i-th sub channel inside ParallelChannel, if i is outside
// [0, sub_count() - 1], sub(i) is NULL.
// NOTE: You must test sub() against NULL, ALWAYS. Even if i is inside
// range, sub(i) can still be NULL:
// * the rpc call may fail and terminate before accessing the sub channel
// * the sub channel was skipped
// SelectiveChannel/DynamicPartitionChannel:
// sub_count() is always 1 and sub(0) is the controller of successful
// or last call to sub channels.
int sub_count() const;
const Controller* sub(int index) const;
// Get/own SampledRequest for sending dumped requests.
// Deleted along with controller.
void reset_sampled_request(SampledRequest* req);
const SampledRequest* sampled_request() { return _sampled_request; }
// Attach a StreamCreator to this RPC. Notice that the ownership of sc has
// been transferred to cntl, and sc->DestroyStreamCreator() would be called
// only once to destroy sc.
void set_stream_creator(StreamCreator* sc);
// Make the RPC end when the HTTP response has complete headers and let
// user read the remaining body by using ReadProgressiveAttachmentBy().
void response_will_be_read_progressively() { add_flag(FLAGS_READ_PROGRESSIVELY); }
// True if response_will_be_read_progressively() was called.
bool is_response_read_progressively() const { return has_flag(FLAGS_READ_PROGRESSIVELY); }
// Read the remaining body after RPC:
// - This function can only be called once.
// - If user called response_will_be_read_progressively() but
// ReadProgressiveAttachmentBy(), controller will set a reader ignoring
// all bytes read before self's Reset() or dtor.
// - If user did not call response_will_be_read_progressively() and calls
// ReadProgressiveAttachmentBy(), the reader is Destroyed() immediately.
// - Any error occurred will destroy the reader by calling r->Destroy().
// - r->Destroy() is guaranteed to be called once and only once.
void ReadProgressiveAttachmentBy(ProgressiveReader* r);
// True if ReadProgressiveAttachmentBy() was ever called successfully.
bool has_progressive_reader() const { return has_flag(FLAGS_PROGRESSIVE_READER); }
// RPC may fail with EOVERCROWDED if the socket to write is too full
// (limited by -socket_max_unwritten_bytes). In some scenarios, user
// may wish to suppress the error completely. To do this, call this
// method before doing the RPC.
void ignore_eovercrowded() { add_flag(FLAGS_IGNORE_EOVERCROWDED); }
// Set if the field of bytes in protobuf message should be encoded
// to base64 string in HTTP request.
void set_pb_bytes_to_base64(bool f) { set_flag(FLAGS_PB_BYTES_TO_BASE64, f); }
bool has_pb_bytes_to_base64() const { return has_flag(FLAGS_PB_BYTES_TO_BASE64); }
// Set if the single repeated field in protobuf message should be encoded
// as array when serialize/deserialize to/from json.
void set_pb_single_repeated_to_array(bool f) { set_flag(FLAGS_PB_SINGLE_REPEATED_TO_ARRAY, f); }
bool has_pb_single_repeated_to_array() const { return has_flag(FLAGS_PB_SINGLE_REPEATED_TO_ARRAY); }
// Set if convert the repeated field that has no entry to a empty array
// of json in HTTP response.
void set_pb_jsonify_empty_array(bool f) { set_flag(FLAGS_PB_JSONIFY_EMPTY_ARRAY, f); }
bool has_pb_jsonify_empty_array() const { return has_flag(FLAGS_PB_JSONIFY_EMPTY_ARRAY); }
// Whether to always print primitive fields. By default proto3 primitive
// fields with default values will be omitted in JSON output. For example, an
// int32 field set to 0 will be omitted. Set this flag to true will override
// the default behavior and print primitive fields regardless of their values.
void set_always_print_primitive_fields(bool f) { set_flag(FLAGS_ALWAYS_PRINT_PRIMITIVE_FIELDS, f); }
bool has_always_print_primitive_fields() const { return has_flag(FLAGS_ALWAYS_PRINT_PRIMITIVE_FIELDS); }
// Tell RPC that done of the RPC can be run in the same thread where
// the RPC is issued, otherwise done is always run in a different thread.
// In current implementation, this option only affects RPC that fails
// before sending the request.
// This option is *rarely* needed by ordinary users. Don't set this option
// if you don't know the consequences. Read implementions in channel.cpp
// and controller.cpp to know more.
void allow_done_to_run_in_place()
{ add_flag(FLAGS_ALLOW_DONE_TO_RUN_IN_PLACE); }
// True iff above method was called.
bool is_done_allowed_to_run_in_place() const
{ return has_flag(FLAGS_ALLOW_DONE_TO_RUN_IN_PLACE); }
// ------------------------------------------------------------------------
// Server-side methods.
// These calls shall be made from the server side only. Their results are
// undefined on the client side (may crash).
// ------------------------------------------------------------------------
// Returns true if the client canceled the RPC or the connection has broken,
// so the server may as well give up on replying to it. The server should still
// call the final "done" callback.
// Note: Reaching deadline of the RPC would not affect this function, which means
// even if deadline has been reached, this function may still return false.
bool IsCanceled() const override;
// Asks that the given callback be called when the RPC is canceled or the
// connection has broken. The callback will always be called exactly once.
// If the RPC completes without being canceled/broken connection, the callback
// will be called after completion. If the RPC has already been canceled/broken
// when NotifyOnCancel() is called, the callback will be called immediately.
//
// NotifyOnCancel() must be called no more than once per request.
void NotifyOnCancel(google::protobuf::Closure* callback) override;
// Returns the authenticated result. NULL if there is no authentication
const AuthContext* auth_context() const { return _auth_context; }
// Whether the underlying channel is using SSL
bool is_ssl() const;
// Get the peer certificate, which can be printed by ostream
x509_st* get_peer_certificate() const;
// Mutable header of http response.
HttpHeader& http_response() {
if (_http_response == NULL) {
_http_response = new HttpHeader;
}
return *_http_response;
}
bool has_http_response() const { return _http_response; }
HttpHeader* release_http_response() {
HttpHeader* const tmp = _http_response;
_http_response = NULL;
return tmp;
}
// User attached data or body of http response, which is wired to network
// directly instead of being serialized into protobuf messages.
butil::IOBuf& response_attachment() { return _response_attachment; }
// Response Body of a failed HTTP call is set to be ErrorText() by default,
// even if response_attachment() is non-empty.
// If this flag is true, the http body of a failed HTTP call will not be
// replaced by ErrorText() and should be managed by user self.
void manage_http_body_on_error(bool manage_or_not)
{ set_flag(FLAGS_MANAGE_HTTP_BODY_ON_ERROR, manage_or_not); }
bool does_manage_http_body_on_error() const
{ return has_flag(FLAGS_MANAGE_HTTP_BODY_ON_ERROR); }
// Create a ProgressiveAttachment to write (often after RPC).
// If `stop_style' is FORCE_STOP, the underlying socket will be failed
// immediately when the socket becomes idle or server is stopped.
// Default value of `stop_style' is WAIT_FOR_STOP.
butil::intrusive_ptr<ProgressiveAttachment>
CreateProgressiveAttachment(StopStyle stop_style = WAIT_FOR_STOP);
bool has_progressive_writer() const { return _wpa != NULL; }
// Set compression method for response.
void set_response_compress_type(CompressType t) { _response_compress_type = t; }
// Non-zero when this RPC call is traced (by rpcz or rig).
// NOTE: Only valid at server-side, always zero at client-side.
uint64_t trace_id() const;
uint64_t span_id() const;
// Tell RPC to close the connection instead of sending back response.
// If this controller was not SetFailed() before, ErrorCode() will be
// set to ECLOSE.
// NOTE: the underlying connection is not closed immediately.
void CloseConnection(const char* reason_fmt, ...);
// True if CloseConnection() was called.
bool IsCloseConnection() const { return has_flag(FLAGS_CLOSE_CONNECTION); }
// ServerOptions.security_mode is turned on, and the RPC is from
// connections accepted from port (rather than internal_port)
bool is_security_mode() const { return has_flag(FLAGS_SECURITY_MODE); }
// The server running this RPC session.
// Always NULL at client-side.
const Server* server() const { return _server; }
// Get the data attached to current RPC session. The data is created by
// ServerOptions.session_local_data_factory and reused between different
// RPC. If factory is NULL, this method returns NULL.
void* session_local_data();
// Get the data attached to a mongo session(practically a socket).
MongoContext* mongo_session_data() { return _mongo_session_data.get(); }
// -------------------------------------------------------------------
// Both-side methods.
// Following methods can be called from both client and server. But they
// may have different or opposite semantics.
// -------------------------------------------------------------------
// Client-side: successful or last server called. Accessible from
// PackXXXRequest() in protocols.
// Server-side: returns the client sending the request
butil::EndPoint remote_side() const { return _remote_side; }
// Client-side: the local address for talking with server, undefined until
// this RPC succeeds (because the connection may not be established
// before RPC).
// Server-side: the address that clients access.
butil::EndPoint local_side() const { return _local_side; }
// Protocol of the request sent by client or received by server.
ProtocolType request_protocol() const { return _request_protocol; }
// Resets the Controller to its initial state so that it may be reused in
// a new call. Must NOT be called while an RPC is in progress.
void Reset() override {
ResetNonPods();
ResetPods();
}
// Causes Failed() to return true on the client side. "reason" will be
// incorporated into the message returned by ErrorText().
// NOTE: Change http_response().status_code() according to `error_code'
// as well if the protocol is HTTP. If you want to overwrite the
// status_code, call http_response().set_status_code() after SetFailed()
// (rather than before SetFailed)
void SetFailed(const std::string& reason) override;
void SetFailed(int error_code, const char* reason_fmt, ...)
__attribute__ ((__format__ (__printf__, 3, 4)));
// After a call has finished, returns true if the RPC call failed.
// The response to Channel is undefined when Failed() is true.
// Calling Failed() before a call has finished is undefined.
bool Failed() const override;
// If Failed() is true, return description of the errors.
// NOTE: ErrorText() != berror(ErrorCode()).
std::string ErrorText() const override;
// Last error code. Equals 0 iff Failed() is false.
// If there's retry, latter code overwrites former one.
int ErrorCode() const { return _error_code; }
// Getters:
const Inheritable& inheritable() { return _inheritable; }
bool has_log_id() const { return has_flag(FLAGS_LOG_ID); }
uint64_t log_id() const { return _inheritable.log_id; }
const std::string& request_id() const { return _inheritable.request_id; }
CompressType request_compress_type() const { return _request_compress_type; }
CompressType response_compress_type() const { return _response_compress_type; }
const HttpHeader& http_request() const
{ return _http_request != NULL ? *_http_request : DefaultHttpHeader(); }
const HttpHeader& http_response() const
{ return _http_response != NULL ? *_http_response : DefaultHttpHeader(); }
const butil::IOBuf& request_attachment() const { return _request_attachment; }
const butil::IOBuf& response_attachment() const { return _response_attachment; }
// Get the object to write key/value which will be flushed into
// LOG(INFO) when this controller is deleted.
KVMap& SessionKV();
// Flush SessionKV() into `os'
void FlushSessionKV(std::ostream& os);
// Contextual prefixes for LOGD/LOGI/LOGW/LOGE/LOGF macros
class LogPrefixDummy {
public:
LogPrefixDummy(const Controller* cntl) : _cntl(cntl) {}
void DoPrintLogPrefix(std::ostream& os) const { _cntl->DoPrintLogPrefix(os); }
private:
const Controller* _cntl;
};
friend class LogPrefixDummy;
LogPrefixDummy LogPrefix() const { return LogPrefixDummy(this); }
// Return true if the remote side creates a stream.
bool has_remote_stream() { return _remote_stream_settings != NULL; }
// The id to cancel RPC call or join response.
CallId call_id();
// Get/set idl names. Notice that the names must be string-constant.
// int32_t Echo(EchoRequest req, EchoResponse res);
// ^ ^
// request_name response_name
void set_idl_names(const IdlNames& names) { _idl_names = names; }
IdlNames idl_names() const { return _idl_names; }
// Get/set idl result. The type is limited to be integral.
// int32_t Echo(EchoRequest req, EchoResponse res);
// ^
// result
void set_idl_result(int64_t result) { _idl_result = result; }
int64_t idl_result() const { return _idl_result; }
const std::string& thrift_method_name() { return _thrift_method_name; }
// Get sock option. .e.g get vip info through ttm kernel module hook,
int GetSockOption(int level, int optname, void* optval, socklen_t* optlen);
// Get deadline of this RPC (since the Epoch in microseconds).
// -1 means no deadline.
int64_t deadline_us() const { return _deadline_us; }
private:
struct CompletionInfo {
CallId id; // call_id of the corresponding request
bool responded; // triggered by a response rather than other errors
};
// Call this method when receiving response/failure. If RPC failed,
// it will try to retry this RPC. Otherwise, it calls user `done'
// if it exists and destroys the correlation_id. Note that
// the correlation_id MUST have been locked before this call.
// Parameter `new_bthread':
// false - Run this function in the current bthread/pthread. Note that
// it could last for a long time or even block the caller (as
// it contains user's `done')
// true - Creates a new bthread to run this function and returns to
// the caller immediately
// Parameter `id':
// It will be used to checked against `_correlation_id' and
// `_current_call.nretry'. If not matched, nothing will happen,
// which means this event has been processed before
// Parameter `saved_error':
// If the above check failed, `_error_code' will be reverted to this
void OnVersionedRPCReturned(const CompletionInfo&,
bool new_bthread, int saved_error);
static void* RunEndRPC(void* arg);
void EndRPC(const CompletionInfo&);
static int HandleSocketFailed(bthread_id_t, void* data, int error_code,
const std::string& error_text);
void HandleSendFailed();
static int RunOnCancel(bthread_id_t, void* data, int error_code);
void set_auth_context(const AuthContext* ctx);
// MongoContext is created by ParseMongoRequest when the first msg comes
// over a socket, then stored in MongoContextMessage of the socket. cntl
// gets a shared reference of the data in PocessMongoRequest. When socket
// is recycled, the container, AKA MongoContextMessage is destroyed, which
// has no infuluence on the cntl(s) who already gets the shared reference
// of the MongoContext. The MongoContext will not be recycled until both
// the container(MongoContextMessage) and all related cntl(s) are recycled.
void set_mongo_session_data(MongoContext* data);
// Reset POD/non-POD fields.
void ResetPods();
void ResetNonPods();
void StartCancel() override;
// Using fixed start_realtime_us (microseconds since the Epoch) gives
// more accurate deadline.
void IssueRPC(int64_t start_realtime_us);
struct ClientSettings {
int32_t timeout_ms;
int32_t backup_request_ms;
int max_retry;
int32_t tos;
ConnectionType connection_type;
CompressType request_compress_type;
uint64_t log_id;
bool has_request_code;
int64_t request_code;
};
void SaveClientSettings(ClientSettings*) const;
void ApplyClientSettings(const ClientSettings&);
bool FailedInline() const { return _error_code; }
CallId get_id(int nretry) const {
CallId id = { _correlation_id.value + nretry + 1 };
return id;
}
// Tell RPC that this particular call is used to do health check.
bool is_health_check_call() const { return has_flag(FLAGS_HEALTH_CHECK_CALL); }
public:
CallId current_id() const {
CallId id = { _correlation_id.value + _current_call.nretry + 1 };
return id;
}
private:
// Append server information to `_error_text'
void AppendServerIdentiy();
// Contexts for tracking and ending a sent request.
// One RPC to a channel may send several requests due to retrying.
struct Call {
Call() { Reset(); }
Call(Call*); //move semantics
~Call();
void Reset();
void OnComplete(Controller* c, int error_code, bool responded, bool end_of_rpc);
int nretry; // sent in nretry-th retry.
bool need_feedback; // The LB needs feedback.
bool enable_circuit_breaker; // The channel enabled circuit_breaker
bool touched_by_stream_creator;
SocketId peer_id; // main server id
int64_t begin_time_us; // sent real time.
// The actual `Socket' for sending RPC. It's socket id will be
// exactly the same as `peer_id' if `_connection_type' is
// CONNECTION_TYPE_SINGLE. Otherwise, it may be a temporary
// socket fetched from socket pool
SocketUniquePtr sending_sock;
StreamUserData* stream_user_data;
};
void HandleStreamConnection(Socket *host_socket);
bool SingleServer() const { return _single_server_id != INVALID_SOCKET_ID; }
void SubmitSpan();
void OnRPCBegin(int64_t begin_time_us) {
_begin_time_us = begin_time_us;
// make latency_us() return 0 when RPC is not over
_end_time_us = begin_time_us;
}
void OnRPCEnd(int64_t end_time_us) {
_end_time_us = end_time_us;
}
static void RunDoneInBackupThread(void*);
void DoneInBackupThread();
// Utilities for manipulating _flags
inline void add_flag(uint32_t f) { _flags |= f; }
inline void clear_flag(uint32_t f) { _flags &= ~f; }
inline void set_flag(uint32_t f, bool t)
{ return t ? add_flag(f) : clear_flag(f); }
inline bool has_flag(uint32_t f) const { return _flags & f; }
void set_used_by_rpc() { add_flag(FLAGS_USED_BY_RPC); }
bool is_used_by_rpc() const { return has_flag(FLAGS_USED_BY_RPC); }
bool has_enabled_circuit_breaker() const {
return has_flag(FLAGS_ENABLED_CIRCUIT_BREAKER);
}
std::string& protocol_param() { return _thrift_method_name; }
const std::string& protocol_param() const { return _thrift_method_name; }
void DoPrintLogPrefix(std::ostream& os) const;
private:
// NOTE: align and group fields to make Controller as compact as possible.
Span* _span;
uint32_t _flags; // all boolean fields inside Controller
int32_t _error_code;
std::string _error_text;
butil::EndPoint _remote_side;
butil::EndPoint _local_side;
void* _session_local_data;
const Server* _server;
bthread_id_t _oncancel_id;
const AuthContext* _auth_context; // Authentication result
butil::intrusive_ptr<MongoContext> _mongo_session_data;
SampledRequest* _sampled_request;
ProtocolType _request_protocol;
// Some of them are copied from `Channel' which might be destroyed
// after CallMethod.
int _max_retry;
const RetryPolicy* _retry_policy;
// Synchronization object for one RPC call. It remains unchanged even
// when retry happens. Synchronous RPC will wait on this id.
CallId _correlation_id;
ConnectionType _connection_type;
// Used by ParallelChannel
int _fail_limit;
uint32_t _pipelined_count;
// [Timeout related]
int32_t _timeout_ms;
int32_t _connect_timeout_ms;
int32_t _backup_request_ms;
// If this rpc call has retry/backup request,this var save the real timeout for current call
int64_t _real_timeout_ms;
// Deadline of this RPC (since the Epoch in microseconds).
int64_t _deadline_us;
// Timer registered to trigger RPC timeout event
bthread_timer_t _timeout_id;
// Begin/End time of a single RPC call (since Epoch in microseconds)
int64_t _begin_time_us;
int64_t _end_time_us;
short _tos; // Type of service.
// The index of parse function which `InputMessenger' will use
int _preferred_index;
CompressType _request_compress_type;
CompressType _response_compress_type;
Inheritable _inheritable;
int _pchan_sub_count;
google::protobuf::Message* _response;
google::protobuf::Closure* _done;
RPCSender* _sender;
uint64_t _request_code;
SocketId _single_server_id;
butil::intrusive_ptr<SharedLoadBalancer> _lb;
// for passing parameters to created bthread, don't modify it otherwhere.
CompletionInfo _tmp_completion_info;
Call _current_call;
Call* _unfinished_call;
ExcludedServers* _accessed;
StreamCreator* _stream_creator;
// Fields will be used when making requests
Protocol::PackRequest _pack_request;
const google::protobuf::MethodDescriptor* _method;
const Authenticator* _auth;
butil::IOBuf _request_buf;
IdlNames _idl_names;
int64_t _idl_result;
HttpHeader* _http_request;
HttpHeader* _http_response;
std::unique_ptr<KVMap> _session_kv;
// Fields with large size but low access frequency
butil::IOBuf _request_attachment;
butil::IOBuf _response_attachment;
// Writable progressive attachment
butil::intrusive_ptr<ProgressiveAttachment> _wpa;
// Readable progressive attachment
butil::intrusive_ptr<ReadableProgressiveAttachment> _rpa;
// TODO: Replace following fields with StreamCreator
// Defined at client side
StreamId _request_stream;
// Defined at server side
StreamId _response_stream;
// Defined at both sides
StreamSettings *_remote_stream_settings;
// Thrift method name, only used when thrift protocol enabled
std::string _thrift_method_name;
uint32_t _auth_flags;
};
// Advises the RPC system that the caller desires that the RPC call be
// canceled. If the call is canceled, the "done" callback will still be
// called and the Controller will indicate that the call failed at that
// time.
void StartCancel(CallId id);
// Suspend until the RPC finishes.
void Join(CallId id);
// Get a global closure for doing nothing. Used in semi-synchronous
// RPC calls. Example:
// stub1.method1(&cntl1, &request1, &response1, brpc::DoNothing());
// stub2.method2(&cntl2, &request2, &response2, brpc::DoNothing());
// ...
// brpc::Join(cntl1.call_id());
// brpc::Join(cntl2.call_id());
google::protobuf::Closure* DoNothing();
// Convert non-web symbols to web equivalence.
void WebEscape(const std::string& source, std::string* output);
// True if Ctrl-C is ever pressed.
bool IsAskedToQuit();
// Send Ctrl-C to current process.
void AskToQuit();
std::ostream& operator<<(std::ostream& os, const Controller::LogPrefixDummy& p);
} // namespace brpc
// Print contextual logs prefixed with "@rid=REQUEST_ID" which marks a session
// and eases debugging. The REQUEST_ID is carried in http/rpc request or
// inherited from another controller.
// As a server:
// Call CLOG*(cntl) << ... to log instead of LOG(*) << ..
// As a client:
// Inside a service:
// Use Controller(service_cntl->inheritable()) to create controllers which
// inherit session info from the service's requests
// Standalone brpc client:
// Set cntl->set_request_id(REQUEST_ID);
// Standalone http client:
// Set header 'X-REQUEST-ID'
#define CLOGD(cntl) LOG(DEBUG) << (cntl)->LogPrefix()
#define CLOGI(cntl) LOG(INFO) << (cntl)->LogPrefix()
#define CLOGW(cntl) LOG(WARNING) << (cntl)->LogPrefix()
#define CLOGE(cntl) LOG(ERROR) << (cntl)->LogPrefix()
#define CLOGF(cntl) LOG(FATAL) << (cntl)->LogPrefix()
#define CVLOG(v, cntl) VLOG(v) << (cntl)->LogPrefix()
#endif // BRPC_CONTROLLER_H
+50
View File
@@ -0,0 +1,50 @@
// 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.
#ifndef BRPC_DATA_FACTORY_H
#define BRPC_DATA_FACTORY_H
// To brpc developers: This is a header included by user, don't depend
// on internal structures, use opaque pointers instead.
namespace brpc {
// ---- thread safety ----
// Method implementations of this interface should be thread-safe
class DataFactory {
public:
virtual ~DataFactory() {}
// Implement this method to create a piece of data
// Returns the data, NULL on error.
virtual void* CreateData() const = 0;
// Implement this method to destroy data created by Create().
virtual void DestroyData(void*) const = 0;
// Overwrite this method to reset the data before reuse. Nothing done by default.
// Returns
// true: the data can be kept for future reuse
// false: the data is improper to be reused and should be sent to
// DestoryData() immediately after calling this method
virtual bool ResetData(void*) const { return true; }
};
} // namespace brpc
#endif // BRPC_DATA_FACTORY_H
+114
View File
@@ -0,0 +1,114 @@
// 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.
#ifndef BRPC_DESCRIBABLE_H
#define BRPC_DESCRIBABLE_H
#include <ostream>
#include "butil/macros.h"
#include "butil/class_name.h"
namespace brpc {
struct DescribeOptions {
DescribeOptions()
: verbose(true)
, use_html(false)
{}
bool verbose;
bool use_html;
};
class Describable {
public:
virtual ~Describable() {}
virtual void Describe(std::ostream& os, const DescribeOptions&) const {
os << butil::class_name_str(*this);
}
};
class NonConstDescribable {
public:
virtual ~NonConstDescribable() {}
virtual void Describe(std::ostream& os, const DescribeOptions&) {
os << butil::class_name_str(*this);
}
};
inline std::ostream& operator<<(std::ostream& os, const Describable& obj) {
DescribeOptions options;
options.verbose = false;
obj.Describe(os, options);
return os;
}
inline std::ostream& operator<<(std::ostream& os,
NonConstDescribable& obj) {
DescribeOptions options;
options.verbose = false;
obj.Describe(os, options);
return os;
}
// Append `indent' spaces after each newline.
// Example:
// IndentingOStream os1(std::cout, 2);
// IndentingOStream os2(os1, 2);
// std::cout << "begin1\nhello" << std::endl << "world\nend1" << std::endl;
// os1 << "begin2\nhello" << std::endl << "world\nend2" << std::endl;
// os2 << "begin3\nhello" << std::endl << "world\nend3" << std::endl;
// Output:
// begin1
// hello
// world
// end1
// begin2
// hello
// world
// end2
// begin3
// hello
// world
// end3
class IndentingOStream : virtual private std::streambuf, public std::ostream {
public:
IndentingOStream(std::ostream& dest, int indent)
: std::ostream(this)
, _dest(dest.rdbuf())
, _is_at_start_of_line(false)
, _indent(indent, ' ')
{}
protected:
int overflow(int ch) override {
if (_is_at_start_of_line && ch != '\n' ) {
_dest->sputn(_indent.data(), _indent.size());
}
_is_at_start_of_line = (ch == '\n');
return _dest->sputc(ch);
}
private:
DISALLOW_COPY_AND_ASSIGN(IndentingOStream);
std::streambuf* _dest;
bool _is_at_start_of_line;
std::string _indent;
};
} // namespace brpc
#endif // BRPC_DESCRIBABLE_H
+49
View File
@@ -0,0 +1,49 @@
// 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.
#ifndef BRPC_DESTROYABLE_H
#define BRPC_DESTROYABLE_H
#include "butil/unique_ptr.h" // std::unique_ptr
namespace brpc {
class Destroyable {
public:
virtual ~Destroyable() {}
virtual void Destroy() = 0;
};
namespace detail {
template <typename T> struct Destroyer {
void operator()(T* obj) const { if (obj) { obj->Destroy(); } }
};
}
// A special unique_ptr that calls "obj->Destroy()" instead of "delete obj".
template <typename T>
struct DestroyingPtr : public std::unique_ptr<T, detail::Destroyer<T> > {
DestroyingPtr() {}
DestroyingPtr(T* p) : std::unique_ptr<T, detail::Destroyer<T> >(p) {}
};
} // namespace brpc
#endif // BRPC_DESTROYABLE_H
@@ -0,0 +1,170 @@
// 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.
#ifndef BRPC_CONTROLLER_PRIVATE_ACCESSOR_H
#define BRPC_CONTROLLER_PRIVATE_ACCESSOR_H
// This is an rpc-internal file.
#include "brpc/socket.h"
#include "brpc/controller.h"
#include "brpc/stream.h"
namespace google {
namespace protobuf {
class Message;
}
}
namespace brpc {
class AuthContext;
// A wrapper to access some private methods/fields of `Controller'
// This is supposed to be used by internal RPC protocols ONLY
class ControllerPrivateAccessor {
public:
explicit ControllerPrivateAccessor(Controller* cntl) {
_cntl = cntl;
}
void OnResponse(CallId id, int saved_error) {
const Controller::CompletionInfo info = { id, true };
_cntl->OnVersionedRPCReturned(info, false, saved_error);
}
ControllerPrivateAccessor &set_peer_id(SocketId peer_id) {
_cntl->_current_call.peer_id = peer_id;
return *this;
}
Socket* get_sending_socket() {
return _cntl->_current_call.sending_sock.get();
}
int64_t real_timeout_ms() {
return _cntl->_real_timeout_ms;
}
void move_in_server_receiving_sock(SocketUniquePtr& ptr) {
CHECK(_cntl->_current_call.sending_sock == NULL);
_cntl->_current_call.sending_sock.reset(ptr.release());
}
StreamUserData* get_stream_user_data() {
return _cntl->_current_call.stream_user_data;
}
ControllerPrivateAccessor &set_security_mode(bool security_mode) {
_cntl->set_flag(Controller::FLAGS_SECURITY_MODE, security_mode);
return *this;
}
ControllerPrivateAccessor &set_remote_side(const butil::EndPoint& pt) {
_cntl->_remote_side = pt;
return *this;
}
ControllerPrivateAccessor &set_local_side(const butil::EndPoint& pt) {
_cntl->_local_side = pt;
return *this;
}
ControllerPrivateAccessor &set_auth_context(const AuthContext* ctx) {
_cntl->set_auth_context(ctx);
return *this;
}
ControllerPrivateAccessor &set_span(Span* span) {
_cntl->_span = span;
return *this;
}
ControllerPrivateAccessor &set_request_protocol(ProtocolType protocol) {
_cntl->_request_protocol = protocol;
return *this;
}
Span* span() const { return _cntl->_span; }
uint32_t pipelined_count() const { return _cntl->_pipelined_count; }
void set_pipelined_count(uint32_t count) { _cntl->_pipelined_count = count; }
ControllerPrivateAccessor& set_server(const Server* server) {
_cntl->_server = server;
return *this;
}
// Pass the owership of |settings| to _cntl, while is going to be
// destroyed in Controller::Reset()
void set_remote_stream_settings(StreamSettings *settings) {
_cntl->_remote_stream_settings = settings;
}
StreamSettings* remote_stream_settings() {
return _cntl->_remote_stream_settings;
}
StreamId request_stream() { return _cntl->_request_stream; }
StreamId response_stream() { return _cntl->_response_stream; }
void set_method(const google::protobuf::MethodDescriptor* method)
{ _cntl->_method = method; }
void set_readable_progressive_attachment(ReadableProgressiveAttachment* s)
{ _cntl->_rpa.reset(s); }
void set_auth_flags(uint32_t auth_flags) {
_cntl->_auth_flags = auth_flags;
}
void clear_auth_flags() { _cntl->_auth_flags = 0; }
std::string& protocol_param() { return _cntl->protocol_param(); }
const std::string& protocol_param() const { return _cntl->protocol_param(); }
// Note: This function can only be called in server side. The deadline of client
// side is properly set in the RPC sending path.
void set_deadline_us(int64_t deadline_us) { _cntl->_deadline_us = deadline_us; }
ControllerPrivateAccessor& set_begin_time_us(int64_t begin_time_us) {
_cntl->_begin_time_us = begin_time_us;
_cntl->_end_time_us = UNSET_MAGIC_NUM;
return *this;
}
ControllerPrivateAccessor& set_health_check_call() {
_cntl->add_flag(Controller::FLAGS_HEALTH_CHECK_CALL);
return *this;
}
private:
Controller* _cntl;
};
// Inherit this class to intercept Controller::IssueRPC. This is an internal
// utility only useable by brpc developers.
class RPCSender {
public:
virtual ~RPCSender() {}
virtual int IssueRPC(int64_t start_realtime_us) = 0;
};
} // namespace brpc
#endif // BRPC_CONTROLLER_PRIVATE_ACCESSOR_H
+34
View File
@@ -0,0 +1,34 @@
// 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.
#ifndef BRPC_HAS_EPOLLRDHUP_H
#define BRPC_HAS_EPOLLRDHUP_H
namespace brpc {
// Check if the kernel supports EPOLLRDHUP which is added in Linux 2.6.17
// This flag is useful in Edge Triggered mode. Without the flag user has
// to call an additional read() even if return value(positive) is less
// than given `count', otherwise return value=0(indicating EOF) may be lost.
extern const unsigned int has_epollrdhup;
} // namespace brpc
#endif // BRPC_HAS_EPOLLRDHUP_H
+36
View File
@@ -0,0 +1,36 @@
// 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.
#ifndef _HEALTH_CHECK_H
#define _HEALTH_CHECK_H
#include "brpc/socket_id.h"
#include "brpc/periodic_task.h"
#include "bvar/bvar.h"
#include "brpc/socket.h"
namespace brpc {
// Start health check for socket id after delay_ms.
// If delay_ms <= 0, HealthCheck would be started
// immediately.
void StartHealthCheck(SocketId id, int64_t delay_ms);
} // namespace brpc
#endif
+366
View File
@@ -0,0 +1,366 @@
// 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.
// Intentionally no header guard
namespace brpc {
struct HeaderCstr {
const char* name;
const char* value;
};
static const HeaderCstr s_static_headers[] = {
{":authority", ""},
{":method", "GET"},
{":method", "POST"},
{":path", "/"},
{":path", "/index.html"},
{":scheme", "http"},
{":scheme", "https"},
{":status", "200"},
{":status", "204"},
{":status", "206"},
{":status", "304"},
{":status", "400"},
{":status", "404"},
{":status", "500"},
{"accept-charset", ""},
{"accept-encoding", "gzip, deflate"},
{"accept-language", ""},
{"accept-ranges", ""},
{"accept", ""},
{"access-control-allow-origin", ""},
{"age", ""},
{"allow", ""},
{"authorization", ""},
{"cache-control", ""},
{"content-disposition", ""},
{"content-encoding", ""},
{"content-language", ""},
{"content-length", ""},
{"content-location", ""},
{"content-range", ""},
{"content-type", ""},
{"cookie", ""},
{"date", ""},
{"etag", ""},
{"expect", ""},
{"expires", ""},
{"from", ""},
{"host", ""},
{"if-match", ""},
{"if-modified-since", ""},
{"if-none-match", ""},
{"if-range", ""},
{"if-unmodified-since", ""},
{"last-modified", ""},
{"link", ""},
{"location", ""},
{"max-forwards", ""},
{"proxy-authenticate", ""},
{"proxy-authorization", ""},
{"range", ""},
{"referer", ""},
{"refresh", ""},
{"retry-after", ""},
{"server", ""},
{"set-cookie", ""},
{"strict-transport-security", ""},
{"transfer-encoding", ""},
{"user-agent", ""},
{"vary", ""},
{"via", ""},
{"www-authenticate", ""}
};
BAIDU_CASSERT(ARRAY_SIZE(s_static_headers) == 61u,
number_of_entries_in_static_table_must_be_61);
struct HuffmanCode {
uint32_t code;
uint32_t bit_len;
};
static const HuffmanCode s_huffman_table[] = {
{0x1ff8, 13},
{0x7fffd8, 23},
{0xfffffe2, 28},
{0xfffffe3, 28},
{0xfffffe4, 28},
{0xfffffe5, 28},
{0xfffffe6, 28},
{0xfffffe7, 28},
{0xfffffe8, 28},
{0xffffea, 24},
{0x3ffffffc, 30},
{0xfffffe9, 28},
{0xfffffea, 28},
{0x3ffffffd, 30},
{0xfffffeb, 28},
{0xfffffec, 28},
{0xfffffed, 28},
{0xfffffee, 28},
{0xfffffef, 28},
{0xffffff0, 28},
{0xffffff1, 28},
{0xffffff2, 28},
{0x3ffffffe, 30},
{0xffffff3, 28},
{0xffffff4, 28},
{0xffffff5, 28},
{0xffffff6, 28},
{0xffffff7, 28},
{0xffffff8, 28},
{0xffffff9, 28},
{0xffffffa, 28},
{0xffffffb, 28},
{0x14, 6},
{0x3f8, 10},
{0x3f9, 10},
{0xffa, 12},
{0x1ff9, 13},
{0x15, 6},
{0xf8, 8},
{0x7fa, 11},
{0x3fa, 10},
{0x3fb, 10},
{0xf9, 8},
{0x7fb, 11},
{0xfa, 8},
{0x16, 6},
{0x17, 6},
{0x18, 6},
{0x0, 5},
{0x1, 5},
{0x2, 5},
{0x19, 6},
{0x1a, 6},
{0x1b, 6},
{0x1c, 6},
{0x1d, 6},
{0x1e, 6},
{0x1f, 6},
{0x5c, 7},
{0xfb, 8},
{0x7ffc, 15},
{0x20, 6},
{0xffb, 12},
{0x3fc, 10},
{0x1ffa, 13},
{0x21, 6},
{0x5d, 7},
{0x5e, 7},
{0x5f, 7},
{0x60, 7},
{0x61, 7},
{0x62, 7},
{0x63, 7},
{0x64, 7},
{0x65, 7},
{0x66, 7},
{0x67, 7},
{0x68, 7},
{0x69, 7},
{0x6a, 7},
{0x6b, 7},
{0x6c, 7},
{0x6d, 7},
{0x6e, 7},
{0x6f, 7},
{0x70, 7},
{0x71, 7},
{0x72, 7},
{0xfc, 8},
{0x73, 7},
{0xfd, 8},
{0x1ffb, 13},
{0x7fff0, 19},
{0x1ffc, 13},
{0x3ffc, 14},
{0x22, 6},
{0x7ffd, 15},
{0x3, 5},
{0x23, 6},
{0x4, 5},
{0x24, 6},
{0x5, 5},
{0x25, 6},
{0x26, 6},
{0x27, 6},
{0x6, 5},
{0x74, 7},
{0x75, 7},
{0x28, 6},
{0x29, 6},
{0x2a, 6},
{0x7, 5},
{0x2b, 6},
{0x76, 7},
{0x2c, 6},
{0x8, 5},
{0x9, 5},
{0x2d, 6},
{0x77, 7},
{0x78, 7},
{0x79, 7},
{0x7a, 7},
{0x7b, 7},
{0x7ffe, 15},
{0x7fc, 11},
{0x3ffd, 14},
{0x1ffd, 13},
{0xffffffc, 28},
{0xfffe6, 20},
{0x3fffd2, 22},
{0xfffe7, 20},
{0xfffe8, 20},
{0x3fffd3, 22},
{0x3fffd4, 22},
{0x3fffd5, 22},
{0x7fffd9, 23},
{0x3fffd6, 22},
{0x7fffda, 23},
{0x7fffdb, 23},
{0x7fffdc, 23},
{0x7fffdd, 23},
{0x7fffde, 23},
{0xffffeb, 24},
{0x7fffdf, 23},
{0xffffec, 24},
{0xffffed, 24},
{0x3fffd7, 22},
{0x7fffe0, 23},
{0xffffee, 24},
{0x7fffe1, 23},
{0x7fffe2, 23},
{0x7fffe3, 23},
{0x7fffe4, 23},
{0x1fffdc, 21},
{0x3fffd8, 22},
{0x7fffe5, 23},
{0x3fffd9, 22},
{0x7fffe6, 23},
{0x7fffe7, 23},
{0xffffef, 24},
{0x3fffda, 22},
{0x1fffdd, 21},
{0xfffe9, 20},
{0x3fffdb, 22},
{0x3fffdc, 22},
{0x7fffe8, 23},
{0x7fffe9, 23},
{0x1fffde, 21},
{0x7fffea, 23},
{0x3fffdd, 22},
{0x3fffde, 22},
{0xfffff0, 24},
{0x1fffdf, 21},
{0x3fffdf, 22},
{0x7fffeb, 23},
{0x7fffec, 23},
{0x1fffe0, 21},
{0x1fffe1, 21},
{0x3fffe0, 22},
{0x1fffe2, 21},
{0x7fffed, 23},
{0x3fffe1, 22},
{0x7fffee, 23},
{0x7fffef, 23},
{0xfffea, 20},
{0x3fffe2, 22},
{0x3fffe3, 22},
{0x3fffe4, 22},
{0x7ffff0, 23},
{0x3fffe5, 22},
{0x3fffe6, 22},
{0x7ffff1, 23},
{0x3ffffe0, 26},
{0x3ffffe1, 26},
{0xfffeb, 20},
{0x7fff1, 19},
{0x3fffe7, 22},
{0x7ffff2, 23},
{0x3fffe8, 22},
{0x1ffffec, 25},
{0x3ffffe2, 26},
{0x3ffffe3, 26},
{0x3ffffe4, 26},
{0x7ffffde, 27},
{0x7ffffdf, 27},
{0x3ffffe5, 26},
{0xfffff1, 24},
{0x1ffffed, 25},
{0x7fff2, 19},
{0x1fffe3, 21},
{0x3ffffe6, 26},
{0x7ffffe0, 27},
{0x7ffffe1, 27},
{0x3ffffe7, 26},
{0x7ffffe2, 27},
{0xfffff2, 24},
{0x1fffe4, 21},
{0x1fffe5, 21},
{0x3ffffe8, 26},
{0x3ffffe9, 26},
{0xffffffd, 28},
{0x7ffffe3, 27},
{0x7ffffe4, 27},
{0x7ffffe5, 27},
{0xfffec, 20},
{0xfffff3, 24},
{0xfffed, 20},
{0x1fffe6, 21},
{0x3fffe9, 22},
{0x1fffe7, 21},
{0x1fffe8, 21},
{0x7ffff3, 23},
{0x3fffea, 22},
{0x3fffeb, 22},
{0x1ffffee, 25},
{0x1ffffef, 25},
{0xfffff4, 24},
{0xfffff5, 24},
{0x3ffffea, 26},
{0x7ffff4, 23},
{0x3ffffeb, 26},
{0x7ffffe6, 27},
{0x3ffffec, 26},
{0x3ffffed, 26},
{0x7ffffe7, 27},
{0x7ffffe8, 27},
{0x7ffffe9, 27},
{0x7ffffea, 27},
{0x7ffffeb, 27},
{0xffffffe, 28},
{0x7ffffec, 27},
{0x7ffffed, 27},
{0x7ffffee, 27},
{0x7ffffef, 27},
{0x7fffff0, 27},
{0x3ffffee, 26},
{0x3fffffff, 30},
};
BAIDU_CASSERT(ARRAY_SIZE(s_huffman_table) == 257u,
sizeof_s_huffman_table_must_be_257);
const static int32_t HPACK_HUFFMAN_EOS = 256;
} // namespace brpc
+152
View File
@@ -0,0 +1,152 @@
// 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.
#ifndef BRPC_HPACK_H
#define BRPC_HPACK_H
#include "butil/iobuf.h" // butil::IOBuf
#include "butil/strings/string_piece.h" // butil::StringPiece
#include "brpc/http2.h"
#include "brpc/describable.h"
namespace brpc {
enum HeaderIndexPolicy {
// Append this header, alerting the decoder dynamic table
// - If the given header matches one of the indexed header, this header
// is replaced by the index.
// - If not, append this header into the decoder dynamic table
HPACK_INDEX_HEADER = 0,
// Append this header, without alerting the decoder dynamic table
// - If the given header matches one of the indexed header, this header
// is replaced by the index.
// - If not, append this header directly *WITHOUT* any modification on the
// decoder dynamic table
HPACK_NOT_INDEX_HEADER = 1,
// Append this header which will never replaced by a index
HPACK_NEVER_INDEX_HEADER = 2,
};
// Options to encode a header
struct HPackOptions {
// How to index this header field.
// Default: HPACK_INDEX_HEADER
HeaderIndexPolicy index_policy;
// If true, the name string would be encoded with huffman encoding
// Default: false
bool encode_name;
// If true, the value string would be encoded with huffman encoding
// Default: false
bool encode_value;
// Construct default options
HPackOptions();
};
inline HPackOptions::HPackOptions()
: index_policy(HPACK_INDEX_HEADER)
, encode_name(false)
, encode_value(false)
{}
class IndexTable;
// HPACK - Header compression algorithm for http2 (rfc7541)
// http://httpwg.org/specs/rfc7541.html
// Note: Name of header is assumed to be in *lowercase* acoording to
// https://tools.ietf.org/html/rfc7540#section-8.1.2
// Just as in HTTP/1.x, header field names are strings of ASCII
// characters that are compared in a case-insensitive fashion. However,
// header field names *MUST* be converted to lowercase prior to their
// encoding in HTTP/2. A request or response containing uppercase
// header field names MUST be treated as malformed
// Not supported methods:
// - Resize dynamic table.
class HPacker : public Describable {
public:
struct Header {
std::string name;
std::string value;
Header() {}
explicit Header(const std::string& name2) : name(name2) {}
Header(const std::string& name2, const std::string& value2)
: name(name2), value(value2) {}
};
HPacker();
~HPacker();
// Initialize the instance.
// Returns 0 on success, -1 otherwise.
int Init(size_t max_table_size = H2Settings::DEFAULT_HEADER_TABLE_SIZE);
// Encode header and append the encoded buffer to |out|
// Returns true on success.
void Encode(butil::IOBufAppender* out, const Header& header,
const HPackOptions& options);
void Encode(butil::IOBufAppender* out, const Header& header)
{ return Encode(out, header, HPackOptions()); }
// Try to decode at most one Header from source and erase corresponding
// buffer.
// Returns:
// * $size of decoded buffer when a header is succesfully decoded
// * 0 when the source is incompleted
// * -1 when the source is malformed
ssize_t Decode(butil::IOBuf* source, Header* h);
// Like the previous function, except that the source is from
// IOBufBytesIterator.
ssize_t Decode(butil::IOBufBytesIterator& source, Header* h);
void Describe(std::ostream& os, const DescribeOptions&) const;
private:
DISALLOW_COPY_AND_ASSIGN(HPacker);
int FindHeaderFromIndexTable(const Header& h) const;
int FindNameFromIndexTable(const std::string& name) const;
const Header* HeaderAt(int index) const;
ssize_t DecodeWithKnownPrefix(
butil::IOBufBytesIterator& iter, Header* h, uint8_t prefix_size) const;
IndexTable* _encode_table;
IndexTable* _decode_table;
};
// Lowercase the input string, a fast implementation.
void tolower(std::string* s);
inline ssize_t HPacker::Decode(butil::IOBuf* source, Header* h) {
butil::IOBufBytesIterator iter(*source);
const ssize_t nc = Decode(iter, h);
if (nc > 0) {
source->pop_front(nc);
}
return nc;
}
} // namespace brpc
#endif //BRPC_HPACK_H
+140
View File
@@ -0,0 +1,140 @@
// 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.
#ifndef BRPC_HTTP_MESSAGE_H
#define BRPC_HTTP_MESSAGE_H
#include <string> // std::string
#include "butil/macros.h"
#include "butil/iobuf.h" // butil::IOBuf
#include "butil/scoped_lock.h" // butil::unique_lock
#include "butil/endpoint.h"
#include "brpc/details/http_parser.h" // http_parser
#include "brpc/http_header.h" // HttpHeader
#include "brpc/progressive_reader.h" // ProgressiveReader
namespace brpc {
enum HttpParserStage {
HTTP_ON_MESSAGE_BEGIN,
HTTP_ON_URL,
HTTP_ON_STATUS,
HTTP_ON_HEADER_FIELD,
HTTP_ON_HEADER_VALUE,
HTTP_ON_HEADERS_COMPLETE,
HTTP_ON_BODY,
HTTP_ON_MESSAGE_COMPLETE
};
class HttpMessage {
public:
// If read_body_progressively is true, the body will be read progressively
// by using SetBodyReader().
HttpMessage(bool read_body_progressively = false);
~HttpMessage();
const butil::IOBuf &body() const { return _body; }
butil::IOBuf &body() { return _body; }
// Parse from array, length=0 is treated as EOF.
// Returns bytes parsed, -1 on failure.
ssize_t ParseFromArray(const char *data, const size_t length);
// Parse from butil::IOBuf.
// Emtpy `buf' is sliently ignored, which is different from ParseFromArray.
// Returns bytes parsed, -1 on failure.
ssize_t ParseFromIOBuf(const butil::IOBuf &buf);
bool Completed() const { return _stage == HTTP_ON_MESSAGE_COMPLETE; }
HttpParserStage stage() const { return _stage; }
HttpHeader &header() { return _header; }
const HttpHeader &header() const { return _header; }
size_t parsed_length() const { return _parsed_length; }
// Http parser callback functions
static int on_message_begin(http_parser *);
static int on_url(http_parser *, const char *, const size_t);
static int on_status(http_parser*, const char *, const size_t);
static int on_header_field(http_parser *, const char *, const size_t);
static int on_header_value(http_parser *, const char *, const size_t);
static int on_headers_complete(http_parser *);
static int on_body_cb(http_parser*, const char *, const size_t);
static int on_message_complete_cb(http_parser *);
const http_parser& parser() const { return _parser; }
bool read_body_progressively() const { return _read_body_progressively; }
// Send new parts of the body to the reader. If the body already has some
// data, feed them to the reader immediately.
// Any error during the setting will destroy the reader.
void SetBodyReader(ProgressiveReader* r);
protected:
int OnBody(const char* data, size_t size);
int OnMessageComplete();
size_t _parsed_length;
private:
DISALLOW_COPY_AND_ASSIGN(HttpMessage);
int UnlockAndFlushToBodyReader(std::unique_lock<butil::Mutex>& locked);
HttpParserStage _stage;
std::string _url;
HttpHeader _header;
bool _read_body_progressively;
// For mutual exclusion between on_body and SetBodyReader.
butil::Mutex _body_mutex;
// Read body progressively
ProgressiveReader* _body_reader;
butil::IOBuf _body;
// Parser related members
struct http_parser _parser;
std::string _cur_header;
std::string *_cur_value;
protected:
// Only valid when -http_verbose is on
butil::IOBufBuilder* _vmsgbuilder;
size_t _vbodylen;
};
std::ostream& operator<<(std::ostream& os, const http_parser& parser);
// Serialize a http request.
// header: may be modified in some cases
// remote_side: used when "Host" is absent
// content: could be NULL.
void MakeRawHttpRequest(butil::IOBuf* request,
HttpHeader* header,
const butil::EndPoint& remote_side,
const butil::IOBuf* content);
// Serialize a http response.
// header: may be modified in some cases
// content: cleared after usage. could be NULL.
void MakeRawHttpResponse(butil::IOBuf* response,
HttpHeader* header,
butil::IOBuf* content);
} // namespace brpc
#endif // BRPC_HTTP_MESSAGE_H
+329
View File
@@ -0,0 +1,329 @@
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef BRPC_HTTP_PARSER_H
#define BRPC_HTTP_PARSER_H
/* Also update SONAME in the Makefile whenever you change these. */
#define HTTP_PARSER_VERSION_MAJOR 2
#define HTTP_PARSER_VERSION_MINOR 3
#define HTTP_PARSER_VERSION_PATCH 0
#include <sys/types.h>
#if defined(_WIN32) && !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER<1600)
#include <BaseTsd.h>
#include <stddef.h>
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
/* Compile with -DBRPC_HTTP_PARSER_STRICT=0 to make less checks, but run
* faster
*/
#ifndef BRPC_HTTP_PARSER_STRICT
# define BRPC_HTTP_PARSER_STRICT 1
#endif
/* Maximium header size allowed. If the macro is not defined
* before including this header then the default is used. To
* change the maximum header size, define the macro in the build
* environment (e.g. -DBRPC_HTTP_MAX_HEADER_SIZE=<value>). To remove
* the effective limit on the size of the header, define the macro
* to a very large number (e.g. -DBRPC_HTTP_MAX_HEADER_SIZE=0x7fffffff)
*/
#ifndef BRPC_HTTP_MAX_HEADER_SIZE
# define BRPC_HTTP_MAX_HEADER_SIZE (80*1024)
#endif
namespace brpc {
struct http_parser;
/* Callbacks should return non-zero to indicate an error. The parser will
* then halt execution.
*
* The one exception is on_headers_complete. In a HTTP_RESPONSE parser
* returning '1' from on_headers_complete will tell the parser that it
* should not expect a body. This is used when receiving a response to a
* HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
* chunked' headers that indicate the presence of a body.
*
* http_data_cb does not return data chunks. It will be called arbitrarily
* many times for each string. E.G. you might get 10 callbacks for "on_url"
* each providing just a few characters more data.
*/
typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
typedef int (*http_cb) (http_parser*);
/* Request Methods */
#define HTTP_METHOD_MAP(XX) \
XX(0, DELETE, DELETE) \
XX(1, GET, GET) \
XX(2, HEAD, HEAD) \
XX(3, POST, POST) \
XX(4, PUT, PUT) \
/* pathological */ \
XX(5, CONNECT, CONNECT) \
XX(6, OPTIONS, OPTIONS) \
XX(7, TRACE, TRACE) \
/* webdav */ \
XX(8, COPY, COPY) \
XX(9, LOCK, LOCK) \
XX(10, MKCOL, MKCOL) \
XX(11, MOVE, MOVE) \
XX(12, PROPFIND, PROPFIND) \
XX(13, PROPPATCH, PROPPATCH) \
XX(14, SEARCH, SEARCH) \
XX(15, UNLOCK, UNLOCK) \
/* subversion */ \
XX(16, REPORT, REPORT) \
XX(17, MKACTIVITY, MKACTIVITY) \
XX(18, CHECKOUT, CHECKOUT) \
XX(19, MERGE, MERGE) \
/* upnp */ \
XX(20, MSEARCH, M-SEARCH) \
XX(21, NOTIFY, NOTIFY) \
XX(22, SUBSCRIBE, SUBSCRIBE) \
XX(23, UNSUBSCRIBE, UNSUBSCRIBE) \
/* RFC-5789 */ \
XX(24, PATCH, PATCH) \
XX(25, PURGE, PURGE) \
/* CalDAV */ \
XX(26, MKCALENDAR, MKCALENDAR) \
enum http_method
{
#define XX(num, name, string) HTTP_##name = num,
HTTP_METHOD_MAP(XX)
#undef XX
};
enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
/* Flag values for http_parser.flags field */
enum http_parser_flags
{ F_CHUNKED = 1 << 0
, F_CONNECTION_KEEP_ALIVE = 1 << 1
, F_CONNECTION_CLOSE = 1 << 2
, F_TRAILING = 1 << 3
, F_UPGRADE = 1 << 4
, F_SKIPBODY = 1 << 5
};
/* Map for errno-related constants
*
* The provided argument should be a macro that takes 2 arguments.
*/
#define HTTP_ERRNO_MAP(XX) \
/* No error */ \
XX(OK, "success") \
\
/* Callback-related errors */ \
XX(CB_message_begin, "the on_message_begin callback failed") \
XX(CB_url, "the on_url callback failed") \
XX(CB_header_field, "the on_header_field callback failed") \
XX(CB_header_value, "the on_header_value callback failed") \
XX(CB_headers_complete, "the on_headers_complete callback failed") \
XX(CB_body, "the on_body callback failed") \
XX(CB_message_complete, "the on_message_complete callback failed") \
XX(CB_status, "the on_status callback failed") \
\
/* Parsing-related errors */ \
XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \
XX(HEADER_OVERFLOW, \
"too many header bytes seen; overflow detected") \
XX(CLOSED_CONNECTION, \
"data received after completed connection: close message") \
XX(INVALID_VERSION, "invalid HTTP version") \
XX(INVALID_STATUS, "invalid HTTP status code") \
XX(INVALID_METHOD, "invalid HTTP method") \
XX(INVALID_URL, "invalid URL") \
XX(INVALID_HOST, "invalid host") \
XX(INVALID_PORT, "invalid port") \
XX(INVALID_PATH, "invalid path") \
XX(INVALID_QUERY_STRING, "invalid query string") \
XX(INVALID_FRAGMENT, "invalid fragment") \
XX(LF_EXPECTED, "LF character expected") \
XX(INVALID_HEADER_TOKEN, "invalid character in header") \
XX(INVALID_CONTENT_LENGTH, \
"invalid character in content-length header") \
XX(INVALID_CHUNK_SIZE, \
"invalid character in chunk size header") \
XX(INVALID_CONSTANT, "invalid constant string") \
XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
XX(STRICT, "strict mode assertion failed") \
XX(PAUSED, "parser is paused") \
XX(UNKNOWN, "an unknown error occurred")
/* Define HPE_* values for each errno value above */
#define HTTP_ERRNO_GEN(n, s) HPE_##n,
enum http_errno {
HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
};
#undef HTTP_ERRNO_GEN
/* Get an http_errno value from an http_parser */
#define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno)
struct http_parser {
/** PRIVATE **/
unsigned int type : 2; /* enum http_parser_type */
unsigned int flags : 6; /* F_* values from 'flags' enum; semi-public */
unsigned int state : 8; /* enum state from http_parser.c */
unsigned int header_state : 8; /* enum header_state from http_parser.c */
unsigned int index : 8; /* index into current matcher */
uint32_t nread; /* # bytes read in various scenarios */
uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
/** READ-ONLY **/
unsigned short http_major;
unsigned short http_minor;
unsigned int status_code : 16; /* responses only */
unsigned int method : 8; /* requests only */
unsigned int http_errno : 7;
unsigned int dummy : 1;
/** PUBLIC **/
void *data; /* A pointer to get hook to the "connection" or "socket" object */
};
struct http_parser_settings {
http_cb on_message_begin;
http_data_cb on_url;
http_data_cb on_status;
http_data_cb on_header_field;
http_data_cb on_header_value;
http_cb on_headers_complete;
http_data_cb on_body;
http_cb on_message_complete;
};
enum http_parser_url_fields
{ UF_SCHEME = 0
, UF_HOST = 1
, UF_PORT = 2
, UF_PATH = 3
, UF_QUERY = 4
, UF_FRAGMENT = 5
, UF_USERINFO = 6
, UF_MAX = 7
};
/* Result structure for http_parser_parse_url().
*
* Callers should index into field_data[] with UF_* values iff field_set
* has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
* because we probably have padding left over), we convert any port to
* a uint16_t.
*/
struct http_parser_url {
uint16_t field_set; /* Bitmask of (1 << UF_*) values */
uint16_t port; /* Converted UF_PORT string */
struct {
uint16_t off; /* Offset into buffer in which field starts */
uint16_t len; /* Length of run in buffer */
} field_data[UF_MAX];
};
/* Returns the library version. Bits 16-23 contain the major version number,
* bits 8-15 the minor version number and bits 0-7 the patch level.
* Usage example:
*
* unsigned long version = http_parser_version();
* unsigned major = (version >> 16) & 255;
* unsigned minor = (version >> 8) & 255;
* unsigned patch = version & 255;
* printf("http_parser v%u.%u.%u\n", major, minor, patch);
*/
unsigned long http_parser_version(void);
void http_parser_init(http_parser *parser, enum http_parser_type type);
/* Executes the parser. Returns number of parsed bytes. Sets
* `parser->http_errno` on error. */
size_t http_parser_execute(http_parser *parser,
const http_parser_settings *settings,
const char *data,
size_t len);
/* If http_should_keep_alive() in the on_headers_complete or
* on_message_complete callback returns 0, then this should be
* the last message on the connection.
* If you are the server, respond with the "Connection: close" header.
* If you are the client, close the connection.
*/
int http_should_keep_alive(const http_parser *parser);
/* Returns a string version of the HTTP method. */
const char *http_method_str(enum http_method m);
/* Return a string name of the given error */
const char *http_errno_name(enum http_errno err);
/* Return a string description of the given error */
const char *http_errno_description(enum http_errno err);
/* Parse a URL; return nonzero on failure */
int http_parser_parse_url(const char *buf, size_t buflen,
int is_connect,
struct http_parser_url *u);
/* Pause or un-pause the parser; a nonzero value pauses */
void http_parser_pause(http_parser *parser, int paused);
/* Checks if this is the final chunk of the body. */
int http_body_is_final(const http_parser *parser);
/* Return a string name of the given type */
const char* http_parser_type_name(enum http_parser_type type);
/* Return a string name of the given state */
const char* http_parser_state_name(unsigned int state);
const char* http_parser_header_state_name(unsigned int header_state);
} // namespace brpc
#endif // BRPC_HTTP_PARSER_H
@@ -0,0 +1,51 @@
// 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.
#ifndef BRPC_LOAD_BALANCER_WITH_NAMING_H
#define BRPC_LOAD_BALANCER_WITH_NAMING_H
#include "butil/intrusive_ptr.hpp"
#include "brpc/load_balancer.h"
#include "brpc/details/naming_service_thread.h" // NamingServiceWatcher
namespace brpc {
class LoadBalancerWithNaming : public SharedLoadBalancer,
public NamingServiceWatcher {
public:
LoadBalancerWithNaming() {}
~LoadBalancerWithNaming();
int Init(const char* ns_url, const char* lb_name,
const NamingServiceFilter* filter,
const GetNamingServiceThreadOptions* options);
void OnAddedServers(const std::vector<ServerId>& servers);
void OnRemovedServers(const std::vector<ServerId>& servers);
void Describe(std::ostream& os, const DescribeOptions& options);
private:
butil::intrusive_ptr<NamingServiceThread> _nsthread_ptr;
};
} // namespace brpc
#endif // BRPC_LOAD_BALANCER_WITH_NAMING_H
+117
View File
@@ -0,0 +1,117 @@
// 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.
#ifndef BRPC_METHOD_STATUS_H
#define BRPC_METHOD_STATUS_H
#include "butil/macros.h" // DISALLOW_COPY_AND_ASSIGN
#include "bvar/bvar.h" // vars
#include "brpc/describable.h"
#include "brpc/concurrency_limiter.h"
namespace brpc {
class Controller;
class Server;
// Record accessing stats of a method.
class MethodStatus : public Describable {
public:
MethodStatus();
~MethodStatus();
// Call this function when the method is about to be called.
// Returns false when the method is overloaded. If rejected_cc is not
// NULL, it's set with the rejected concurrency.
bool OnRequested(int* rejected_cc = NULL);
// Call this when the method just finished.
// `error_code' : The error code obtained from the controller. Equal to
// 0 when the call is successful.
// `latency_us' : microseconds taken by a successful call. Latency can
// be measured in this utility class as well, but the callsite often
// did the time keeping and the cost is better saved.
void OnResponded(int error_code, int64_t latency_us);
// Expose internal vars.
// Return 0 on success, -1 otherwise.
int Expose(const butil::StringPiece& prefix);
// Describe internal vars, used by /status
void Describe(std::ostream &os, const DescribeOptions&) const override;
// Current max_concurrency of the method.
int MaxConcurrency() const { return _cl ? _cl->MaxConcurrency() : 0; }
private:
friend class Server;
DISALLOW_COPY_AND_ASSIGN(MethodStatus);
// Note: SetConcurrencyLimiter() is not thread safe and can only be called
// before the server is started.
void SetConcurrencyLimiter(ConcurrencyLimiter* cl);
std::unique_ptr<ConcurrencyLimiter> _cl;
butil::atomic<int> _nconcurrency;
bvar::Adder<int64_t> _nerror_bvar;
bvar::LatencyRecorder _latency_rec;
bvar::PassiveStatus<int> _nconcurrency_bvar;
bvar::PerSecond<bvar::Adder<int64_t>> _eps_bvar;
bvar::PassiveStatus<int32_t> _max_concurrency_bvar;
};
class ConcurrencyRemover {
public:
ConcurrencyRemover(MethodStatus* status, Controller* c, int64_t received_us)
: _status(status)
, _c(c)
, _received_us(received_us) {}
~ConcurrencyRemover();
private:
DISALLOW_COPY_AND_ASSIGN(ConcurrencyRemover);
MethodStatus* _status;
Controller* _c;
uint64_t _received_us;
};
inline bool MethodStatus::OnRequested(int* rejected_cc) {
const int cc = _nconcurrency.fetch_add(1, butil::memory_order_relaxed) + 1;
if (NULL == _cl || _cl->OnRequested(cc)) {
return true;
}
if (rejected_cc) {
*rejected_cc = cc;
}
return false;
}
inline void MethodStatus::OnResponded(int error_code, int64_t latency) {
_nconcurrency.fetch_sub(1, butil::memory_order_relaxed);
if (0 == error_code) {
_latency_rec << latency;
} else {
_nerror_bvar << 1;
}
if (NULL != _cl) {
_cl->OnResponded(error_code, latency);
}
}
} // namespace brpc
#endif //BRPC_METHOD_STATUS_H
@@ -0,0 +1,142 @@
// 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.
#ifndef BRPC_NAMING_SERVICE_THREAD_H
#define BRPC_NAMING_SERVICE_THREAD_H
#include <string>
#include "butil/intrusive_ptr.hpp" // butil::intrusive_ptr
#include "bthread/bthread.h" // bthread_t
#include "brpc/server_id.h" // ServerId
#include "brpc/shared_object.h" // SharedObject
#include "brpc/naming_service.h" // NamingService
#include "brpc/naming_service_filter.h" // NamingServiceFilter
#include "brpc/socket_map.h"
namespace brpc {
// Inherit this class to observer NamingService changes.
// NOTE: Same SocketId with different tags are treated as different entries.
// When you change tag of a server, the server with the old tag will appear
// in OnRemovedServers first, then in OnAddedServers with the new tag.
class NamingServiceWatcher {
public:
virtual ~NamingServiceWatcher() {}
virtual void OnAddedServers(const std::vector<ServerId>& servers) = 0;
virtual void OnRemovedServers(const std::vector<ServerId>& servers) = 0;
};
struct GetNamingServiceThreadOptions {
GetNamingServiceThreadOptions()
: succeed_without_server(false)
, log_succeed_without_server(true)
, use_rdma(false) {}
bool succeed_without_server;
bool log_succeed_without_server;
bool use_rdma;
ChannelSignature channel_signature;
std::shared_ptr<SocketSSLContext> ssl_ctx;
};
// A dedicated thread to map a name to ServerIds
class NamingServiceThread : public SharedObject, public Describable {
struct ServerNodeWithId {
ServerNode node;
SocketId id;
inline bool operator<(const ServerNodeWithId& rhs) const {
return id != rhs.id ? (id < rhs.id) : (node < rhs.node);
}
};
class Actions : public NamingServiceActions {
public:
Actions(NamingServiceThread* owner);
~Actions();
void AddServers(const std::vector<ServerNode>& servers);
void RemoveServers(const std::vector<ServerNode>& servers);
void ResetServers(const std::vector<ServerNode>& servers);
int WaitForFirstBatchOfServers();
void EndWait(int error_code);
private:
NamingServiceThread* _owner;
bthread_id_t _wait_id;
butil::atomic<bool> _has_wait_error;
int _wait_error;
std::vector<ServerNode> _last_servers;
std::vector<ServerNode> _servers;
std::vector<ServerNode> _added;
std::vector<ServerNode> _removed;
std::vector<ServerNodeWithId> _sockets;
std::vector<ServerNodeWithId> _added_sockets;
std::vector<ServerNodeWithId> _removed_sockets;
};
public:
NamingServiceThread();
~NamingServiceThread();
int Start(NamingService* ns,
const std::string& protocol,
const std::string& service_name,
const GetNamingServiceThreadOptions* options);
int WaitForFirstBatchOfServers();
int AddWatcher(NamingServiceWatcher* w, const NamingServiceFilter* f);
int AddWatcher(NamingServiceWatcher* w) { return AddWatcher(w, NULL); }
int RemoveWatcher(NamingServiceWatcher* w);
void Describe(std::ostream& os, const DescribeOptions&) const;
private:
void Run();
static void* RunThis(void*);
static void ServerNodeWithId2ServerId(
const std::vector<ServerNodeWithId>& src,
std::vector<ServerId>* dst, const NamingServiceFilter* filter);
butil::Mutex _mutex;
bthread_t _tid;
NamingService* _ns;
std::string _protocol;
std::string _service_name;
GetNamingServiceThreadOptions _options;
std::vector<ServerNodeWithId> _last_sockets;
Actions _actions;
std::map<NamingServiceWatcher*, const NamingServiceFilter*> _watchers;
};
std::ostream& operator<<(std::ostream& os, const NamingServiceThread&);
// Get the decicated thread associated with `url' and put the thread into
// `ns_thread'. Calling with same `url' shares and returns the same thread.
// If the url is not accessed before, this function blocks until the
// NamingService returns the first batch of servers. If no servers are
// available, unless `options->succeed_without_server' is on, this function
// returns -1.
// Returns 0 on success, -1 otherwise.
int GetNamingServiceThread(butil::intrusive_ptr<NamingServiceThread>* ns_thread,
const char* url,
const GetNamingServiceThreadOptions* options);
} // namespace brpc
#endif // BRPC_NAMING_SERVICE_THREAD_H
+55
View File
@@ -0,0 +1,55 @@
// 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.
#ifndef BRPC_PROFILER_LINKER_H
#define BRPC_PROFILER_LINKER_H
#if defined(BRPC_ENABLE_CPU_PROFILER) || defined(BAIDU_RPC_ENABLE_CPU_PROFILER)
#include "butil/gperftools_profiler.h"
#endif
namespace brpc {
// defined in src/brpc/builtin/index_service.cpp
extern bool cpu_profiler_enabled;
// defined in src/brpc/controller.cpp
extern int PROFILER_LINKER_DUMMY;
struct ProfilerLinker {
// [ Must be inlined ]
// This function is included by user's compilation unit to force
// linking of ProfilerStart()/ProfilerStop()
// etc when corresponding macros are defined.
inline ProfilerLinker() {
#if defined(BRPC_ENABLE_CPU_PROFILER) || defined(BAIDU_RPC_ENABLE_CPU_PROFILER)
cpu_profiler_enabled = true;
// compiler has no way to tell if PROFILER_LINKER_DUMMY is 0 or not,
// so it has to link the function inside the branch.
if (PROFILER_LINKER_DUMMY != 0/*must be false*/) {
ProfilerStart("this_function_should_never_run");
}
#endif
}
};
} // namespace brpc
#endif // BRPC_PROFILER_LINKER_H
+63
View File
@@ -0,0 +1,63 @@
// 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.
#ifndef BRPC_DETAILS_RTMP_UTILS_H
#define BRPC_DETAILS_RTMP_UTILS_H
#include <stdint.h> // int32_t
#include <stddef.h> // size_t
namespace brpc {
// Extract bits one by one from the bytes.
class BitStream {
public:
BitStream(const void* data, size_t len)
: _data(data), _data_end((const char*)data + len), _shift(7) {}
~BitStream() {}
// True if no bits any more.
bool empty() { return _data == _data_end; }
// Read one bit from the data. empty() must be checked before calling
// this function, otherwise the behavior is undefined.
int8_t read_bit() {
const int8_t* p = (const int8_t*)_data;
int8_t result = (*p >> _shift) & 0x1;
if (_shift == 0) {
_shift = 7;
_data = p + 1;
} else {
--_shift;
}
return result;
}
private:
const void* _data;
const void* const _data_end;
int _shift;
};
int avc_nalu_read_uev(BitStream* stream, int32_t* v);
int avc_nalu_read_bit(BitStream* stream, int8_t* v);
} // namespace brpc
#endif // BRPC_DETAILS_RTMP_UTILS_H
@@ -0,0 +1,130 @@
// 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.
#ifndef BRPC_SERVER_PRIVATE_ACCESSOR_H
#define BRPC_SERVER_PRIVATE_ACCESSOR_H
#include <google/protobuf/descriptor.h>
#include "brpc/server.h"
#include "brpc/acceptor.h"
#include "brpc/details/method_status.h"
#include "brpc/builtin/bad_method_service.h"
#include "brpc/restful.h"
namespace brpc {
// A wrapper to access some private methods/fields of `Server'
// This is supposed to be used by internal RPC protocols ONLY
class ServerPrivateAccessor {
public:
explicit ServerPrivateAccessor(const Server* svr) {
CHECK(svr);
_server = svr;
}
void AddError() {
_server->_nerror_bvar << 1;
}
// Returns true if the `max_concurrency' limit is not reached.
bool AddConcurrency(Controller* c) {
if (_server->options().max_concurrency <= 0) {
return true;
}
c->add_flag(Controller::FLAGS_ADDED_CONCURRENCY);
return (butil::subtle::NoBarrier_AtomicIncrement(&_server->_concurrency, 1)
<= _server->options().max_concurrency);
}
void RemoveConcurrency(const Controller* c) {
if (c->has_flag(Controller::FLAGS_ADDED_CONCURRENCY)) {
butil::subtle::NoBarrier_AtomicIncrement(&_server->_concurrency, -1);
}
}
// Find by MethodDescriptor::full_name
const Server::MethodProperty*
FindMethodPropertyByFullName(const butil::StringPiece &fullname) {
return _server->FindMethodPropertyByFullName(fullname);
}
const Server::MethodProperty*
FindMethodPropertyByFullName(const butil::StringPiece& fullname) const {
return _server->FindMethodPropertyByFullName(fullname);
}
const Server::MethodProperty*
FindMethodPropertyByFullName(const butil::StringPiece& full_service_name,
const butil::StringPiece& method_name) const {
return _server->FindMethodPropertyByFullName(
full_service_name, method_name);
}
const Server::MethodProperty* FindMethodPropertyByNameAndIndex(
const butil::StringPiece& service_name, int method_index) const {
return _server->FindMethodPropertyByNameAndIndex(service_name, method_index);
}
const Server::ServiceProperty*
FindServicePropertyByFullName(const butil::StringPiece& fullname) const {
return _server->FindServicePropertyByFullName(fullname);
}
const Server::ServiceProperty*
FindServicePropertyByName(const butil::StringPiece& name) const {
return _server->FindServicePropertyByName(name);
}
const Server::ServiceProperty*
FindServicePropertyAdaptively(const butil::StringPiece& service_name) const {
if (service_name.find('.') == butil::StringPiece::npos) {
return _server->FindServicePropertyByName(service_name);
} else {
return _server->FindServicePropertyByFullName(service_name);
}
}
Acceptor* acceptor() const { return _server->_am; }
RestfulMap* global_restful_map() const
{ return _server->_global_restful_map; }
private:
const Server* _server;
};
// Count one error if release() is not called before destruction of this object.
class ScopedNonServiceError {
public:
ScopedNonServiceError(const Server* server) : _server(server) {}
~ScopedNonServiceError() {
if (_server) {
ServerPrivateAccessor(_server).AddError();
_server = NULL;
}
}
const Server* release() {
const Server* tmp = _server;
_server = NULL;
return tmp;
}
private:
DISALLOW_COPY_AND_ASSIGN(ScopedNonServiceError);
const Server* _server;
};
} // namespace brpc
#endif // BRPC_SERVER_PRIVATE_ACCESSOR_H
@@ -0,0 +1,168 @@
// 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.
#ifndef BRPC_SPARSE_MINUTE_COUNTER_H
#define BRPC_SPARSE_MINUTE_COUNTER_H
#include "butil/containers/bounded_queue.h"
namespace brpc {
// An utility to add up per-second value into per-minute value.
// About "sparse":
// This utility assumes that when a lot of instances exist, many of them do
// not need to update every second. This is true for stats of connections.
// When a lot of connections(>100K) connected to one server, most of them
// are idle since the overall actitivities of all connections are limited
// by throughput of the server. To make use of the fact, this utility stores
// per-second values in a sparse array tagged with timestamps. The array
// is resized on-demand to save memory.
template <typename T> class SparseMinuteCounter {
struct Item {
int64_t timestamp_ms;
T value;
Item() : timestamp_ms(0) {}
Item(int64_t ts, const T& v) : timestamp_ms(ts), value(v) {}
};
public:
SparseMinuteCounter() : _q(NULL) {}
~SparseMinuteCounter() { DestroyQueue(_q); }
// Add `value' into this counter at timestamp `now_ms'
// Returns true when old value is popped and set into *popped.
bool Add(int64_t now_ms, const T& value, T* popped);
// Try to pop value before one minute.
// Returns true when old value is popped and set into *popped.
bool TryPop(int64_t now_ms, T* popped);
private:
DISALLOW_COPY_AND_ASSIGN(SparseMinuteCounter);
typedef butil::BoundedQueue<Item> Q;
static Q* CreateQueue(uint32_t cap);
static void DestroyQueue(Q* q);
void Resize();
Q* _q;
Item _first_item;
};
template <typename T>
bool SparseMinuteCounter<T>::Add(int64_t now_ms, const T& val, T* popped) {
if (_q) { // more common
Item new_item(now_ms, val);
if (_q->full()) {
const Item* const oldest = _q->top();
if (now_ms < oldest->timestamp_ms + 60000 &&
_q->capacity() < 60) {
Resize();
_q->push(new_item);
return false;
} else {
*popped = oldest->value;
_q->pop();
_q->push(new_item);
return true;
}
} else {
_q->push(new_item);
return false;
}
} else {
// first-time storing is different. If Add() is rarely called,
// This strategy may not allocate _q at all.
if (_first_item.timestamp_ms == 0) {
_first_item.timestamp_ms = std::max(now_ms, (int64_t)1);
_first_item.value = val;
return false;
}
const int64_t delta = now_ms - _first_item.timestamp_ms;
if (delta >= 60000) {
*popped = _first_item.value;
_first_item.timestamp_ms = std::max(now_ms, (int64_t)1);
_first_item.value = val;
return true;
}
// Predict initial capacity of _q according to interval between
// now_ms and last timestamp.
int64_t initial_cap = (delta <= 1000 ? 30 : (60000 + delta - 1) / delta);
if (initial_cap < 4) {
initial_cap = 4;
}
_q = CreateQueue(initial_cap);
_q->push(_first_item);
_q->push(Item(now_ms, val));
return false;
}
}
template <typename T>
typename SparseMinuteCounter<T>::Q*
SparseMinuteCounter<T>::CreateQueue(uint32_t cap) {
const size_t memsize =
sizeof(Q) + sizeof(Item) * cap;
char* mem = (char*)malloc(memsize); // intended crash on ENOMEM
return new (mem) Q(mem + sizeof(Q), sizeof(Item) * cap, butil::NOT_OWN_STORAGE);
}
template <typename T>
void SparseMinuteCounter<T>::DestroyQueue(Q* q) {
if (q) {
q->~Q();
free(q);
}
}
template <typename T>
void SparseMinuteCounter<T>::Resize() {
CHECK_LT(_q->capacity(), (size_t)60);
uint32_t new_cap = std::min(2 * (uint32_t)_q->capacity(), 60u);
Q* new_q = CreateQueue(new_cap);
for (size_t i = 0; i < _q->size(); ++i) {
new_q->push(*_q->top(i));
}
DestroyQueue(_q);
_q = new_q;
}
template <typename T>
bool SparseMinuteCounter<T>::TryPop(int64_t now_ms, T* popped) {
if (_q) {
const Item* const oldest = _q->top();
if (oldest == NULL || now_ms < oldest->timestamp_ms + 60000) {
return false;
}
*popped = oldest->value;
_q->pop();
return true;
} else {
if (_first_item.timestamp_ms == 0 ||
now_ms < _first_item.timestamp_ms + 60000) {
return false;
}
_first_item.timestamp_ms = 0;
*popped = _first_item.value;
return true;
}
}
} // namespace brpc
#endif // BRPC_SPARSE_MINUTE_COUNTER_H
+107
View File
@@ -0,0 +1,107 @@
// 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.
#ifndef BRPC_SSL_HELPER_H
#define BRPC_SSL_HELPER_H
#include <string.h>
#ifndef USE_MESALINK
#include <openssl/ssl.h>
// For some versions of openssl, SSL_* are defined inside this header
#include <openssl/ossl_typ.h>
#else
#include <mesalink/openssl/ssl.h>
#include <mesalink/openssl/err.h>
#include <mesalink/openssl/x509.h>
#endif
#include "brpc/socket_id.h" // SocketId
#include "brpc/ssl_options.h" // ServerSSLOptions
namespace brpc {
enum SSLState {
SSL_UNKNOWN = 0,
SSL_OFF = 1, // Not an SSL connection
SSL_CONNECTING = 2, // During SSL handshake
SSL_CONNECTED = 3, // SSL handshake completed
};
enum SSLProtocol {
SSLv3 = 1 << 0,
TLSv1 = 1 << 1,
TLSv1_1 = 1 << 2,
TLSv1_2 = 1 << 3,
};
struct FreeSSLCTX {
inline void operator()(SSL_CTX* ctx) const {
if (ctx != NULL) {
SSL_CTX_free(ctx);
}
}
};
struct SSLError {
explicit SSLError(unsigned long e) : error(e) { }
unsigned long error;
};
std::ostream& operator<<(std::ostream& os, const SSLError&);
std::ostream& operator<<(std::ostream& os, const CertInfo&);
const char* SSLStateToString(SSLState s);
// Initialize locks and callbacks to make SSL work under multi-threaded
// environment. Return 0 on success, -1 otherwise
int SSLThreadInit();
// Initialize global Diffie-Hellman parameters used for DH key exchanges
// Return 0 on success, -1 otherwise
int SSLDHInit();
// Create a new SSL_CTX in client mode and
// set the right options according `options'
SSL_CTX* CreateClientSSLContext(const ChannelSSLOptions& options);
// Create a new SSL_CTX in server mode using `certificate_file'
// and `private_key_file' and then set the right options onto it
// according `options'. Finally, extract hostnames from CN/subject
// fields into `hostnames'
SSL_CTX* CreateServerSSLContext(const std::string& certificate_file,
const std::string& private_key_file,
const ServerSSLOptions& options,
std::vector<std::string>* hostnames);
// Create a new SSL (per connection object) using configurations in `ctx'.
// Set the required `fd' and mode. `id' will be set into SSL as app data.
SSL* CreateSSLSession(SSL_CTX* ctx, SocketId id, int fd, bool server_mode);
// Add a buffer layer of BIO in front of the socket fd layer,
// which can reduce the total number of calls to system read/write
void AddBIOBuffer(SSL* ssl, int fd, int bufsize);
// Judge whether the underlying channel of `fd' is using SSL
// If the return value is SSL_UNKNOWN, `error_code' will be
// set to indicate the reason (0 for EOF)
SSLState DetectSSLState(int fd, int* error_code);
void Print(std::ostream& os, SSL* ssl, const char* sep);
void Print(std::ostream& os, X509* cert, const char* sep);
} // namespace brpc
#endif // BRPC_SSL_HELPER_H
+319
View File
@@ -0,0 +1,319 @@
// Copyright (c) 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ---
// Author: Sanjay Ghemawat <opensource@google.com>
//
// Extra extensions exported by some malloc implementations. These
// extensions are accessed through a virtual base class so an
// application can link against a malloc that does not implement these
// extensions, and it will get default versions that do nothing.
//
// NOTE FOR C USERS: If you wish to use this functionality from within
// a C program, see malloc_extension_c.h.
#include <stddef.h>
// I can't #include config.h in this public API file, but I should
// really use configure (and make malloc_extension.h a .in file) to
// figure out if the system has stdint.h or not. But I'm lazy, so
// for now I'm assuming it's a problem only with MSVC.
#ifndef _MSC_VER
#include <stdint.h>
#endif
#include <string>
#include <vector>
// Annoying stuff for windows -- makes sure clients can import these functions
#ifndef PERFTOOLS_DLL_DECL
# ifdef _WIN32
# define PERFTOOLS_DLL_DECL __declspec(dllimport)
# else
# define PERFTOOLS_DLL_DECL
# endif
#endif
static const int kMallocHistogramSize = 64;
typedef std::string MallocExtensionWriter;
namespace base {
struct MallocRange;
}
// The default implementations of the following routines do nothing.
// All implementations should be thread-safe; the current one
// (TCMallocImplementation) is.
class PERFTOOLS_DLL_DECL MallocExtension {
public:
virtual ~MallocExtension();
// Call this very early in the program execution -- say, in a global
// constructor -- to set up parameters and state needed by all
// instrumented malloc implemenatations. One example: this routine
// sets environemnt variables to tell STL to use libc's malloc()
// instead of doing its own memory management. This is safe to call
// multiple times, as long as each time is before threads start up.
static void Initialize();
// See "verify_memory.h" to see what these routines do
virtual bool VerifyAllMemory();
virtual bool VerifyNewMemory(void* p);
virtual bool VerifyArrayNewMemory(void* p);
virtual bool VerifyMallocMemory(void* p);
virtual bool MallocMemoryStats(int* blocks, size_t* total,
int histogram[kMallocHistogramSize]);
// Get a human readable description of the current state of the malloc
// data structures. The state is stored as a null-terminated string
// in a prefix of "buffer[0,buffer_length-1]".
// REQUIRES: buffer_length > 0.
virtual void GetStats(char* buffer, int buffer_length);
// Outputs to "writer" a sample of live objects and the stack traces
// that allocated these objects. The format of the returned output
// is equivalent to the output of the heap profiler and can
// therefore be passed to "pprof".
// NOTE: by default, tcmalloc does not do any heap sampling, and this
// function will always return an empty sample. To get useful
// data from GetHeapSample, you must also set the environment
// variable TCMALLOC_SAMPLE_PARAMETER to a value such as 524288.
virtual void GetHeapSample(MallocExtensionWriter* writer);
// Outputs to "writer" the stack traces that caused growth in the
// address space size. The format of the returned output is
// equivalent to the output of the heap profiler and can therefore
// be passed to "pprof". (This does not depend on, or require,
// TCMALLOC_SAMPLE_PARAMETER.)
virtual void GetHeapGrowthStacks(MallocExtensionWriter* writer);
// Invokes func(arg, range) for every controlled memory
// range. *range is filled in with information about the range.
//
// This is a best-effort interface useful only for performance
// analysis. The implementation may not call func at all.
typedef void (RangeFunction)(void*, const base::MallocRange*);
virtual void Ranges(void* arg, RangeFunction func);
// -------------------------------------------------------------------
// Control operations for getting and setting malloc implementation
// specific parameters. Some currently useful properties:
//
// generic
// -------
// "generic.current_allocated_bytes"
// Number of bytes currently allocated by application
// This property is not writable.
//
// "generic.heap_size"
// Number of bytes in the heap ==
// current_allocated_bytes +
// fragmentation +
// freed memory regions
// This property is not writable.
//
// tcmalloc
// --------
// "tcmalloc.max_total_thread_cache_bytes"
// Upper limit on total number of bytes stored across all
// per-thread caches. Default: 16MB.
//
// "tcmalloc.current_total_thread_cache_bytes"
// Number of bytes used across all thread caches.
// This property is not writable.
//
// "tcmalloc.pageheap_free_bytes"
// Number of bytes in free, mapped pages in page heap. These
// bytes can be used to fulfill allocation requests. They
// always count towards virtual memory usage, and unless the
// underlying memory is swapped out by the OS, they also count
// towards physical memory usage. This property is not writable.
//
// "tcmalloc.pageheap_unmapped_bytes"
// Number of bytes in free, unmapped pages in page heap.
// These are bytes that have been released back to the OS,
// possibly by one of the MallocExtension "Release" calls.
// They can be used to fulfill allocation requests, but
// typically incur a page fault. They always count towards
// virtual memory usage, and depending on the OS, typically
// do not count towards physical memory usage. This property
// is not writable.
// -------------------------------------------------------------------
// Get the named "property"'s value. Returns true if the property
// is known. Returns false if the property is not a valid property
// name for the current malloc implementation.
// REQUIRES: property != NULL; value != NULL
virtual bool GetNumericProperty(const char* property, size_t* value);
// Set the named "property"'s value. Returns true if the property
// is known and writable. Returns false if the property is not a
// valid property name for the current malloc implementation, or
// is not writable.
// REQUIRES: property != NULL
virtual bool SetNumericProperty(const char* property, size_t value);
// Mark the current thread as "idle". This routine may optionally
// be called by threads as a hint to the malloc implementation that
// any thread-specific resources should be released. Note: this may
// be an expensive routine, so it should not be called too often.
//
// Also, if the code that calls this routine will go to sleep for
// a while, it should take care to not allocate anything between
// the call to this routine and the beginning of the sleep.
//
// Most malloc implementations ignore this routine.
virtual void MarkThreadIdle();
// Mark the current thread as "busy". This routine should be
// called after MarkThreadIdle() if the thread will now do more
// work. If this method is not called, performance may suffer.
//
// Most malloc implementations ignore this routine.
virtual void MarkThreadBusy();
// Try to release num_bytes of free memory back to the operating
// system for reuse. Use this extension with caution -- to get this
// memory back may require faulting pages back in by the OS, and
// that may be slow. (Currently only implemented in tcmalloc.)
virtual void ReleaseToSystem(size_t num_bytes);
// Same as ReleaseToSystem() but release as much memory as possible.
virtual void ReleaseFreeMemory();
// Sets the rate at which we release unused memory to the system.
// Zero means we never release memory back to the system. Increase
// this flag to return memory faster; decrease it to return memory
// slower. Reasonable rates are in the range [0,10]. (Currently
// only implemented in tcmalloc).
virtual void SetMemoryReleaseRate(double rate);
// Gets the release rate. Returns a value < 0 if unknown.
virtual double GetMemoryReleaseRate();
// Returns the estimated number of bytes that will be allocated for
// a request of "size" bytes. This is an estimate: an allocation of
// SIZE bytes may reserve more bytes, but will never reserve less.
// (Currently only implemented in tcmalloc, other implementations
// always return SIZE.)
// This is equivalent to malloc_good_size() in OS X.
virtual size_t GetEstimatedAllocatedSize(size_t size);
// Returns the actual number N of bytes reserved by tcmalloc for the
// pointer p. The client is allowed to use the range of bytes
// [p, p+N) in any way it wishes (i.e. N is the "usable size" of this
// allocation). This number may be equal to or greater than the number
// of bytes requested when p was allocated.
// p must have been allocated by this malloc implementation,
// must not be an interior pointer -- that is, must be exactly
// the pointer returned to by malloc() et al., not some offset
// from that -- and should not have been freed yet. p may be NULL.
// (Currently only implemented in tcmalloc; other implementations
// will return 0.)
// This is equivalent to malloc_size() in OS X, malloc_usable_size()
// in glibc, and _msize() for windows.
virtual size_t GetAllocatedSize(void* p);
// The current malloc implementation. Always non-NULL.
static MallocExtension* instance();
// Change the malloc implementation. Typically called by the
// malloc implementation during initialization.
static void Register(MallocExtension* implementation);
// Returns detailed information about malloc's freelists. For each list,
// return a FreeListInfo:
struct FreeListInfo {
size_t min_object_size;
size_t max_object_size;
size_t total_bytes_free;
const char* type;
};
// Each item in the vector refers to a different freelist. The lists
// are identified by the range of allocations that objects in the
// list can satisfy ([min_object_size, max_object_size]) and the
// type of freelist (see below). The current size of the list is
// returned in total_bytes_free (which count against a processes
// resident and virtual size).
//
// Currently supported types are:
//
// "tcmalloc.page{_unmapped}" - tcmalloc's page heap. An entry for each size
// class in the page heap is returned. Bytes in "page_unmapped"
// are no longer backed by physical memory and do not count against
// the resident size of a process.
//
// "tcmalloc.large{_unmapped}" - tcmalloc's list of objects larger
// than the largest page heap size class. Only one "large"
// entry is returned. There is no upper-bound on the size
// of objects in the large free list; this call returns
// kint64max for max_object_size. Bytes in
// "large_unmapped" are no longer backed by physical memory
// and do not count against the resident size of a process.
//
// "tcmalloc.central" - tcmalloc's central free-list. One entry per
// size-class is returned. Never unmapped.
//
// "debug.free_queue" - free objects queued by the debug allocator
// and not returned to tcmalloc.
//
// "tcmalloc.thread" - tcmalloc's per-thread caches. Never unmapped.
virtual void GetFreeListSizes(std::vector<FreeListInfo>* v);
protected:
// Get a list of stack traces of sampled allocation points. Returns
// a pointer to a "new[]-ed" result array, and stores the sample
// period in "sample_period".
//
// The state is stored as a sequence of adjacent entries
// in the returned array. Each entry has the following form:
// uintptr_t count; // Number of objects with following trace
// uintptr_t size; // Total size of objects with following trace
// uintptr_t depth; // Number of PC values in stack trace
// void* stack[depth]; // PC values that form the stack trace
//
// The list of entries is terminated by a "count" of 0.
//
// It is the responsibility of the caller to "delete[]" the returned array.
//
// May return NULL to indicate no results.
//
// This is an internal extension. Callers should use the more
// convenient "GetHeapSample(string*)" method defined above.
virtual void** ReadStackTraces(int* sample_period);
// Like ReadStackTraces(), but returns stack traces that caused growth
// in the address space size.
virtual void** ReadHeapGrowthStackTraces();
};
// True iff heap profiler is enabled.
bool IsHeapProfilerEnabled();
// True iff TCMALLOC_SAMPLE_PARAMETER is set in environment.
bool has_TCMALLOC_SAMPLE_PARAMETER();
@@ -0,0 +1,88 @@
// 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.
#ifndef BRPC_USERCODE_BACKUP_POOL_H
#define BRPC_USERCODE_BACKUP_POOL_H
#include "butil/atomicops.h"
#include "bthread/bthread.h"
#include <gflags/gflags_declare.h>
namespace brpc {
DECLARE_bool(usercode_in_pthread);
DECLARE_int32(usercode_backup_threads);
// "user code backup pool" is a set of pthreads to run user code when #pthread
// workers of bthreads reaches a threshold, avoiding potential deadlock when
// -usercode_in_pthread is on. These threads are NOT supposed to be active
// frequently, if they're, user should configure more num_threads for the
// server or set -bthread_concurrency to a larger value.
// Run the user code in-place or in backup threads. The place depends on
// busy-ness of bthread workers.
// NOTE: To avoid memory allocation(for `arg') in the case of in-place running,
// check out the inline impl. of this function just below.
void RunUserCode(void (*fn)(void*), void* arg);
// RPC code should check this function before submitting operations that have
// user code to run laterly.
inline bool TooManyUserCode() {
extern bool g_too_many_usercode;
return g_too_many_usercode;
}
// If this function returns true, the user code is suggested to be run in-place
// and user should call EndRunningUserCodeInPlace() after running the code.
// Otherwise, user should call EndRunningUserCodeInPool() to run the user code
// in backup threads.
// Check RunUserCode() below to see the usage pattern.
inline bool BeginRunningUserCode() {
extern butil::static_atomic<int> g_usercode_inplace;
return (g_usercode_inplace.fetch_add(1, butil::memory_order_relaxed)
+ FLAGS_usercode_backup_threads) < bthread_getconcurrency();
}
inline void EndRunningUserCodeInPlace() {
extern butil::static_atomic<int> g_usercode_inplace;
g_usercode_inplace.fetch_sub(1, butil::memory_order_relaxed);
}
void EndRunningUserCodeInPool(void (*fn)(void*), void* arg);
// Incorporate functions above together. However `arg' to this function often
// has to be new-ed even for in-place cases. If performance is critical, use
// the BeginXXX/EndXXX pattern.
inline void RunUserCode(void (*fn)(void*), void* arg) {
if (BeginRunningUserCode()) {
fn(arg);
EndRunningUserCodeInPlace();
} else {
EndRunningUserCodeInPool(fn, arg);
}
}
// [Optional] initialize the pool of backup threads. If this function is not
// called, it will be called in EndRunningUserCodeInPool
void InitUserCodeBackupPoolOnceOrDie();
} // namespace brpc
#endif //BRPC_USERCODE_BACKUP_POOL_H
+139
View File
@@ -0,0 +1,139 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: brpc/errno.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_brpc_2ferrno_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_brpc_2ferrno_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3017000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3017003 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/generated_enum_reflection.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_brpc_2ferrno_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_brpc_2ferrno_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_brpc_2ferrno_2eproto;
PROTOBUF_NAMESPACE_OPEN
PROTOBUF_NAMESPACE_CLOSE
namespace brpc {
enum Errno : int {
ENOSERVICE = 1001,
ENOMETHOD = 1002,
EREQUEST = 1003,
ERPCAUTH = 1004,
ETOOMANYFAILS = 1005,
EPCHANFINISH = 1006,
EBACKUPREQUEST = 1007,
ERPCTIMEDOUT = 1008,
EFAILEDSOCKET = 1009,
EHTTP = 1010,
EOVERCROWDED = 1011,
ERTMPPUBLISHABLE = 1012,
ERTMPCREATESTREAM = 1013,
EEOF = 1014,
EUNUSED = 1015,
ESSL = 1016,
EH2RUNOUTSTREAMS = 1017,
EREJECT = 1018,
EINTERNAL = 2001,
ERESPONSE = 2002,
ELOGOFF = 2003,
ELIMIT = 2004,
ECLOSE = 2005,
EITP = 2006,
ERDMA = 3001,
ERDMAMEM = 3002
};
bool Errno_IsValid(int value);
constexpr Errno Errno_MIN = ENOSERVICE;
constexpr Errno Errno_MAX = ERDMAMEM;
constexpr int Errno_ARRAYSIZE = Errno_MAX + 1;
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Errno_descriptor();
template<typename T>
inline const std::string& Errno_Name(T enum_t_value) {
static_assert(::std::is_same<T, Errno>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function Errno_Name.");
return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
Errno_descriptor(), enum_t_value);
}
inline bool Errno_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Errno* value) {
return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<Errno>(
Errno_descriptor(), name, value);
}
// ===================================================================
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
} // namespace brpc
PROTOBUF_NAMESPACE_OPEN
template <> struct is_proto_enum< ::brpc::Errno> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::brpc::Errno>() {
return ::brpc::Errno_descriptor();
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_brpc_2ferrno_2eproto
+44
View File
@@ -0,0 +1,44 @@
// 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.
#ifndef BRPC_ESP_HEAD_H
#define BRPC_ESP_HEAD_H
namespace brpc {
#pragma pack(push, r1, 1)
union EspAddress {
uint64_t addr;
struct {
uint16_t stub;
uint16_t port;
uint32_t ip;
};
};
struct EspHead {
EspAddress from;
EspAddress to;
uint32_t msg;
uint64_t msg_id;
int body_len;
};
#pragma pack(pop, r1)
} // namespace brpc
#endif // BRPC_ESP_HEAD_H
+87
View File
@@ -0,0 +1,87 @@
// 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.
#ifndef BRPC_ESP_MESSAGE_H
#define BRPC_ESP_MESSAGE_H
#include <string>
#include <google/protobuf/message.h>
#include <google/protobuf/generated_message_reflection.h> // dynamic_cast_if_available
#include <google/protobuf/reflection_ops.h> // ReflectionOps::Merge
#include "brpc/esp_head.h"
#include "butil/iobuf.h"
#include "brpc/proto_base.pb.h"
#include "brpc/pb_compat.h"
namespace brpc {
class EspMessage : public ::google::protobuf::Message {
public:
EspHead head;
butil::IOBuf body;
public:
EspMessage();
virtual ~EspMessage();
EspMessage(const EspMessage& from);
inline EspMessage& operator=(const EspMessage& from) {
CopyFrom(from);
return *this;
}
static const ::google::protobuf::Descriptor* descriptor();
static const EspMessage& default_instance();
void Swap(EspMessage* other);
// implements Message ----------------------------------------------
EspMessage* New() const PB_319_OVERRIDE;
#if GOOGLE_PROTOBUF_VERSION >= 3006000
EspMessage* New(::google::protobuf::Arena* arena) const override;
#endif
void CopyFrom(const ::google::protobuf::Message& from) PB_321_OVERRIDE;
void MergeFrom(const ::google::protobuf::Message& from) override;
void CopyFrom(const EspMessage& from);
void MergeFrom(const EspMessage& from);
void Clear() override;
bool IsInitialized() const override;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PB_310_OVERRIDE;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PB_310_OVERRIDE;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(
::google::protobuf::uint8* output) const PB_310_OVERRIDE;
int GetCachedSize() const override { return ByteSize(); }
protected:
::google::protobuf::Metadata GetMetadata() const override;
private:
void SharedCtor();
void SharedDtor();
};
} // namespace brpc
#endif // BRPC_ESP_MESSAGE_H
+107
View File
@@ -0,0 +1,107 @@
// 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.
#ifndef BRPC_EVENT_DISPATCHER_H
#define BRPC_EVENT_DISPATCHER_H
#include "butil/macros.h" // DISALLOW_COPY_AND_ASSIGN
#include "bthread/types.h" // bthread_t, bthread_attr_t
#include "brpc/socket.h" // Socket, SocketId
namespace brpc {
// Dispatch edge-triggered events of file descriptors to consumers
// running in separate bthreads.
class EventDispatcher {
friend class Socket;
friend class rdma::RdmaEndpoint;
public:
EventDispatcher();
virtual ~EventDispatcher();
// Start this dispatcher in a bthread.
// Use |*consumer_thread_attr| (if it's not NULL) as the attribute to
// create bthreads running user callbacks.
// Returns 0 on success, -1 otherwise.
virtual int Start(const bthread_attr_t* consumer_thread_attr);
// True iff this dispatcher is running in a bthread
bool Running() const;
// Stop bthread of this dispatcher.
void Stop();
// Suspend calling thread until bthread of this dispatcher stops.
void Join();
// When edge-triggered events happen on `fd', call
// `on_edge_triggered_events' of `socket_id'.
// Notice that this function also transfers ownership of `socket_id',
// When the file descriptor is removed from internal epoll, the Socket
// will be dereferenced once additionally.
// Returns 0 on success, -1 otherwise.
int AddConsumer(SocketId socket_id, int fd);
// Watch EPOLLOUT event on `fd' into epoll device. If `pollin' is
// true, EPOLLIN event will also be included and EPOLL_CTL_MOD will
// be used instead of EPOLL_CTL_ADD. When event arrives,
// `Socket::HandleEpollOut' will be called with `socket_id'
// Returns 0 on success, -1 otherwise and errno is set
int AddEpollOut(SocketId socket_id, int fd, bool pollin);
// Remove EPOLLOUT event on `fd'. If `pollin' is true, EPOLLIN event
// will be kept and EPOLL_CTL_MOD will be used instead of EPOLL_CTL_DEL
// Returns 0 on success, -1 otherwise and errno is set
int RemoveEpollOut(SocketId socket_id, int fd, bool pollin);
private:
DISALLOW_COPY_AND_ASSIGN(EventDispatcher);
// Calls Run()
static void* RunThis(void* arg);
// Thread entry.
void Run();
// Remove the file descriptor `fd' from epoll.
int RemoveConsumer(int fd);
// The epoll to watch events.
int _epfd;
// false unless Stop() is called.
volatile bool _stop;
// identifier of hosting bthread
bthread_t _tid;
// The attribute of bthreads calling user callbacks.
bthread_attr_t _consumer_thread_attr;
// Pipe fds to wakeup EventDispatcher from `epoll_wait' in order to quit
int _wakeup_fds[2];
};
EventDispatcher& GetGlobalEventDispatcher(int fd);
} // namespace brpc
#endif // BRPC_EVENT_DISPATCHER_H
+102
View File
@@ -0,0 +1,102 @@
// 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.
#ifndef BRPC_EXCLUDED_SERVERS_H
#define BRPC_EXCLUDED_SERVERS_H
#include "butil/scoped_lock.h"
#include "butil/containers/bounded_queue.h"
#include "brpc/socket_id.h" // SocketId
namespace brpc {
// Remember servers that should be avoided in selection. These servers
// are often selected in previous tries inside a RPC.
class ExcludedServers {
public:
// Create a instance with at most `cap' servers.
static ExcludedServers* Create(int cap);
// Destroy the instance
static void Destroy(ExcludedServers* ptr);
// Add a server. If the internal queue is full, pop one from the queue first.
void Add(SocketId id);
// True if the server shall be excluded.
bool IsExcluded(SocketId id) const;
static bool IsExcluded(const ExcludedServers* s, SocketId id) {
return s != NULL && s->IsExcluded(id);
}
// #servers inside.
size_t size() const { return _l.size(); }
private:
ExcludedServers(int cap)
: _l(_space, sizeof(SocketId)* cap, butil::NOT_OWN_STORAGE) {}
~ExcludedServers() {}
// Controller::_accessed may be shared by sub channels in schan, protect
// all mutable methods with this mutex. In ordinary channels, this mutex
// is never contended.
mutable butil::Mutex _mutex;
butil::BoundedQueue<SocketId> _l;
SocketId _space[0];
};
// ===================================================
inline ExcludedServers* ExcludedServers::Create(int cap) {
void *space = malloc(
offsetof(ExcludedServers, _space) + sizeof(SocketId) * cap);
if (NULL == space) {
return NULL;
}
return new (space) ExcludedServers(cap);
}
inline void ExcludedServers::Destroy(ExcludedServers* ptr) {
if (ptr) {
ptr->~ExcludedServers();
free(ptr);
}
}
inline void ExcludedServers::Add(SocketId id) {
BAIDU_SCOPED_LOCK(_mutex);
const SocketId* last_id = _l.bottom();
if (last_id == NULL || *last_id != id) {
_l.elim_push(id);
}
}
inline bool ExcludedServers::IsExcluded(SocketId id) const {
BAIDU_SCOPED_LOCK(_mutex);
for (size_t i = 0; i < _l.size(); ++i) {
if (*_l.bottom(i) == id) {
return true;
}
}
return false;
}
} // namespace brpc
#endif // BRPC_EXCLUDED_SERVERS_H
+63
View File
@@ -0,0 +1,63 @@
// 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.
#ifndef BRPC_EXTENSION_H
#define BRPC_EXTENSION_H
#include <string>
#include "butil/scoped_lock.h"
#include "butil/logging.h"
#include "butil/containers/case_ignored_flat_map.h"
#include "butil/memory/singleton_on_pthread_once.h"
namespace butil {
template <typename T> class GetLeakySingleton;
}
namespace brpc {
// A global map from string to user-extended instances (typed T).
// It's used by NamingService and LoadBalancer to maintain globally
// available instances.
// All names are case-insensitive. Names are printed in lowercases.
template <typename T>
class Extension {
public:
static Extension<T>* instance();
int Register(const std::string& name, T* instance);
int RegisterOrDie(const std::string& name, T* instance);
T* Find(const char* name);
void List(std::ostream& os, char separator);
private:
friend class butil::GetLeakySingleton<Extension<T> >;
Extension();
~Extension();
butil::CaseIgnoredFlatMap<T*> _instance_map;
butil::Mutex _map_mutex;
};
} // namespace brpc
#include "brpc/extension_inl.h"
#endif // BRPC_EXTENSION_H
+96
View File
@@ -0,0 +1,96 @@
// 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.
#ifndef BRPC_EXTENSION_INL_H
#define BRPC_EXTENSION_INL_H
namespace brpc {
template <typename T>
Extension<T>* Extension<T>::instance() {
// NOTE: We don't delete extensions because in principle they can be
// accessed during exiting, e.g. create a channel to send rpc at exit.
return butil::get_leaky_singleton<Extension<T> >();
}
template <typename T>
Extension<T>::Extension() {
_instance_map.init(29);
}
template <typename T>
Extension<T>::~Extension() {
}
template <typename T>
int Extension<T>::Register(const std::string& name, T* instance) {
if (NULL == instance) {
LOG(ERROR) << "instance to \"" << name << "\" is NULL";
return -1;
}
BAIDU_SCOPED_LOCK(_map_mutex);
if (_instance_map.seek(name) != NULL) {
LOG(ERROR) << "\"" << name << "\" was registered";
return -1;
}
_instance_map[name] = instance;
return 0;
}
template <typename T>
int Extension<T>::RegisterOrDie(const std::string& name, T* instance) {
if (Register(name, instance) == 0) {
return 0;
}
exit(1);
}
template <typename T>
T* Extension<T>::Find(const char* name) {
if (NULL == name) {
return NULL;
}
BAIDU_SCOPED_LOCK(_map_mutex);
T** p = _instance_map.seek(name);
if (p) {
return *p;
}
return NULL;
}
template <typename T>
void Extension<T>::List(std::ostream& os, char separator) {
BAIDU_SCOPED_LOCK(_map_mutex);
for (typename butil::CaseIgnoredFlatMap<T*>::iterator
it = _instance_map.begin(); it != _instance_map.end(); ++it) {
// private extensions which is not intended to be seen by users starts
// with underscore.
if (it->first.data()[0] != '_') {
if (it != _instance_map.begin()) {
os << separator;
}
os << it->first;
}
}
}
} // namespace brpc
#endif // BRPC_EXTENSION_INL_H
+424
View File
@@ -0,0 +1,424 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: brpc/get_favicon.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_brpc_2fget_5ffavicon_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_brpc_2fget_5ffavicon_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3017000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3017003 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/service.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_brpc_2fget_5ffavicon_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_brpc_2fget_5ffavicon_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[2]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_brpc_2fget_5ffavicon_2eproto;
namespace brpc {
class GetFaviconRequest;
struct GetFaviconRequestDefaultTypeInternal;
extern GetFaviconRequestDefaultTypeInternal _GetFaviconRequest_default_instance_;
class GetFaviconResponse;
struct GetFaviconResponseDefaultTypeInternal;
extern GetFaviconResponseDefaultTypeInternal _GetFaviconResponse_default_instance_;
} // namespace brpc
PROTOBUF_NAMESPACE_OPEN
template<> ::brpc::GetFaviconRequest* Arena::CreateMaybeMessage<::brpc::GetFaviconRequest>(Arena*);
template<> ::brpc::GetFaviconResponse* Arena::CreateMaybeMessage<::brpc::GetFaviconResponse>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace brpc {
// ===================================================================
class GetFaviconRequest final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:brpc.GetFaviconRequest) */ {
public:
inline GetFaviconRequest() : GetFaviconRequest(nullptr) {}
~GetFaviconRequest() override;
explicit constexpr GetFaviconRequest(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
GetFaviconRequest(const GetFaviconRequest& from);
GetFaviconRequest(GetFaviconRequest&& from) noexcept
: GetFaviconRequest() {
*this = ::std::move(from);
}
inline GetFaviconRequest& operator=(const GetFaviconRequest& from) {
CopyFrom(from);
return *this;
}
inline GetFaviconRequest& operator=(GetFaviconRequest&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const GetFaviconRequest& default_instance() {
return *internal_default_instance();
}
static inline const GetFaviconRequest* internal_default_instance() {
return reinterpret_cast<const GetFaviconRequest*>(
&_GetFaviconRequest_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(GetFaviconRequest& a, GetFaviconRequest& b) {
a.Swap(&b);
}
inline void Swap(GetFaviconRequest* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(GetFaviconRequest* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline GetFaviconRequest* New() const final {
return new GetFaviconRequest();
}
GetFaviconRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<GetFaviconRequest>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const GetFaviconRequest& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const GetFaviconRequest& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(GetFaviconRequest* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "brpc.GetFaviconRequest";
}
protected:
explicit GetFaviconRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// @@protoc_insertion_point(class_scope:brpc.GetFaviconRequest)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_brpc_2fget_5ffavicon_2eproto;
};
// -------------------------------------------------------------------
class GetFaviconResponse final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:brpc.GetFaviconResponse) */ {
public:
inline GetFaviconResponse() : GetFaviconResponse(nullptr) {}
~GetFaviconResponse() override;
explicit constexpr GetFaviconResponse(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
GetFaviconResponse(const GetFaviconResponse& from);
GetFaviconResponse(GetFaviconResponse&& from) noexcept
: GetFaviconResponse() {
*this = ::std::move(from);
}
inline GetFaviconResponse& operator=(const GetFaviconResponse& from) {
CopyFrom(from);
return *this;
}
inline GetFaviconResponse& operator=(GetFaviconResponse&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const GetFaviconResponse& default_instance() {
return *internal_default_instance();
}
static inline const GetFaviconResponse* internal_default_instance() {
return reinterpret_cast<const GetFaviconResponse*>(
&_GetFaviconResponse_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
friend void swap(GetFaviconResponse& a, GetFaviconResponse& b) {
a.Swap(&b);
}
inline void Swap(GetFaviconResponse* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(GetFaviconResponse* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline GetFaviconResponse* New() const final {
return new GetFaviconResponse();
}
GetFaviconResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<GetFaviconResponse>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const GetFaviconResponse& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const GetFaviconResponse& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(GetFaviconResponse* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "brpc.GetFaviconResponse";
}
protected:
explicit GetFaviconResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// @@protoc_insertion_point(class_scope:brpc.GetFaviconResponse)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_brpc_2fget_5ffavicon_2eproto;
};
// ===================================================================
class ico_Stub;
class ico : public ::PROTOBUF_NAMESPACE_ID::Service {
protected:
// This class should be treated as an abstract interface.
inline ico() {};
public:
virtual ~ico();
typedef ico_Stub Stub;
static const ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor* descriptor();
virtual void default_method(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetFaviconRequest* request,
::brpc::GetFaviconResponse* response,
::google::protobuf::Closure* done);
// implements Service ----------------------------------------------
const ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor* GetDescriptor();
void CallMethod(const ::PROTOBUF_NAMESPACE_ID::MethodDescriptor* method,
::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::PROTOBUF_NAMESPACE_ID::Message* request,
::PROTOBUF_NAMESPACE_ID::Message* response,
::google::protobuf::Closure* done);
const ::PROTOBUF_NAMESPACE_ID::Message& GetRequestPrototype(
const ::PROTOBUF_NAMESPACE_ID::MethodDescriptor* method) const;
const ::PROTOBUF_NAMESPACE_ID::Message& GetResponsePrototype(
const ::PROTOBUF_NAMESPACE_ID::MethodDescriptor* method) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ico);
};
class ico_Stub : public ico {
public:
ico_Stub(::PROTOBUF_NAMESPACE_ID::RpcChannel* channel);
ico_Stub(::PROTOBUF_NAMESPACE_ID::RpcChannel* channel,
::PROTOBUF_NAMESPACE_ID::Service::ChannelOwnership ownership);
~ico_Stub();
inline ::PROTOBUF_NAMESPACE_ID::RpcChannel* channel() { return channel_; }
// implements ico ------------------------------------------
void default_method(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetFaviconRequest* request,
::brpc::GetFaviconResponse* response,
::google::protobuf::Closure* done);
private:
::PROTOBUF_NAMESPACE_ID::RpcChannel* channel_;
bool owns_channel_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ico_Stub);
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// GetFaviconRequest
// -------------------------------------------------------------------
// GetFaviconResponse
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace brpc
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_brpc_2fget_5ffavicon_2eproto
+448
View File
@@ -0,0 +1,448 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: brpc/get_js.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_brpc_2fget_5fjs_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_brpc_2fget_5fjs_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3017000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3017003 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/service.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_brpc_2fget_5fjs_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_brpc_2fget_5fjs_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[2]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_brpc_2fget_5fjs_2eproto;
namespace brpc {
class GetJsRequest;
struct GetJsRequestDefaultTypeInternal;
extern GetJsRequestDefaultTypeInternal _GetJsRequest_default_instance_;
class GetJsResponse;
struct GetJsResponseDefaultTypeInternal;
extern GetJsResponseDefaultTypeInternal _GetJsResponse_default_instance_;
} // namespace brpc
PROTOBUF_NAMESPACE_OPEN
template<> ::brpc::GetJsRequest* Arena::CreateMaybeMessage<::brpc::GetJsRequest>(Arena*);
template<> ::brpc::GetJsResponse* Arena::CreateMaybeMessage<::brpc::GetJsResponse>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace brpc {
// ===================================================================
class GetJsRequest final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:brpc.GetJsRequest) */ {
public:
inline GetJsRequest() : GetJsRequest(nullptr) {}
~GetJsRequest() override;
explicit constexpr GetJsRequest(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
GetJsRequest(const GetJsRequest& from);
GetJsRequest(GetJsRequest&& from) noexcept
: GetJsRequest() {
*this = ::std::move(from);
}
inline GetJsRequest& operator=(const GetJsRequest& from) {
CopyFrom(from);
return *this;
}
inline GetJsRequest& operator=(GetJsRequest&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const GetJsRequest& default_instance() {
return *internal_default_instance();
}
static inline const GetJsRequest* internal_default_instance() {
return reinterpret_cast<const GetJsRequest*>(
&_GetJsRequest_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(GetJsRequest& a, GetJsRequest& b) {
a.Swap(&b);
}
inline void Swap(GetJsRequest* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(GetJsRequest* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline GetJsRequest* New() const final {
return new GetJsRequest();
}
GetJsRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<GetJsRequest>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const GetJsRequest& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const GetJsRequest& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(GetJsRequest* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "brpc.GetJsRequest";
}
protected:
explicit GetJsRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// @@protoc_insertion_point(class_scope:brpc.GetJsRequest)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_brpc_2fget_5fjs_2eproto;
};
// -------------------------------------------------------------------
class GetJsResponse final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:brpc.GetJsResponse) */ {
public:
inline GetJsResponse() : GetJsResponse(nullptr) {}
~GetJsResponse() override;
explicit constexpr GetJsResponse(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
GetJsResponse(const GetJsResponse& from);
GetJsResponse(GetJsResponse&& from) noexcept
: GetJsResponse() {
*this = ::std::move(from);
}
inline GetJsResponse& operator=(const GetJsResponse& from) {
CopyFrom(from);
return *this;
}
inline GetJsResponse& operator=(GetJsResponse&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const GetJsResponse& default_instance() {
return *internal_default_instance();
}
static inline const GetJsResponse* internal_default_instance() {
return reinterpret_cast<const GetJsResponse*>(
&_GetJsResponse_default_instance_);
}
static constexpr int kIndexInFileMessages =
1;
friend void swap(GetJsResponse& a, GetJsResponse& b) {
a.Swap(&b);
}
inline void Swap(GetJsResponse* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(GetJsResponse* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline GetJsResponse* New() const final {
return new GetJsResponse();
}
GetJsResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<GetJsResponse>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const GetJsResponse& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const GetJsResponse& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(GetJsResponse* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "brpc.GetJsResponse";
}
protected:
explicit GetJsResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// @@protoc_insertion_point(class_scope:brpc.GetJsResponse)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_brpc_2fget_5fjs_2eproto;
};
// ===================================================================
class js_Stub;
class js : public ::PROTOBUF_NAMESPACE_ID::Service {
protected:
// This class should be treated as an abstract interface.
inline js() {};
public:
virtual ~js();
typedef js_Stub Stub;
static const ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor* descriptor();
virtual void sorttable(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetJsRequest* request,
::brpc::GetJsResponse* response,
::google::protobuf::Closure* done);
virtual void jquery_min(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetJsRequest* request,
::brpc::GetJsResponse* response,
::google::protobuf::Closure* done);
virtual void flot_min(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetJsRequest* request,
::brpc::GetJsResponse* response,
::google::protobuf::Closure* done);
virtual void viz_min(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetJsRequest* request,
::brpc::GetJsResponse* response,
::google::protobuf::Closure* done);
// implements Service ----------------------------------------------
const ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor* GetDescriptor();
void CallMethod(const ::PROTOBUF_NAMESPACE_ID::MethodDescriptor* method,
::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::PROTOBUF_NAMESPACE_ID::Message* request,
::PROTOBUF_NAMESPACE_ID::Message* response,
::google::protobuf::Closure* done);
const ::PROTOBUF_NAMESPACE_ID::Message& GetRequestPrototype(
const ::PROTOBUF_NAMESPACE_ID::MethodDescriptor* method) const;
const ::PROTOBUF_NAMESPACE_ID::Message& GetResponsePrototype(
const ::PROTOBUF_NAMESPACE_ID::MethodDescriptor* method) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(js);
};
class js_Stub : public js {
public:
js_Stub(::PROTOBUF_NAMESPACE_ID::RpcChannel* channel);
js_Stub(::PROTOBUF_NAMESPACE_ID::RpcChannel* channel,
::PROTOBUF_NAMESPACE_ID::Service::ChannelOwnership ownership);
~js_Stub();
inline ::PROTOBUF_NAMESPACE_ID::RpcChannel* channel() { return channel_; }
// implements js ------------------------------------------
void sorttable(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetJsRequest* request,
::brpc::GetJsResponse* response,
::google::protobuf::Closure* done);
void jquery_min(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetJsRequest* request,
::brpc::GetJsResponse* response,
::google::protobuf::Closure* done);
void flot_min(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetJsRequest* request,
::brpc::GetJsResponse* response,
::google::protobuf::Closure* done);
void viz_min(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
const ::brpc::GetJsRequest* request,
::brpc::GetJsResponse* response,
::google::protobuf::Closure* done);
private:
::PROTOBUF_NAMESPACE_ID::RpcChannel* channel_;
bool owns_channel_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(js_Stub);
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// GetJsRequest
// -------------------------------------------------------------------
// GetJsResponse
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace brpc
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_brpc_2fget_5fjs_2eproto
+32
View File
@@ -0,0 +1,32 @@
// 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.
#ifndef BRPC_GLOBAL_H
#define BRPC_GLOBAL_H
namespace brpc {
// Register all naming service, load balancers, compress handlers inside
// `brpc/policy/' directory
void GlobalInitializeOrDie();
} // namespace brpc
#endif // BRPC_GLOBAL_H
+161
View File
@@ -0,0 +1,161 @@
// 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.
#ifndef BRPC_GRPC_H
#define BRPC_GRPC_H
#include <map>
#include <brpc/http2.h>
namespace brpc {
enum GrpcStatus {
// OK is returned on success.
GRPC_OK = 0,
// CANCELED indicates the operation was canceled (typically by the caller).
GRPC_CANCELED,
// Unknown error. An example of where this error may be returned is
// if a Status value received from another address space belongs to
// an error-space that is not known in this address space. Also
// errors raised by APIs that do not return enough error information
// may be converted to this error.
GRPC_UNKNOWN,
// INVALIDARGUMENT Indicates client specified an invalid argument.
// Note that this differs from FAILEDPRECONDITION. It indicates arguments
// that are problematic regardless of the state of the system
// (e.g., a malformed file name).
GRPC_INVALIDARGUMENT,
// DEADLINEEXCEEDED Means operation expired before completion.
// For operations that change the state of the system, this error may be
// returned even if the operation has completed successfully. For
// example, a successful response from a server could have been delayed
// long enough for the deadline to expire.
GRPC_DEADLINEEXCEEDED,
// NOTFOUND Means some requested entity (e.g., file or directory) was
// not found.
GRPC_NOTFOUND,
// ALREADYEXISTS Means an attempt to create an entity failed because one
// already exists.
GRPC_ALREADYEXISTS,
// PERMISSIONDENIED Indicates the caller does not have permission to
// execute the specified operation. It must not be used for rejections
// caused by exhausting some resource (use ResourceExhausted
// instead for those errors). It must not be
// used if the caller cannot be identified (use UNAUTHENTICATED
// instead for those errors).
GRPC_PERMISSIONDENIED,
// RESOURCEEXHAUSTED Indicates some resource has been exhausted, perhaps
// a per-user quota, or perhaps the entire file system is out of space.
GRPC_RESOURCEEXHAUSTED,
// FAILEDPRECONDITION indicates operation was rejected because the
// system is not in a state required for the operation's execution.
// For example, directory to be deleted may be non-empty, an rmdir
// operation is applied to a non-directory, etc.
//
// A litmus test that may help a service implementor in deciding
// between FAILEDPRECONDITION, Aborted, and Unavailable:
// (a) Use Unavailable if the client can retry just the failing call.
// (b) Use Aborted if the client should retry at a higher-level
// (e.g., restarting a read-modify-write sequence).
// (c) Use FAILEDPRECONDITION if the client should not retry until
// the system state has been explicitly fixed. E.g., if an "rmdir"
// fails because the directory is non-empty, FAILEDPRECONDITION
// should be returned since the client should not retry unless
// they have first fixed up the directory by deleting files from it.
// (d) Use FAILEDPRECONDITION if the client performs conditional
// REST Get/Update/Delete on a resource and the resource on the
// server does not match the condition. E.g., conflicting
// read-modify-write on the same resource.
GRPC_FAILEDPRECONDITION,
// ABORTED indicates the operation was aborted, typically due to a
// concurrency issue like sequencer check failures, transaction aborts,
// etc.
//
// See litmus test above for deciding between FAILEDPRECONDITION,
// Aborted, and Unavailable.
GRPC_ABORTED,
// OUTOFRANGE means operation was attempted past the valid range.
// E.g., seeking or reading past end of file.
//
// Unlike INVALIDARGUMENT, this error indicates a problem that may
// be fixed if the system state changes. For example, a 32-bit file
// system will generate INVALIDARGUMENT if asked to read at an
// offset that is not in the range [0,2^32-1], but it will generate
// OUTOFRANGE if asked to read from an offset past the current
// file size.
//
// There is a fair bit of overlap between FAILEDPRECONDITION and
// OUTOFRANGE. We recommend using OUTOFRANGE (the more specific
// error) when it applies so that callers who are iterating through
// a space can easily look for an OUTOFRANGE error to detect when
// they are done.
GRPC_OUTOFRANGE,
// UNIMPLEMENTED indicates operation is not implemented or not
// supported/enabled in this service.
GRPC_UNIMPLEMENTED,
// INTERNAL errors. Means some invariants expected by underlying
// system has been broken. If you see one of these errors,
// something is very broken.
GRPC_INTERNAL,
// UNAVAILABLE indicates the service is currently unavailable.
// This is a most likely a transient condition and may be corrected
// by retrying with a backoff.
//
// See litmus test above for deciding between FAILEDPRECONDITION,
// ABORTED, and UNAVAILABLE.
GRPC_UNAVAILABLE,
// DATALOSS indicates unrecoverable data loss or corruption.
GRPC_DATALOSS,
// UNAUTHENTICATED indicates the request does not have valid
// authentication credentials for the operation.
GRPC_UNAUTHENTICATED,
GRPC_MAX,
};
// Get description of the error.
const char* GrpcStatusToString(GrpcStatus);
// Convert between error code and grpc status with similar semantics
GrpcStatus ErrorCodeToGrpcStatus(int error_code);
int GrpcStatusToErrorCode(GrpcStatus grpc_status);
void PercentEncode(const std::string& str, std::string* str_out);
void PercentDecode(const std::string& str, std::string* str_out);
} // namespace brpc
#endif // BRPC_GRPC_H
+42
View File
@@ -0,0 +1,42 @@
// 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.
#ifndef BRPC_HEALTH_REPORTER_H
#define BRPC_HEALTH_REPORTER_H
#include "brpc/controller.h"
namespace brpc {
// For customizing /health page.
// Inherit this class and assign an instance to ServerOptions.health_reporter.
class HealthReporter {
public:
virtual ~HealthReporter() {}
// Get the http request from cntl->http_request() / cntl->request_attachment()
// and put the response in cntl->http_response() / cntl->response_attachment()
// Don't forget to call done->Run() at the end.
virtual void GenerateReport(Controller* cntl, google::protobuf::Closure* done) = 0;
};
} // namespace brpc
#endif // BRPC_HEALTH_REPORTER_H
+125
View File
@@ -0,0 +1,125 @@
// 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.
#ifndef BAIDU_RPC_HTTP2_H
#define BAIDU_RPC_HTTP2_H
#include "brpc/http_status_code.h"
// To baidu-rpc developers: This is a header included by user, don't depend
// on internal structures, use opaque pointers instead.
namespace brpc {
struct H2Settings {
// Construct with default values.
H2Settings();
// Returns true iff all options are valid.
bool IsValid(bool log_error = false) const;
// Allows the sender to inform the remote endpoint of the maximum size of
// the header compression table used to decode header blocks, in octets.
// The encoder can select any size equal to or less than this value by
// using signaling specific to the header compression format inside a
// header block (see [COMPRESSION]).
// Default: 4096
static const uint32_t DEFAULT_HEADER_TABLE_SIZE = 4096;
uint32_t header_table_size;
// Enable server push or not (Section 8.2).
// An endpoint MUST NOT send a PUSH_PROMISE frame if it receives this
// parameter set to a value of 0. An endpoint that has both set this
// parameter to 0 and had it acknowledged MUST treat the receipt of a
// PUSH_PROMISE frame as a connection error (Section 5.4.1) of type
// PROTOCOL_ERROR.
// Default: false (server push is disabled)
static const bool DEFAULT_ENABLE_PUSH = true;
bool enable_push;
// The maximum number of concurrent streams that the sender will allow.
// This limit is directional: it applies to the number of streams that the
// sender permits the receiver to create. It is recommended that this value
// be no smaller than 100, so as to not unnecessarily limit parallelism.
// 0 prevents the creation of new streams. However, this can also happen
// for any limit that is exhausted with active streams. Servers SHOULD only
// set a zero value for short durations; if a server does not wish to
// accept requests, closing the connection is more appropriate.
// Default: unlimited
uint32_t max_concurrent_streams;
// Sender's initial window size (in octets) for stream-level flow control.
// This setting affects the window size of all streams (see Section 6.9.2).
// Values above the maximum flow-control window size of 2^31-1 are treated
// as a connection error (Section 5.4.1) of type FLOW_CONTROL_ERROR
// Default: 256 * 1024
static const uint32_t DEFAULT_INITIAL_WINDOW_SIZE = 65535;
static const uint32_t MAX_WINDOW_SIZE = (1u << 31) - 1;
uint32_t stream_window_size;
// Initial window size for connection-level flow control.
// Default: 1024 * 1024
// Setting to zero stops printing this field.
uint32_t connection_window_size;
// Size of the largest frame payload that the sender is willing to receive,
// in octets. The value advertised by an endpoint MUST be between 16384 and
// 16777215, inclusive. Values outside this range are treated as a
// connection error(Section 5.4.1) of type PROTOCOL_ERROR.
// Default: 16384
static const uint32_t DEFAULT_MAX_FRAME_SIZE = 16384;
static const uint32_t MAX_OF_MAX_FRAME_SIZE = 16777215;
uint32_t max_frame_size;
// This advisory setting informs a peer of the maximum size of header list
// that the sender is prepared to accept, in octets. The value is based on
// the uncompressed size of header fields, including the length of the name
// and value in octets plus an overhead of 32 octets for each header field.
// For any given request, a lower limit than what is advertised MAY be
// enforced.
// Default: unlimited.
uint32_t max_header_list_size;
};
std::ostream& operator<<(std::ostream& os, const H2Settings& s);
enum H2Error {
H2_NO_ERROR = 0x0, // Graceful shutdown
H2_PROTOCOL_ERROR = 0x1, // Protocol error detected
H2_INTERNAL_ERROR = 0x2, // Implementation fault
H2_FLOW_CONTROL_ERROR = 0x3, // Flow-control limits exceeded
H2_SETTINGS_TIMEOUT = 0x4, // Settings not acknowledged
H2_STREAM_CLOSED_ERROR = 0x5, // Frame received for closed stream
H2_FRAME_SIZE_ERROR = 0x6, // Frame size incorrect
H2_REFUSED_STREAM = 0x7, // Stream not processed
H2_CANCEL = 0x8, // Stream cancelled
H2_COMPRESSION_ERROR = 0x9, // Compression state not updated
H2_CONNECT_ERROR = 0xa, // TCP connection error for CONNECT method
H2_ENHANCE_YOUR_CALM = 0xb, // Processing capacity exceeded
H2_INADEQUATE_SECURITY = 0xc, // Negotiated TLS parameters not acceptable
H2_HTTP_1_1_REQUIRED = 0xd, // Use HTTP/1.1 for the request
};
// Get description of the error.
const char* H2ErrorToString(H2Error e);
// Convert the error to status code with similar semantics
int H2ErrorToStatusCode(H2Error e);
} // namespace brpc
#endif // BAIDU_RPC_HTTP2_H
+166
View File
@@ -0,0 +1,166 @@
// 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.
#ifndef BRPC_HTTP_HEADER_H
#define BRPC_HTTP_HEADER_H
#include "butil/strings/string_piece.h" // StringPiece
#include "butil/containers/case_ignored_flat_map.h"
#include "brpc/uri.h" // URI
#include "brpc/http_method.h" // HttpMethod
#include "brpc/http_status_code.h"
#include "brpc/http2.h"
// To rpc developers: DON'T put impl. details here, use opaque pointers instead.
namespace brpc {
class InputMessageBase;
namespace policy {
void ProcessHttpRequest(InputMessageBase *msg);
class H2StreamContext;
}
// Non-body part of a HTTP message.
class HttpHeader {
public:
typedef butil::CaseIgnoredFlatMap<std::string> HeaderMap;
typedef HeaderMap::const_iterator HeaderIterator;
HttpHeader();
// Exchange internal fields with another HttpHeader.
void Swap(HttpHeader &rhs);
// Reset internal fields as if they're just default-constructed.
void Clear();
// Get http version, 1.1 by default.
int major_version() const { return _version.first; }
int minor_version() const { return _version.second; }
// Change the http version
void set_version(int http_major, int http_minor)
{ _version = std::make_pair(http_major, http_minor); }
// True if version of http is earlier than 1.1
bool before_http_1_1() const
{ return (major_version() * 10000 + minor_version()) <= 10000; }
// True if the message is from HTTP2.
bool is_http2() const { return major_version() == 2; }
// Get/set "Content-Type". Notice that you can't get "Content-Type"
// via GetHeader().
// possible values: "text/plain", "application/json" ...
const std::string& content_type() const { return _content_type; }
void set_content_type(const std::string& type) { _content_type = type; }
void set_content_type(const char* type) { _content_type = type; }
std::string& mutable_content_type() { return _content_type; }
// Get value of a header which is case-insensitive according to:
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
// Namely, GetHeader("log-id"), GetHeader("Log-Id"), GetHeader("LOG-ID")
// point to the same value.
// Return pointer to the value, NULL on not found.
// NOTE: Not work for "Content-Type", call content_type() instead.
const std::string* GetHeader(const char* key) const
{ return _headers.seek(key); }
const std::string* GetHeader(const std::string& key) const
{ return _headers.seek(key); }
// Set value of a header.
// NOTE: Not work for "Content-Type", call set_content_type() instead.
void SetHeader(const std::string& key, const std::string& value)
{ GetOrAddHeader(key) = value; }
// Remove a header.
void RemoveHeader(const char* key) { _headers.erase(key); }
void RemoveHeader(const std::string& key) { _headers.erase(key); }
// Append value to a header. If the header already exists, separate
// old value and new value with comma(,) according to:
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
void AppendHeader(const std::string& key, const butil::StringPiece& value);
// Get header iterators which are invalidated after calling AppendHeader()
HeaderIterator HeaderBegin() const { return _headers.begin(); }
HeaderIterator HeaderEnd() const { return _headers.end(); }
// #headers
size_t HeaderCount() const { return _headers.size(); }
// Get the URI object, check src/brpc/uri.h for details.
const URI& uri() const { return _uri; }
URI& uri() { return _uri; }
// Get/set http method.
HttpMethod method() const { return _method; }
void set_method(const HttpMethod method) { _method = method; }
// Get/set status-code and reason-phrase. Notice that the const char*
// returned by reason_phrase() will be invalidated after next call to
// set_status_code().
int status_code() const { return _status_code; }
const char* reason_phrase() const;
void set_status_code(int status_code);
// The URL path removed with matched prefix.
// NOTE: always normalized and NOT started with /.
//
// Accessing HttpService.Echo
// [URL] [unresolved_path]
// "/HttpService/Echo" ""
// "/HttpService/Echo/Foo" "Foo"
// "/HttpService/Echo/Foo/Bar" "Foo/Bar"
// "/HttpService//Echo///Foo//" "Foo"
//
// Accessing FileService.default_method:
// [URL] [unresolved_path]
// "/FileService" ""
// "/FileService/123.txt" "123.txt"
// "/FileService/mydir/123.txt" "mydir/123.txt"
// "/FileService//mydir///123.txt//" "mydir/123.txt"
const std::string& unresolved_path() const { return _unresolved_path; }
private:
friend class HttpMessage;
friend class HttpMessageSerializer;
friend class policy::H2StreamContext;
friend void policy::ProcessHttpRequest(InputMessageBase *msg);
std::string& GetOrAddHeader(const std::string& key) {
if (!_headers.initialized()) {
_headers.init(29);
}
return _headers[key];
}
HeaderMap _headers;
URI _uri;
int _status_code;
HttpMethod _method;
std::string _content_type;
std::string _unresolved_path;
std::pair<int, int> _version;
};
const HttpHeader& DefaultHttpHeader();
} // namespace brpc
#endif //BRPC_HTTP_HEADER_H
+63
View File
@@ -0,0 +1,63 @@
// 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.
#ifndef BRPC_HTTP_METHOD_H
#define BRPC_HTTP_METHOD_H
namespace brpc {
enum HttpMethod {
HTTP_METHOD_DELETE = 0,
HTTP_METHOD_GET = 1,
HTTP_METHOD_HEAD = 2,
HTTP_METHOD_POST = 3,
HTTP_METHOD_PUT = 4,
HTTP_METHOD_CONNECT = 5,
HTTP_METHOD_OPTIONS = 6,
HTTP_METHOD_TRACE = 7,
HTTP_METHOD_COPY = 8,
HTTP_METHOD_LOCK = 9,
HTTP_METHOD_MKCOL = 10,
HTTP_METHOD_MOVE = 11,
HTTP_METHOD_PROPFIND = 12,
HTTP_METHOD_PROPPATCH = 13,
HTTP_METHOD_SEARCH = 14,
HTTP_METHOD_UNLOCK = 15,
HTTP_METHOD_REPORT = 16,
HTTP_METHOD_MKACTIVITY = 17,
HTTP_METHOD_CHECKOUT = 18,
HTTP_METHOD_MERGE = 19,
HTTP_METHOD_MSEARCH = 20, // M-SEARCH
HTTP_METHOD_NOTIFY = 21,
HTTP_METHOD_SUBSCRIBE = 22,
HTTP_METHOD_UNSUBSCRIBE = 23,
HTTP_METHOD_PATCH = 24,
HTTP_METHOD_PURGE = 25,
HTTP_METHOD_MKCALENDAR = 26
};
// Returns literal description of `http_method'. "UNKNOWN" on not found.
const char *HttpMethod2Str(HttpMethod http_method);
// Convert case-insensitive `method_str' to enum HttpMethod.
// Returns true on success.
bool Str2HttpMethod(const char* method_str, HttpMethod* method);
} // namespace brpc
#endif //BRPC_HTTP_METHOD_H
+683
View File
@@ -0,0 +1,683 @@
// 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.
#ifndef BRPC_HTTP_STATUS_CODE_H
#define BRPC_HTTP_STATUS_CODE_H
namespace brpc {
// Read the description of a status code carefully before using it
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
// Status-Code =
// "100" ; Section 10.1.1: Continue
// | "101" ; Section 10.1.2: Switching Protocols
// | "200" ; Section 10.2.1: OK
// | "201" ; Section 10.2.2: Created
// | "202" ; Section 10.2.3: Accepted
// | "203" ; Section 10.2.4: Non-Authoritative Information
// | "204" ; Section 10.2.5: No Content
// | "205" ; Section 10.2.6: Reset Content
// | "206" ; Section 10.2.7: Partial Content
// | "300" ; Section 10.3.1: Multiple Choices
// | "301" ; Section 10.3.2: Moved Permanently
// | "302" ; Section 10.3.3: Found
// | "303" ; Section 10.3.4: See Other
// | "304" ; Section 10.3.5: Not Modified
// | "305" ; Section 10.3.6: Use Proxy
// | "307" ; Section 10.3.8: Temporary Redirect
// | "400" ; Section 10.4.1: Bad Request
// | "401" ; Section 10.4.2: Unauthorized
// | "402" ; Section 10.4.3: Payment Required
// | "403" ; Section 10.4.4: Forbidden
// | "404" ; Section 10.4.5: Not Found
// | "405" ; Section 10.4.6: Method Not Allowed
// | "406" ; Section 10.4.7: Not Acceptable
// | "407" ; Section 10.4.8: Proxy Authentication Required
// | "408" ; Section 10.4.9: Request Time-out
// | "409" ; Section 10.4.10: Conflict
// | "410" ; Section 10.4.11: Gone
// | "411" ; Section 10.4.12: Length Required
// | "412" ; Section 10.4.13: Precondition Failed
// | "413" ; Section 10.4.14: Request Entity Too Large
// | "414" ; Section 10.4.15: Request-URI Too Large
// | "415" ; Section 10.4.16: Unsupported Media Type
// | "416" ; Section 10.4.17: Requested range not satisfiable
// | "417" ; Section 10.4.18: Expectation Failed
// | "500" ; Section 10.5.1: Internal Server Error
// | "501" ; Section 10.5.2: Not Implemented
// | "502" ; Section 10.5.3: Bad Gateway
// | "503" ; Section 10.5.4: Service Unavailable
// | "504" ; Section 10.5.5: Gateway Time-out
// | "505" ; Section 10.5.6: HTTP Version not supported
// | extension-code
// Return the reason phrase of a given status_code.
// "Unknown status code (|status_code|)" will be returned if the status_code is
// unknown
// This function is thread-safe and NULL is never supposed to be returned
//
// NOTICE: the memory referenced by the pointer returned before might be reused
// when this function is called again, so please DON'T try to cache the return
// value into a container. Directly copy the memory instead.
const char *HttpReasonPhrase(int status_code);
// Convert brpc error code to related status code.
int ErrorCodeToStatusCode(int error_code);
// Informational 1xx
// This class of status code indicates a provisional response, consisting
// only of the Status-Line and optional headers, and is terminated by an
// empty line. There are no required headers for this class of status code.
// Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT
// send a 1xx response to an HTTP/1.0 client except under experimental
// conditions.
//
// A client MUST be prepared to accept one or more 1xx status responses
// prior to a regular response, even if the client does not expect a 100
// (Continue) status message. Unexpected 1xx status responses MAY be
// ignored by a user agent.
//
// Proxies MUST forward 1xx responses, unless the connection between the
// proxy and its client has been closed, or unless the proxy itself
// requested the generation of the 1xx response. (For example, if a
//
// proxy adds a "Expect: 100-continue" field when it forwards a request;
// then it need not forward the corresponding 100 (Continue) response(s).)
// 100 Continue
//
// The client SHOULD continue with its request. This interim response is
// used to inform the client that the initial part of the request has been
// received and has not yet been rejected by the server. The client SHOULD
// continue by sending the remainder of the request or, if the request has
// already been completed, ignore this response. The server MUST send a
// final response after the request has been completed.
//
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3 for
// detailed discussion of the use and handling of this status code.
static const int HTTP_STATUS_CONTINUE = 100;
// 101 Switching Protocols
//
// The server understands and is willing to comply with the client's
// request, via the Upgrade message header field (section 14.42), for a
// change in the application protocol being used on this connection. The
// server will switch protocols to those defined by the response's Upgrade
// header field immediately after the empty line which terminates the 101
// response.
//
// The protocol SHOULD be switched only when it is advantageous to do so.
// For example, switching to a newer version of HTTP is advantageous over
// older versions, and switching to a real-time, synchronous protocol might
// be advantageous when delivering resources that use such features.
static const int HTTP_STATUS_SWITCHING_PROTOCOLS = 101;
// Successful 2xx
// This class of status code indicates that the client's request was
// successfully received, understood, and accepted.
// 200 OK
//
// The request has succeeded. The information returned with the response is
// dependent on the method used in the request, for example:
// - GET an entity corresponding to the requested resource is sent in the
// response.
// - HEAD the entity-header fields corresponding to the requested resource
// are sent in the response without any message-body.
// - POST an entity describing or containing the result of the action;
// - TRACE an entity containing the request message as received by the end
// server.
static const int HTTP_STATUS_OK = 200;
// 201 Created
//
// The request has been fulfilled and resulted in a new resource being
// created. The newly created resource can be referenced by the URI(s)
// returned in the entity of the response, with the most specific URI for
// the resource given by a Location header field. The response SHOULD
// include an entity containing a list of resource characteristics and
// location(s) from which the user or user agent can choose the one most
// appropriate. The entity format is specified by the media type given in
// the Content-Type header field. The origin server MUST create the resource
// before returning the 201 status code. If the action cannot be carried out
// immediately, the server SHOULD respond with 202 (Accepted) response
// instead.
//
// A 201 response MAY contain an ETag response header field indicating the
// current value of the entity tag for the requested variant just created;
// see section 14.19
// (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19)
static const int HTTP_STATUS_CREATED = 201;
// 202 Accepted
//
// The request has been accepted for processing, but the processing has not
// been completed. The request might or might not eventually be acted upon;
// as it might be disallowed when processing actually takes place. There is
// no facility for re-sending a status code from an asynchronous operation
// such as this.
//
// The 202 response is intentionally non-committal. Its purpose is to allow
// a server to accept a request for some other process (perhaps a
// batch-oriented process that is only run once per day) without requiring
// that the user agent's connection to the server persist until the process
// is completed. The entity returned with this response SHOULD include an
// indication of the request's current status and either a pointer to a
// status monitor or some estimate of when the user can expect the request
// to be fulfilled.
static const int HTTP_STATUS_ACCEPTED = 202;
// 203 Non-Authoritative Information
//
// The returned metainformation in the entity-header is not the definitive
// set as available from the origin server, but is gathered from a local or
// a third-party copy. The set presented MAY be a subset or superset of the
// original version. For example, including local annotation information
// about the resource might result in a superset of the metainformation
// known by the origin server. Use of this response code is not required and
// is only appropriate when the response would otherwise be 200 (OK).
static const int HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION = 203;
// 204 No Content
//
// The server has fulfilled the request but does not need to return an
// entity-body, and might want to return updated metainformation. The
// response MAY include new or updated metainformation in the form of
// entity-headers, which if present SHOULD be associated with the requested
// variant.
//
// If the client is a user agent, it SHOULD NOT change its document view
// from that which caused the request to be sent. This response is primarily
// intended to allow input for actions to take place without causing a
// change to the user agent's active document view, although any new or
// updated metainformation SHOULD be applied to the document currently in
// the user agent's active view.
//
// The 204 response MUST NOT include a message-body, and thus is always
// terminated by the first empty line after the header fields.
static const int HTTP_STATUS_NO_CONTENT = 204;
// 205 Reset Content
//
// The server has fulfilled the request and the user agent SHOULD reset the
// document view which caused the request to be sent. This response is
// primarily intended to allow input for actions to take place via user
// input, followed by a clearing of the form in which the input is given so
// that the user can easily initiate another input action. The response
// MUST NOT include an entity.
static const int HTTP_STATUS_RESET_CONTENT = 205;
// 206 Partial Content
//
// The server has fulfilled the partial GET request for the resource. The
// request MUST have included a Range header field (section 14.35
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35)
// indicating the desired range, and MAY have included an If-Range header
// field (section 14.27) to make the request conditional.
//
// The response MUST include the following header fields:
// - Either a Content-Range header field (section 14.16
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16)
// indicating the range included with this response, or a
// multipart/byteranges Content-Type including Content-Range fields for
// each part. If a Content-Length header field is present in the
// response, its value MUST match the actual number of OCTETs
// transmitted in the message-body.
// - Date
// - ETag and/or Content-Location, if the header would have been sent
// in a 200 response to the same request
// - Expires, Cache-Control, and/or Vary, if the field-value might
// differ from that sent in any previous response for the same
// variant
//
// If the 206 response is the result of an If-Range request that used a
// strong cache validator (see section 13.3.3
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.3),
// the response SHOULD NOT include other entity-headers. If the response is
// the result of an If-Range request that used a weak validator, the
// response MUST NOT include other entity-headers; this prevents
// inconsistencies between cached entity-bodies and updated headers.
// Otherwise, the response MUST include all of the entity-headers that would
// have been returned with a 200 (OK) response to the same request.
//
// A cache MUST NOT combine a 206 response with other previously cached
// content if the ETag or Last-Modified headers do not match exactly, see
// 13.5.4 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.4)
//
// A cache that does not support the Range and Content-Range headers MUST
// NOT cache 206 (Partial) responses.
static const int HTTP_STATUS_PARTIAL_CONTENT = 206;
// Redirection 3xx
// This class of status code indicates that further action needs to be
// taken by the user agent in order to fulfill the request. The action
// required MAY be carried out by the user agent without interaction with
// the user if and only if the method used in the second request is GET or
// HEAD. A client SHOULD detect infinite redirection loops, since such
// loops generate network traffic for each redirection.
// 300 Multiple Choices
// The requested resource corresponds to any one of a set of
// representations, each with its own specific location, and agent-driven
// negotiation information
// (http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html#sec12.2)
// is being provided so that the user (or user agent) can select a preferred
// representation and redirect its request to that location.
//
// Unless it was a HEAD request, the response SHOULD include an entity
// containing a list of resource characteristics and location(s) from which
// the user or user agent can choose the one most appropriate. The entity
// format is specified by the media type given in the Content- Type header
// field. Depending upon the format and the capabilities of
//
// the user agent, selection of the most appropriate choice MAY be performed
// automatically. However, this specification does not define any standard
// for such automatic selection.
//
// If the server has a preferred choice of representation, it SHOULD include
// the specific URI for that representation in the Location field; user
// agents MAY use the Location field value for automatic redirection. This
// response is cacheable unless indicated otherwise.
static const int HTTP_STATUS_MULTIPLE_CHOICES = 300;
// 301 Moved Permanently
//
// The requested resource has been assigned a new permanent URI and any
// future references to this resource SHOULD use one of the returned URIs.
// Clients with link editing capabilities ought to automatically re-link
// references to the Request-URI to one or more of the new references
// returned by the server, where possible. This response is cacheable
// unless indicated otherwise.
//
// The new permanent URI SHOULD be given by the Location field in the
// response. Unless the request method was HEAD, the entity of the response
// SHOULD contain a short hypertext note with a hyperlink to the new
// URI(s).
//
// If the 301 status code is received in response to a request other than
// GET or HEAD, the user agent MUST NOT automatically redirect the request
// unless it can be confirmed by the user, since this might change the
// conditions under which the request was issued.
static const int HTTP_STATUS_MOVE_PERMANENTLY = 301;
// 302 Found
//
// The requested resource resides temporarily under a different URI. Since
// the redirection might be altered on occasion, the client SHOULD continue
// to use the Request-URI for future requests. This response is only
// cacheable if indicated by a Cache-Control or Expires header field.
//
// The temporary URI SHOULD be given by the Location field in the response.
// Unless the request method was HEAD, the entity of the response SHOULD
// contain a short hypertext note with a hyperlink to the new URI(s).
//
// If the 302 status code is received in response to a request other than
// GET or HEAD, the user agent MUST NOT automatically redirect the request
// unless it can be confirmed by the user, since this might change the
// conditions under which the request was issued.
static const int HTTP_STATUS_FOUND = 302;
// 303 See Other
//
// The response to the request can be found under a different URI and
// SHOULD be retrieved using a GET method on that resource. This method
// exists primarily to allow the output of a POST-activated script to
// redirect the user agent to a selected resource. The new URI is not a
// substitute reference for the originally requested resource. The 303
// response MUST NOT be cached, but the response to the second (redirected)
// request might be cacheable.
//
// The different URI SHOULD be given by the Location field in the response.
// Unless the request method was HEAD, the entity of the response SHOULD
// contain a short hypertext note with a hyperlink to the new URI(s).
static const int HTTP_STATUS_SEE_OTHER = 303;
// 304 Not Modified
//
// If the client has performed a conditional GET request and access is
// allowed, but the document has not been modified, the server SHOULD
// respond with this status code. The 304 response MUST NOT contain a
// message-body, and thus is always terminated by the first empty line
// after the header fields.
//
// The response MUST include the following header fields:
// - Date, unless its omission is required by section 14.18.1
// (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18.1)
// If a clockless origin server obeys these rules, and proxies and clients
// add their own Date to any response received without one (as already
// specified by [RFC 2068], section 14.19
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19), caches
// will operate correctly.
static const int HTTP_STATUS_NOT_MODIFIED = 304;
// 305 Use Proxy
//
// The requested resource MUST be accessed through the proxy given by the
// Location field. The Location field gives the URI of the proxy. The
// recipient is expected to repeat this single request via the proxy. 305
// responses MUST only be generated by origin servers.
//
// Note: RFC 2068 was not clear that 305 was intended to redirect a
// single request, and to be generated by origin servers only.
// Not observing these limitations has significant security
// consequences.
static const int HTTP_STATUS_USE_PROXY = 305;
// 307 Temporary Redirect
//
// The requested resource resides temporarily under a different URI. Since
// the redirection MAY be altered on occasion, the client SHOULD continue to
// use the Request-URI for future requests. This response is only cacheable
// if indicated by a Cache-Control or Expires header field.
//
// The temporary URI SHOULD be given by the Location field in the response.
// Unless the request method was HEAD, the entity of the response SHOULD
// contain a short hypertext note with a hyperlink to the new URI(s) , since
// many pre-HTTP/1.1 user agents do not understand the 307 status.
// Therefore, the note SHOULD contain the information necessary for a user
// to repeat the original request on the new URI.
//
// If the 307 status code is received in response to a request other than
// GET or HEAD, the user agent MUST NOT automatically redirect the request
// unless it can be confirmed by the user, since this might change the
// conditions under which the request was issued.
static const int HTTP_STATUS_TEMPORARY_REDIRECT = 307;
// Client Error 4xx
// The 4xx class of status code is intended for cases in which the client
// seems to have erred. Except when responding to a HEAD request, the
// server SHOULD include an entity containing an explanation of the error
// situation, and whether it is a temporary or permanent condition. These
// status codes are applicable to any request method. User agents SHOULD
// display any included entity to the user.
//
// If the client is sending data, a server implementation using TCP SHOULD
// be careful to ensure that the client acknowledges receipt of the
// packet(s) containing the response, before the server closes the input
// connection. If the client continues sending data to the server after the
// close, the server's TCP stack will send a reset packet to the client;
// which may erase the client's unacknowledged input buffers before they
// can be read and interpreted by the HTTP application.
// 400 Bad Request
// The request could not be understood by the server due to malformed
// syntax. The client SHOULD NOT repeat the request without modifications.
static const int HTTP_STATUS_BAD_REQUEST = 400;
// 401 Unauthorized
//
// The request requires user authentication. The response MUST include a
// WWW-Authenticate header field containing a challenge
// applicable to the requested resource. The client MAY repeat the request
// with a suitable Authorization header field. If the request
// already included Authorization credentials, then the 401 response
// indicates that authorization has been refused for those credentials. If
// the 401 response contains the same challenge as the prior response, and
// the user agent has already attempted authentication at least once, then
// the user SHOULD be presented the entity that was given in the response;
// since that entity might include relevant diagnostic information. HTTP
// access authentication is explained in "HTTP Authentication: Basic and
// Digest Access Authentication" (http://www.ietf.org/rfc/rfc2617.txt)
static const int HTTP_STATUS_UNAUTHORIZED = 401;
// 402 Payment Required
//
// This code is reserved for future use.
static const int HTTP_STATUS_PAYMENT_REQUIRED = 402;
// 403 Forbidden
//
// The server understood the request, but is refusing to fulfill it.
// Authorization will not help and the request SHOULD NOT be repeated. If
// the request method was not HEAD and the server wishes to make public why
// the request has not been fulfilled, it SHOULD describe the reason for
// the refusal in the entity. If the server does not wish to make this
// information available to the client, the status code 404 (Not Found) can
// be used instead.
static const int HTTP_STATUS_FORBIDDEN = 403;
// 404 Not Found
//
// The server has not found anything matching the Request-URI. No indication
// is given of whether the condition is temporary or permanent. The 410
// (Gone) status code SHOULD be used if the server knows, through some
// internally configurable mechanism, that an old resource is permanently
// unavailable and has no forwarding address. This status code is commonly
// used when the server does not wish to reveal exactly why the request has
// been refused, or when no other response is applicable.
static const int HTTP_STATUS_NOT_FOUND = 404;
// 405 Method Not Allowed
//
// The method specified in the Request-Line is not allowed for the resource
// identified by the Request-URI. The response MUST include an Allow header
// containing a list of valid methods for the requested resource.
static const int HTTP_STATUS_METHOD_NOT_ALLOWED = 405;
// 406 Not Acceptable
//
// The resource identified by the request is only capable of generating
// response entities which have content characteristics not acceptable
// according to the accept headers sent in the request.
//
// Unless it was a HEAD request, the response SHOULD include an entity
// containing a list of available entity characteristics and location(s)
// from which the user or user agent can choose the one most appropriate.
// The entity format is specified by the media type given in the
// Content-Type header field. Depending upon the format and the
// capabilities of the user agent, selection of the most appropriate choice
// MAY be performed automatically. However, this specification does not
// define any standard for such automatic selection.
static const int HTTP_STATUS_NOT_ACCEPTABLE = 406;
// 407 Proxy Authentication Required
// This code is similar to 401 (Unauthorized), but indicates that the client
// must first authenticate itself with the proxy. The proxy MUST return a
// Proxy-Authenticate header field containing a challenge
// applicable to the proxy for the requested resource. The client MAY repeat
// the request with a suitable Proxy-Authorization header field.
// HTTP access authentication is explained in "HTTP Authentication:
// Basic and Digest Access Authentication"
static const int HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED = 407;
// 408 Request Timeout
//
// The client did not produce a request within the time that the server was
// prepared to wait. The client MAY repeat the request without modifications
// at any later time.
static const int HTTP_STATUS_REQUEST_TIMEOUT = 408;
// 409 Conflict
//
// The request could not be completed due to a conflict with the current
// state of the resource. This code is only allowed in situations where it
// is expected that the user might be able to resolve the conflict and
// resubmit the request. The response body SHOULD include enough information
// for the user to recognize the source of the conflict. Ideally, the
// response entity would include enough information for the user or user
// agent to fix the problem; however, that might not be possible and is not
// required.
//
// Conflicts are most likely to occur in response to a PUT request. For
// example, if versioning were being used and the entity being PUT included
// changes to a resource which conflict with those made by an earlier
// (third-party) request, the server might use the 409 response to indicate
// that it can't complete the request. In this case, the response entity
// would likely contain a list of the differences between the two versions
// in a format defined by the response Content-Type.
static const int HTTP_STATUS_CONFLICT = 409;
// 410 Gone
//
// The requested resource is no longer available at the server and no
// forwarding address is known. This condition is expected to be considered
// permanent. Clients with link editing capabilities SHOULD delete
// references to the Request-URI after user approval. If the server does not
// know, or has no facility to determine, whether or not the condition is
// permanent, the status code 404 (Not Found) SHOULD be used instead. This
// response is cacheable unless indicated otherwise.
//
// The 410 response is primarily intended to assist the task of web
// maintenance by notifying the recipient that the resource is intentionally
// unavailable and that the server owners desire that remote links to that
// resource be removed. Such an event is common for limited-time;
// promotional services and for resources belonging to individuals no longer
// working at the server's site. It is not necessary to mark all permanently
// unavailable resources as "gone" or to keep the mark for any length of
// time -- that is left to the discretion of the server owner.
static const int HTTP_STATUS_GONE = 410;
// 411 Length Required
//
// The server refuses to accept the request without a defined
// Content-Length. The client MAY repeat the request if it adds a valid
// Content-Length header field containing the length of the message-body in
// the request message.
static const int HTTP_STATUS_LENGTH_REQUIRED = 411;
// 412 Precondition Failed
//
// The precondition given in one or more of the request-header fields
// evaluated to false when it was tested on the server. This response code
// allows the client to place preconditions on the current resource
// metainformation (header field data) and thus prevent the requested method
// from being applied to a resource other than the one intended.
static const int HTTP_STATUS_PRECONDITION_FAILED = 412;
// 413 Request Entity Too Large
//
// The server is refusing to process a request because the request entity is
// larger than the server is willing or able to process. The server MAY
// close the connection to prevent the client from continuing the request.
//
// If the condition is temporary, the server SHOULD include a Retry-After
// header field to indicate that it is temporary and after what time the
// client MAY try again.
static const int HTTP_STATUS_REQUEST_ENTITY_TOO_LARGE = 413;
// 414 Request-URI Too Long
//
// The server is refusing to service the request because the Request-URI is
// longer than the server is willing to interpret. This rare condition is
// only likely to occur when a client has improperly converted a POST
// request to a GET request with long query information, when the client has
// descended into a URI "black hole" of redirection (e.g., a redirected URI
// prefix that points to a suffix of itself), or when the server is under
// attack by a client attempting to exploit security holes present in some
// servers using fixed-length buffers for reading or manipulating the
// Request-URI.
static const int HTTP_STATUS_REQUEST_URI_TOO_LARG = 414;
// 415 Unsupported Media Type
//
// The server is refusing to service the request because the entity of the
// request is in a format not supported by the requested resource for the
// requested method.
static const int HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE = 415;
// 416 Requested Range Not Satisfiable
//
// A server SHOULD return a response with this status code if a request
// included a Range request-header field, and none of the
// range-specifier values in this field overlap the current extent of the
// selected resource, and the request did not include an If-Range
// request-header field. (For byte-ranges, this means that the
// first-byte-pos of all of the byte-range-spec values were greater than the
// current length of the selected resource.)
//
// When this status code is returned for a byte-range request, the response
// SHOULD include a Content-Range entity-header field specifying the current
// length of the selected resource. This response MUST
// NOT use the multipart/byteranges content-type.
static const int HTTP_STATUS_REQUEST_RANGE_NOT_SATISFIABLE = 416;
// 417 Expectation Failed
//
// The expectation given in an Expect request-header field (see section
// 14.20 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20)
// could not be met by this server, or, if the server is a proxy, the
// server has unambiguous evidence that the request could not be met by the
// next-hop server.
static const int HTTP_STATUS_EXPECTATION_FAILED = 417;
// Server Error 5xx
//
// Response status codes beginning with the digit "5" indicate cases in
// which the server is aware that it has erred or is incapable of performing
// the request. Except when responding to a HEAD request, the server SHOULD
// include an entity containing an explanation of the error situation, and
// whether it is a temporary or permanent condition. User agents SHOULD
// display any included entity to the user. These response codes are
// applicable to any request method.
// 500 Internal Server Error
//
// The server encountered an unexpected condition which prevented it from
// fulfilling the request.
static const int HTTP_STATUS_INTERNAL_SERVER_ERROR = 500;
// 501 Not Implemented
//
// The server does not support the functionality required to fulfill the
// request. This is the appropriate response when the server does not
// recognize the request method and is not capable of supporting it for any
// resource.
static const int HTTP_STATUS_NOT_IMPLEMENTED = 501;
// 502 Bad Gateway
//
// The server, while acting as a gateway or proxy, received an invalid
// response from the upstream server it accessed in attempting to fulfill
// the request.
static const int HTTP_STATUS_BAD_GATEWAY = 502;
// 503 Service Unavailable
//
// The server is currently unable to handle the request due to a temporary
// overloading or maintenance of the server. The implication is that this is
// a temporary condition which will be alleviated after some delay. If
// known, the length of the delay MAY be indicated in a Retry-After header.
// If no Retry-After is given, the client SHOULD handle the response as it
// would for a 500 response.
static const int HTTP_STATUS_SERVICE_UNAVAILABLE = 503;
// 504 Gateway Timeout
//
// The server, while acting as a gateway or proxy, did not receive a timely
// response from the upstream server specified by the URI (e.g. HTTP, FTP;
// LDAP) or some other auxiliary server (e.g. DNS) it needed to access in
// attempting to complete the request.
static const int HTTP_STATUS_GATEWAY_TIMEOUT = 504;
// 505 HTTP Version Not Supported
//
// The server does not support, or refuses to support, the HTTP protocol
// version that was used in the request message. The server is indicating
// that it is unable or unwilling to complete the request using the same
// major version as the client, as described in section 3.1, other than with
// this error message. The response SHOULD contain an entity describing why
// that version is not supported and what other protocols are supported by
// that server.
static const int HTTP_STATUS_VERSION_NOT_SUPPORTED = 505;
} // namespace brpc
#endif //BRPC_HTTP_STATUS_CODE_H
+68
View File
@@ -0,0 +1,68 @@
// 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.
#ifndef BRPC_INPUT_MESSAGE_BASE_H
#define BRPC_INPUT_MESSAGE_BASE_H
#include "brpc/socket_id.h" // SocketId
#include "brpc/destroyable.h" // DestroyingPtr
namespace brpc {
// Messages returned by Parse handlers must extend this class
class InputMessageBase : public Destroyable {
protected:
// Implement this method to customize deletion of this message.
virtual void DestroyImpl() = 0;
public:
// Called to release the memory of this message instead of "delete"
void Destroy();
// Own the socket where this message is from.
Socket* ReleaseSocket();
// Get the socket where this message is from.
Socket* socket() const { return _socket.get(); }
// Arg of the InputMessageHandler which parses this message successfully.
const void* arg() const { return _arg; }
// [Internal]
int64_t received_us() const { return _received_us; }
int64_t base_real_us() const { return _base_real_us; }
protected:
virtual ~InputMessageBase();
private:
friend class InputMessenger;
friend void* ProcessInputMessage(void*);
friend class Stream;
int64_t _received_us;
int64_t _base_real_us;
SocketUniquePtr _socket;
void (*_process)(InputMessageBase* msg);
const void* _arg;
};
} // namespace brpc
#endif // BRPC_INPUT_MESSAGE_BASE_H
+164
View File
@@ -0,0 +1,164 @@
// 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.
#ifndef BRPC_INPUT_MESSENGER_H
#define BRPC_INPUT_MESSENGER_H
#include "butil/iobuf.h" // butil::IOBuf
#include "brpc/socket.h" // SocketId, SocketUser
#include "brpc/parse_result.h" // ParseResult
#include "brpc/input_message_base.h" // InputMessageBase
namespace brpc {
namespace rdma {
class RdmaEndpoint;
}
struct InputMessageHandler {
// The callback to cut a message from `source'.
// Returned message will be passed to process_request or process_response
// later and Destroy()-ed by them.
// Returns:
// MakeParseError(PARSE_ERROR_NOT_ENOUGH_DATA):
// `source' does not form a complete message yet.
// MakeParseError(PARSE_ERROR_TRY_OTHERS).
// `source' does not fit the protocol, the data should be tried by
// other protocols. If the data is definitely corrupted (e.g. magic
// header matches but other fields are wrong), pop corrupted part
// from `source' before returning.
// MakeMessage(InputMessageBase*):
// The message is parsed successfully and cut from `source'.
typedef ParseResult (*Parse)(butil::IOBuf* source, Socket *socket,
bool read_eof, const void *arg);
Parse parse;
// The callback to handle `msg' created by a successful parse().
// `msg' must be Destroy()-ed when the processing is done. To make sure
// Destroy() is always called, consider using DestroyingPtr<> defined in
// destroyable.h
// May be called in a different thread from parse().
typedef void (*Process)(InputMessageBase* msg);
Process process;
// The callback to verify authentication of this socket. Only called
// on the first message that a socket receives. Can be NULL when
// authentication is not needed or this is the client side.
// Returns true on successful authentication.
typedef bool (*Verify)(const InputMessageBase* msg);
Verify verify;
// An argument associated with the handler.
const void* arg;
// Name of this handler, must be string constant.
const char* name;
};
// Process messages from connections.
// `Message' corresponds to a client's request or a server's response.
class InputMessenger : public SocketUser {
friend class rdma::RdmaEndpoint;
public:
explicit InputMessenger(size_t capacity = 128);
~InputMessenger();
// [thread-safe] Must be called at least once before Start().
// `handler' contains user-supplied callbacks to cut off and
// process messages from connections.
// Returns 0 on success, -1 otherwise.
int AddHandler(const InputMessageHandler& handler);
// [thread-safe] Create a socket to process input messages.
int Create(const butil::EndPoint& remote_side,
time_t health_check_interval_s,
SocketId* id);
// Overwrite necessary fields in `base_options' and create a socket with
// the modified options.
int Create(SocketOptions base_options, SocketId* id);
// Returns the internal index of `InputMessageHandler' whose name=`name'
// Returns -1 when not found
int FindProtocolIndex(const char* name) const;
int FindProtocolIndex(ProtocolType type) const;
// Get name of the n-th handler
const char* NameOfProtocol(int n) const;
// Add a handler which doesn't belong to any registered protocol.
// Note: Invoking this method indicates that you are using Socket without
// Channel nor Server.
int AddNonProtocolHandler(const InputMessageHandler& handler);
protected:
// Load data from m->fd() into m->read_buf, cut off new messages and
// call callbacks.
static void OnNewMessages(Socket* m);
private:
class InputMessageClosure {
public:
InputMessageClosure() : _msg(NULL) { }
~InputMessageClosure();
InputMessageBase* release() {
InputMessageBase* m = _msg;
_msg = NULL;
return m;
}
void reset(InputMessageBase* m);
private:
InputMessageBase* _msg;
};
// Find a valid scissor from `handlers' to cut off `header' and `payload'
// from m->read_buf, save index of the scissor into `index'.
ParseResult CutInputMessage(Socket* m, size_t* index, bool read_eof);
// Process a new message just received in OnNewMessages
// Return value >= 0 means success
int ProcessNewMessage(
Socket* m, ssize_t bytes, bool read_eof,
const uint64_t received_us, const uint64_t base_realtime,
InputMessageClosure& last_msg);
// User-supplied scissors and handlers.
// the index of handler is exactly the same as the protocol
InputMessageHandler* _handlers;
// Max added protocol type
butil::atomic<int> _max_index;
bool _non_protocol;
size_t _capacity;
butil::Mutex _add_handler_mutex;
};
// Get the global InputMessenger at client-side.
BUTIL_FORCE_INLINE InputMessenger* get_client_side_messenger() {
extern InputMessenger* g_messenger;
return g_messenger;
}
InputMessenger* get_or_new_client_side_messenger();
} // namespace brpc
#endif // BRPC_INPUT_MESSENGER_H
+75
View File
@@ -0,0 +1,75 @@
// 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.
#ifndef BRPC_KVMAP_H
#define BRPC_KVMAP_H
#include "butil/containers/flat_map.h"
namespace brpc {
// Remember Key/Values in string
class KVMap {
public:
typedef butil::FlatMap<std::string, std::string> Map;
typedef Map::const_iterator Iterator;
KVMap() {}
// Exchange internal fields with another KVMap.
void Swap(KVMap &rhs) { _entries.swap(rhs._entries); }
// Reset internal fields as if they're just default-constructed.
void Clear() { _entries.clear(); }
// Get value of a key(case-sensitive)
// Return pointer to the value, NULL on not found.
const std::string* Get(const char* key) const { return _entries.seek(key); }
const std::string* Get(const std::string& key) const { return _entries.seek(key); }
// Set value of a key
void Set(const std::string& key, const std::string& value) { GetOrAdd(key) = value; }
void Set(const std::string& key, const char* value) { GetOrAdd(key) = value; }
// Convert other types to string as well
template <typename T>
void Set(const std::string& key, const T& value) { GetOrAdd(key) = std::to_string(value); }
// Remove a key
void Remove(const char* key) { _entries.erase(key); }
void Remove(const std::string& key) { _entries.erase(key); }
// Get iterators to iterate key/value
Iterator Begin() const { return _entries.begin(); }
Iterator End() const { return _entries.end(); }
// number of key/values
size_t Count() const { return _entries.size(); }
private:
std::string& GetOrAdd(const std::string& key) {
if (!_entries.initialized()) {
_entries.init(29);
}
return _entries[key];
}
Map _entries;
};
} // namespace brpc
#endif // BRPC_KVMAP_H
+190
View File
@@ -0,0 +1,190 @@
// 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.
#ifndef BRPC_LOAD_BALANCER_H
#define BRPC_LOAD_BALANCER_H
#include "bvar/passive_status.h"
#include "brpc/describable.h"
#include "brpc/destroyable.h"
#include "brpc/excluded_servers.h" // ExcludedServers
#include "brpc/shared_object.h" // SharedObject
#include "brpc/server_id.h" // ServerId
#include "brpc/extension.h" // Extension<T>
namespace brpc {
class Controller;
// Select a server from a set of servers (in form of ServerId).
class LoadBalancer : public NonConstDescribable, public Destroyable {
public:
struct SelectIn {
int64_t begin_time_us;
// Weight of different nodes could be changed.
bool changable_weights;
bool has_request_code;
uint64_t request_code;
const ExcludedServers* excluded;
};
struct SelectOut {
explicit SelectOut(SocketUniquePtr* ptr_in)
: ptr(ptr_in), need_feedback(false) {}
SocketUniquePtr* ptr;
bool need_feedback;
};
struct CallInfo {
// Exactly same with SelectIn.begin_time_us, may be different from
// controller->_begin_time_us which is beginning of the RPC.
int64_t begin_time_us;
// Remote side of the call.
SocketId server_id;
// A RPC may have multiple calls, this error may be different from
// controller->ErrorCode();
int error_code;
// The controller for the RPC. Should NOT be saved in Feedback()
// and used after the function.
const Controller* controller;
};
LoadBalancer() { }
// ====================================================================
// All methods must be thread-safe!
// Take a look at policy/round_robin_load_balancer.cpp to see how to
// make SelectServer() low contended by using DoublyBufferedData<>
// =====================================================================
// Add `server' into this balancer.
// Returns true on added.
virtual bool AddServer(const ServerId& server) = 0;
// Remove `server' from this balancer.
// Returns true iff the server was removed.
virtual bool RemoveServer(const ServerId& server) = 0;
// Add a list of `servers' into this balancer.
// Returns number of servers added.
virtual size_t AddServersInBatch(const std::vector<ServerId>& servers) = 0;
// Remove a list of `servers' from this balancer.
// Returns number of servers removed.
virtual size_t RemoveServersInBatch(const std::vector<ServerId>& servers) = 0;
// Select a server and address it into `out->ptr'.
// If Feedback() should be called when the RPC is done, set
// out->need_feedback to true.
// Returns 0 on success, errno otherwise.
virtual int SelectServer(const SelectIn& in, SelectOut* out) = 0;
// Feedback this balancer with CallInfo gathered before RPC finishes.
// This function is only called when corresponding SelectServer was
// successful and out->need_feedback was set to true.
virtual void Feedback(const CallInfo& /*info*/) { }
// Create/destroy an instance.
// Caller is responsible for Destroy() the instance after usage.
virtual LoadBalancer* New(const butil::StringPiece& params) const = 0;
protected:
virtual ~LoadBalancer() { }
};
DECLARE_bool(show_lb_in_vars);
DECLARE_int32(default_weight_of_wlb);
// A intrusively shareable load balancer created from name.
class SharedLoadBalancer : public SharedObject, public NonConstDescribable {
public:
SharedLoadBalancer();
~SharedLoadBalancer();
int Init(const char* lb_name);
int SelectServer(const LoadBalancer::SelectIn& in,
LoadBalancer::SelectOut* out) {
if (FLAGS_show_lb_in_vars && !_exposed) {
ExposeLB();
}
return _lb->SelectServer(in, out);
}
void Feedback(const LoadBalancer::CallInfo& info) { _lb->Feedback(info); }
bool AddServer(const ServerId& server) {
if (_lb->AddServer(server)) {
_weight_sum.fetch_add(1, butil::memory_order_relaxed);
return true;
}
return false;
}
bool RemoveServer(const ServerId& server) {
if (_lb->RemoveServer(server)) {
_weight_sum.fetch_sub(1, butil::memory_order_relaxed);
return true;
}
return false;
}
size_t AddServersInBatch(const std::vector<ServerId>& servers) {
size_t n = _lb->AddServersInBatch(servers);
if (n) {
_weight_sum.fetch_add(n, butil::memory_order_relaxed);
}
return n;
}
size_t RemoveServersInBatch(const std::vector<ServerId>& servers) {
size_t n = _lb->RemoveServersInBatch(servers);
if (n) {
_weight_sum.fetch_sub(n, butil::memory_order_relaxed);
}
return n;
}
virtual void Describe(std::ostream& os, const DescribeOptions&);
virtual int Weight() {
return _weight_sum.load(butil::memory_order_relaxed);
}
private:
static bool ParseParameters(const butil::StringPiece& lb_protocol,
std::string* lb_name,
butil::StringPiece* lb_params);
static void DescribeLB(std::ostream& os, void* arg);
void ExposeLB();
LoadBalancer* _lb;
butil::atomic<int> _weight_sum;
volatile bool _exposed;
butil::Mutex _st_mutex;
bvar::PassiveStatus<std::string> _st;
};
// For registering global instances.
inline Extension<const LoadBalancer>* LoadBalancerExtension() {
return Extension<const LoadBalancer>::instance();
}
} // namespace brpc
#endif // BRPC_LOAD_BALANCER_H
+31
View File
@@ -0,0 +1,31 @@
// 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.
#ifndef BRPC_LOG_H
#define BRPC_LOG_H
#include <inttypes.h> // PRId64 PRIu64
#include "bthread/errno.h"
#define RPC_VLOG_LEVEL 99
#define RPC_VLOG_IS_ON VLOG_IS_ON(RPC_VLOG_LEVEL)
#define RPC_VLOG VLOG(RPC_VLOG_LEVEL)
#define RPC_VPLOG VPLOG(RPC_VLOG_LEVEL)
#define RPC_VLOG_IF(cond) VLOG_IF(RPC_VLOG_LEVEL, (cond))
#define RPC_VPLOG_IF(cond) VPLOG_IF(RPC_VLOG_LEVEL, (cond))
#endif // BRPC_LOG_H
+246
View File
@@ -0,0 +1,246 @@
// 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.
#ifndef BRPC_MEMCACHE_H
#define BRPC_MEMCACHE_H
#include <string>
#include <google/protobuf/message.h>
#include "butil/iobuf.h"
#include "butil/strings/string_piece.h"
#include "brpc/proto_base.pb.h"
#include "brpc/pb_compat.h"
namespace brpc {
// Request to memcache.
// Notice that you can pipeline multiple operations in one request and sent
// them to memcached server together.
// Example:
// MemcacheRequest request;
// request.get("my_key1");
// request.get("my_key2");
// request.set("my_key3", "some_value", 0, 10);
// ...
// MemcacheResponse response;
// // 2 GET and 1 SET are sent to the server together.
// channel.CallMethod(&controller, &request, &response, NULL/*done*/);
class MemcacheRequest : public ::google::protobuf::Message {
public:
MemcacheRequest();
virtual ~MemcacheRequest();
MemcacheRequest(const MemcacheRequest& from);
inline MemcacheRequest& operator=(const MemcacheRequest& from) {
CopyFrom(from);
return *this;
}
void Swap(MemcacheRequest* other);
bool Get(const butil::StringPiece& key);
// If the cas_value(Data Version Check) is non-zero, the requested operation
// MUST only succeed if the item exists and has a cas_value identical to the
// provided value.
bool Set(const butil::StringPiece& key, const butil::StringPiece& value,
uint32_t flags, uint32_t exptime, uint64_t cas_value);
bool Add(const butil::StringPiece& key, const butil::StringPiece& value,
uint32_t flags, uint32_t exptime, uint64_t cas_value);
bool Replace(const butil::StringPiece& key, const butil::StringPiece& value,
uint32_t flags, uint32_t exptime, uint64_t cas_value);
bool Append(const butil::StringPiece& key, const butil::StringPiece& value,
uint32_t flags, uint32_t exptime, uint64_t cas_value);
bool Prepend(const butil::StringPiece& key, const butil::StringPiece& value,
uint32_t flags, uint32_t exptime, uint64_t cas_value);
bool Delete(const butil::StringPiece& key);
bool Flush(uint32_t timeout);
bool Increment(const butil::StringPiece& key, uint64_t delta,
uint64_t initial_value, uint32_t exptime);
bool Decrement(const butil::StringPiece& key, uint64_t delta,
uint64_t initial_value, uint32_t exptime);
bool Touch(const butil::StringPiece& key, uint32_t exptime);
bool Version();
int pipelined_count() const { return _pipelined_count; }
butil::IOBuf& raw_buffer() { return _buf; }
const butil::IOBuf& raw_buffer() const { return _buf; }
// Protobuf methods.
MemcacheRequest* New() const PB_319_OVERRIDE;
#if GOOGLE_PROTOBUF_VERSION >= 3006000
MemcacheRequest* New(::google::protobuf::Arena* arena) const override;
#endif
void CopyFrom(const ::google::protobuf::Message& from) PB_321_OVERRIDE;
void MergeFrom(const ::google::protobuf::Message& from) override;
void CopyFrom(const MemcacheRequest& from);
void MergeFrom(const MemcacheRequest& from);
void Clear() override;
bool IsInitialized() const override;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PB_310_OVERRIDE;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PB_310_OVERRIDE;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const PB_310_OVERRIDE;
int GetCachedSize() const override { return _cached_size_; }
static const ::google::protobuf::Descriptor* descriptor();
protected:
::google::protobuf::Metadata GetMetadata() const override;
private:
bool GetOrDelete(uint8_t command, const butil::StringPiece& key);
bool Counter(uint8_t command, const butil::StringPiece& key, uint64_t delta,
uint64_t initial_value, uint32_t exptime);
bool Store(uint8_t command, const butil::StringPiece& key,
const butil::StringPiece& value,
uint32_t flags, uint32_t exptime, uint64_t cas_value);
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const override;
int _pipelined_count;
butil::IOBuf _buf;
mutable int _cached_size_;
};
// Response from Memcache.
// Notice that a MemcacheResponse instance may contain multiple operations
// due to pipelining. You can call pop_xxx according to your calling sequence
// of operations in corresponding MemcacheRequest.
// Example:
// MemcacheResponse response;
// channel.CallMethod(&controller, &request, &response, NULL/*done*/);
// ...
// if (!response.PopGet(&my_value1, &flags1, &cas1)) {
// LOG(FATAL) << "Fail to pop GET: " << response.LastError();
// } else {
// // Use my_value1, flags1, cas1
// }
// if (!response.PopGet(&my_value2, &flags2, &cas2)) {
// LOG(FATAL) << "Fail to pop GET: " << response.LastError();
// } else {
// // Use my_value2, flags2, cas2
// }
// if (!response.PopSet(&cas3)) {
// LOG(FATAL) << "Fail to pop SET: " << response.LastError();
// } else {
// // the SET was successful.
// }
class MemcacheResponse : public ::google::protobuf::Message {
public:
// Definition of the valid response status numbers.
// See section 3.2 Response Status
enum Status {
STATUS_SUCCESS = 0x00,
STATUS_KEY_ENOENT = 0x01,
STATUS_KEY_EEXISTS = 0x02,
STATUS_E2BIG = 0x03,
STATUS_EINVAL = 0x04,
STATUS_NOT_STORED = 0x05,
STATUS_DELTA_BADVAL = 0x06,
STATUS_AUTH_ERROR = 0x20,
STATUS_AUTH_CONTINUE = 0x21,
STATUS_UNKNOWN_COMMAND = 0x81,
STATUS_ENOMEM = 0x82
};
MemcacheResponse();
virtual ~MemcacheResponse();
MemcacheResponse(const MemcacheResponse& from);
inline MemcacheResponse& operator=(const MemcacheResponse& from) {
CopyFrom(from);
return *this;
}
void Swap(MemcacheResponse* other);
const std::string& LastError() const { return _err; }
bool PopGet(butil::IOBuf* value, uint32_t* flags, uint64_t* cas_value);
bool PopGet(std::string* value, uint32_t* flags, uint64_t* cas_value);
bool PopSet(uint64_t* cas_value);
bool PopAdd(uint64_t* cas_value);
bool PopReplace(uint64_t* cas_value);
bool PopAppend(uint64_t* cas_value);
bool PopPrepend(uint64_t* cas_value);
bool PopDelete();
bool PopFlush();
bool PopIncrement(uint64_t* new_value, uint64_t* cas_value);
bool PopDecrement(uint64_t* new_value, uint64_t* cas_value);
bool PopTouch();
bool PopVersion(std::string* version);
butil::IOBuf& raw_buffer() { return _buf; }
const butil::IOBuf& raw_buffer() const { return _buf; }
static const char* status_str(Status);
// implements Message ----------------------------------------------
MemcacheResponse* New() const PB_319_OVERRIDE;
#if GOOGLE_PROTOBUF_VERSION >= 3006000
MemcacheResponse* New(::google::protobuf::Arena* arena) const override;
#endif
void CopyFrom(const ::google::protobuf::Message& from) PB_321_OVERRIDE;
void MergeFrom(const ::google::protobuf::Message& from) override;
void CopyFrom(const MemcacheResponse& from);
void MergeFrom(const MemcacheResponse& from);
void Clear() override;
bool IsInitialized() const override;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PB_310_OVERRIDE;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PB_310_OVERRIDE;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const PB_310_OVERRIDE;
int GetCachedSize() const override { return _cached_size_; }
static const ::google::protobuf::Descriptor* descriptor();
protected:
::google::protobuf::Metadata GetMetadata() const override;
private:
bool PopCounter(uint8_t command, uint64_t* new_value, uint64_t* cas_value);
bool PopStore(uint8_t command, uint64_t* cas_value);
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const override;
std::string _err;
butil::IOBuf _buf;
mutable int _cached_size_;
};
} // namespace brpc
#endif // BRPC_MEMCACHE_H
+78
View File
@@ -0,0 +1,78 @@
// 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.
#ifndef BRPC_MONGO_HEAD_H
#define BRPC_MONGO_HEAD_H
#include "butil/sys_byteorder.h"
namespace brpc {
// Sync with
// https://github.com/mongodb/mongo-c-driver/blob/master/src/mongoc/mongoc-opcode.h
// https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#request-opcodes
enum MongoOpCode {
MONGO_OPCODE_REPLY = 1,
MONGO_OPCODE_MSG = 1000,
MONGO_OPCODE_UPDATE = 2001,
MONGO_OPCODE_INSERT = 2002,
MONGO_OPCODE_QUERY = 2004,
MONGO_OPCODE_GET_MORE = 2005,
MONGO_OPCODE_DELETE = 2006,
MONGO_OPCODE_KILL_CURSORS = 2007,
};
inline bool is_mongo_opcode(int32_t op_code) {
switch (op_code) {
case MONGO_OPCODE_REPLY: return true;
case MONGO_OPCODE_MSG: return true;
case MONGO_OPCODE_UPDATE: return true;
case MONGO_OPCODE_INSERT: return true;
case MONGO_OPCODE_QUERY: return true;
case MONGO_OPCODE_GET_MORE: return true;
case MONGO_OPCODE_DELETE: return true;
case MONGO_OPCODE_KILL_CURSORS : return true;
}
return false;
}
// All data of mongo protocol is little-endian.
// https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#byte-ordering
#pragma pack(1)
struct mongo_head_t {
int32_t message_length; // total message size, including this
int32_t request_id; // identifier for this message
int32_t response_to; // requestID from the original request
// (used in responses from db)
int32_t op_code; // request type, see MongoOpCode.
void make_host_endian() {
if (!ARCH_CPU_LITTLE_ENDIAN) {
message_length = butil::ByteSwap((uint32_t)message_length);
request_id = butil::ByteSwap((uint32_t)request_id);
response_to = butil::ByteSwap((uint32_t)response_to);
op_code = butil::ByteSwap((uint32_t)op_code);
}
}
};
#pragma pack()
} // namespace brpc
#endif // BRPC_MONGO_HEAD_H
+61
View File
@@ -0,0 +1,61 @@
// 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.
#ifndef BRPC_MONGO_SERVICE_ADAPTOR_H
#define BRPC_MONGO_SERVICE_ADAPTOR_H
#include "butil/iobuf.h"
#include "brpc/input_message_base.h"
#include "brpc/shared_object.h"
namespace brpc {
// custom mongo context. derive this and implement your own functionalities.
class MongoContext : public SharedObject {
public:
virtual ~MongoContext() {}
};
// a container of custom mongo context. created by ParseMongoRequest when the first msg comes over
// a socket. it lives as long as the socket.
class MongoContextMessage : public InputMessageBase {
public:
MongoContextMessage(MongoContext *context) : _context(context) {}
// @InputMessageBase
void DestroyImpl() { delete this; }
MongoContext* context() { return _context.get(); }
private:
butil::intrusive_ptr<MongoContext> _context;
};
class MongoServiceAdaptor {
public:
// Make an error msg when the cntl fails. If cntl fails, we must send mongo client a msg not
// only to indicate the error, but also to finish the round trip.
virtual void SerializeError(int response_to, butil::IOBuf* out_buf) const = 0;
// Create a custom context which is attached to socket. This func is called only when the first
// msg from the socket comes. The context will be destroyed when the socket is closed.
virtual MongoContext* CreateSocketContext() const = 0;
};
} // namespace brpc
#endif
+77
View File
@@ -0,0 +1,77 @@
// 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.
#ifndef BRPC_NAMING_SERVICE_H
#define BRPC_NAMING_SERVICE_H
#include <vector> // std::vector
#include <string> // std::string
#include <ostream> // std::ostream
#include "butil/endpoint.h" // butil::EndPoint
#include "butil/macros.h" // BAIDU_CONCAT
#include "brpc/describable.h"
#include "brpc/destroyable.h"
#include "brpc/extension.h" // Extension<T>
#include "brpc/server_node.h" // ServerNode
namespace brpc {
// Continuing actions to added/removed servers.
// NOTE: You don't have to implement this class.
class NamingServiceActions {
public:
virtual ~NamingServiceActions() {}
virtual void AddServers(const std::vector<ServerNode>& servers) = 0;
virtual void RemoveServers(const std::vector<ServerNode>& servers) = 0;
virtual void ResetServers(const std::vector<ServerNode>& servers) = 0;
};
// Mapping a name to ServerNodes.
class NamingService : public Describable, public Destroyable {
public:
// Implement this method to get servers associated with `service_name'
// in periodic or event-driven manner, call methods of `actions' to
// tell RPC system about server changes. This method will be run in
// a dedicated bthread without access from other threads, thus the
// implementation does NOT need to be thread-safe.
// Return 0 on success, error code otherwise.
virtual int RunNamingService(const char* service_name,
NamingServiceActions* actions) = 0;
// If this method returns true, RunNamingService will be called without
// a dedicated bthread. As the name implies, this is suitable for static
// and simple impl, saving the cost of creating a bthread. However most
// impl of RunNamingService never quit, thread is a must to prevent the
// method from blocking the caller.
virtual bool RunNamingServiceReturnsQuickly() { return false; }
// Create/destroy an instance.
// Caller is responsible for Destroy() the instance after usage.
virtual NamingService* New() const = 0;
protected:
virtual ~NamingService() {}
};
inline Extension<const NamingService>* NamingServiceExtension() {
return Extension<const NamingService>::instance();
}
} // namespace brpc
#endif // BRPC_NAMING_SERVICE_H
+40
View File
@@ -0,0 +1,40 @@
// 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.
#ifndef BRPC_NAMING_SERVICE_FILTER_H
#define BRPC_NAMING_SERVICE_FILTER_H
#include "brpc/naming_service.h" // ServerNode
namespace brpc {
class NamingServiceFilter {
public:
virtual ~NamingServiceFilter() {}
// Return true to take this `server' as a candidate to issue RPC
// Return false to filter it out
virtual bool Accept(const ServerNode& server) const = 0;
};
} // namespace brpc
#endif // BRPC_NAMING_SERVICE_FILTER_H
+41
View File
@@ -0,0 +1,41 @@
// 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.
#ifndef BRPC_NSHEAD_H
#define BRPC_NSHEAD_H
namespace brpc {
// Copied from public/nshead/nshead.h which is essentially unchangable. (Or
// even if it's changed, servers accepting new formats should also accept
// older formats).
static const unsigned int NSHEAD_MAGICNUM = 0xfb709394;
struct nshead_t {
unsigned short id;
unsigned short version;
unsigned int log_id;
char provider[16];
unsigned int magic_num;
unsigned int reserved;
unsigned int body_len;
};
} // namespace brpc
#endif // BRPC_NSHEAD_H
+83
View File
@@ -0,0 +1,83 @@
// 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.
#ifndef BRPC_NSHEAD_MESSAGE_H
#define BRPC_NSHEAD_MESSAGE_H
#include <google/protobuf/message.h>
#include "brpc/nshead.h" // nshead_t
#include "butil/iobuf.h" // IOBuf
#include "brpc/proto_base.pb.h"
#include "brpc/pb_compat.h"
namespace brpc {
// Representing a nshead request or response.
class NsheadMessage : public ::google::protobuf::Message {
public:
nshead_t head;
butil::IOBuf body;
public:
NsheadMessage();
virtual ~NsheadMessage();
NsheadMessage(const NsheadMessage& from);
inline NsheadMessage& operator=(const NsheadMessage& from) {
CopyFrom(from);
return *this;
}
static const ::google::protobuf::Descriptor* descriptor();
void Swap(NsheadMessage* other);
// implements Message ----------------------------------------------
NsheadMessage* New() const PB_319_OVERRIDE;
#if GOOGLE_PROTOBUF_VERSION >= 3006000
NsheadMessage* New(::google::protobuf::Arena* arena) const override;
#endif
void CopyFrom(const ::google::protobuf::Message& from) PB_321_OVERRIDE;
void MergeFrom(const ::google::protobuf::Message& from) override;
void CopyFrom(const NsheadMessage& from);
void MergeFrom(const NsheadMessage& from);
void Clear() override;
bool IsInitialized() const override;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PB_310_OVERRIDE;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PB_310_OVERRIDE;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const PB_310_OVERRIDE;
int GetCachedSize() const override { return ByteSize(); }
protected:
::google::protobuf::Metadata GetMetadata() const override;
private:
void SharedCtor();
void SharedDtor();
};
} // namespace brpc
#endif // BRPC_NSHEAD_MESSAGE_H
+683
View File
@@ -0,0 +1,683 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: brpc/nshead_meta.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_brpc_2fnshead_5fmeta_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_brpc_2fnshead_5fmeta_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3017000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3017003 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
#include "brpc/options.pb.h"
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_brpc_2fnshead_5fmeta_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_brpc_2fnshead_5fmeta_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_brpc_2fnshead_5fmeta_2eproto;
namespace brpc {
class NsheadMeta;
struct NsheadMetaDefaultTypeInternal;
extern NsheadMetaDefaultTypeInternal _NsheadMeta_default_instance_;
} // namespace brpc
PROTOBUF_NAMESPACE_OPEN
template<> ::brpc::NsheadMeta* Arena::CreateMaybeMessage<::brpc::NsheadMeta>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace brpc {
// ===================================================================
class NsheadMeta final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:brpc.NsheadMeta) */ {
public:
inline NsheadMeta() : NsheadMeta(nullptr) {}
~NsheadMeta() override;
explicit constexpr NsheadMeta(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
NsheadMeta(const NsheadMeta& from);
NsheadMeta(NsheadMeta&& from) noexcept
: NsheadMeta() {
*this = ::std::move(from);
}
inline NsheadMeta& operator=(const NsheadMeta& from) {
CopyFrom(from);
return *this;
}
inline NsheadMeta& operator=(NsheadMeta&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const NsheadMeta& default_instance() {
return *internal_default_instance();
}
static inline const NsheadMeta* internal_default_instance() {
return reinterpret_cast<const NsheadMeta*>(
&_NsheadMeta_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(NsheadMeta& a, NsheadMeta& b) {
a.Swap(&b);
}
inline void Swap(NsheadMeta* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(NsheadMeta* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline NsheadMeta* New() const final {
return new NsheadMeta();
}
NsheadMeta* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<NsheadMeta>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const NsheadMeta& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const NsheadMeta& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(NsheadMeta* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "brpc.NsheadMeta";
}
protected:
explicit NsheadMeta(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kFullMethodNameFieldNumber = 1,
kUserStringFieldNumber = 9,
kCorrelationIdFieldNumber = 2,
kLogIdFieldNumber = 3,
kAttachmentSizeFieldNumber = 4,
kCompressTypeFieldNumber = 5,
kTraceIdFieldNumber = 6,
kSpanIdFieldNumber = 7,
kParentSpanIdFieldNumber = 8,
};
// required string full_method_name = 1;
bool has_full_method_name() const;
private:
bool _internal_has_full_method_name() const;
public:
void clear_full_method_name();
const std::string& full_method_name() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_full_method_name(ArgT0&& arg0, ArgT... args);
std::string* mutable_full_method_name();
PROTOBUF_MUST_USE_RESULT std::string* release_full_method_name();
void set_allocated_full_method_name(std::string* full_method_name);
private:
const std::string& _internal_full_method_name() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_full_method_name(const std::string& value);
std::string* _internal_mutable_full_method_name();
public:
// optional bytes user_string = 9;
bool has_user_string() const;
private:
bool _internal_has_user_string() const;
public:
void clear_user_string();
const std::string& user_string() const;
template <typename ArgT0 = const std::string&, typename... ArgT>
void set_user_string(ArgT0&& arg0, ArgT... args);
std::string* mutable_user_string();
PROTOBUF_MUST_USE_RESULT std::string* release_user_string();
void set_allocated_user_string(std::string* user_string);
private:
const std::string& _internal_user_string() const;
inline PROTOBUF_ALWAYS_INLINE void _internal_set_user_string(const std::string& value);
std::string* _internal_mutable_user_string();
public:
// optional int64 correlation_id = 2;
bool has_correlation_id() const;
private:
bool _internal_has_correlation_id() const;
public:
void clear_correlation_id();
::PROTOBUF_NAMESPACE_ID::int64 correlation_id() const;
void set_correlation_id(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_correlation_id() const;
void _internal_set_correlation_id(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional int64 log_id = 3;
bool has_log_id() const;
private:
bool _internal_has_log_id() const;
public:
void clear_log_id();
::PROTOBUF_NAMESPACE_ID::int64 log_id() const;
void set_log_id(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_log_id() const;
void _internal_set_log_id(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional int32 attachment_size = 4;
bool has_attachment_size() const;
private:
bool _internal_has_attachment_size() const;
public:
void clear_attachment_size();
::PROTOBUF_NAMESPACE_ID::int32 attachment_size() const;
void set_attachment_size(::PROTOBUF_NAMESPACE_ID::int32 value);
private:
::PROTOBUF_NAMESPACE_ID::int32 _internal_attachment_size() const;
void _internal_set_attachment_size(::PROTOBUF_NAMESPACE_ID::int32 value);
public:
// optional .brpc.CompressType compress_type = 5;
bool has_compress_type() const;
private:
bool _internal_has_compress_type() const;
public:
void clear_compress_type();
::brpc::CompressType compress_type() const;
void set_compress_type(::brpc::CompressType value);
private:
::brpc::CompressType _internal_compress_type() const;
void _internal_set_compress_type(::brpc::CompressType value);
public:
// optional int64 trace_id = 6;
bool has_trace_id() const;
private:
bool _internal_has_trace_id() const;
public:
void clear_trace_id();
::PROTOBUF_NAMESPACE_ID::int64 trace_id() const;
void set_trace_id(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_trace_id() const;
void _internal_set_trace_id(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional int64 span_id = 7;
bool has_span_id() const;
private:
bool _internal_has_span_id() const;
public:
void clear_span_id();
::PROTOBUF_NAMESPACE_ID::int64 span_id() const;
void set_span_id(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_span_id() const;
void _internal_set_span_id(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// optional int64 parent_span_id = 8;
bool has_parent_span_id() const;
private:
bool _internal_has_parent_span_id() const;
public:
void clear_parent_span_id();
::PROTOBUF_NAMESPACE_ID::int64 parent_span_id() const;
void set_parent_span_id(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_parent_span_id() const;
void _internal_set_parent_span_id(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// @@protoc_insertion_point(class_scope:brpc.NsheadMeta)
private:
class _Internal;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr full_method_name_;
::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr user_string_;
::PROTOBUF_NAMESPACE_ID::int64 correlation_id_;
::PROTOBUF_NAMESPACE_ID::int64 log_id_;
::PROTOBUF_NAMESPACE_ID::int32 attachment_size_;
int compress_type_;
::PROTOBUF_NAMESPACE_ID::int64 trace_id_;
::PROTOBUF_NAMESPACE_ID::int64 span_id_;
::PROTOBUF_NAMESPACE_ID::int64 parent_span_id_;
friend struct ::TableStruct_brpc_2fnshead_5fmeta_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// NsheadMeta
// required string full_method_name = 1;
inline bool NsheadMeta::_internal_has_full_method_name() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool NsheadMeta::has_full_method_name() const {
return _internal_has_full_method_name();
}
inline void NsheadMeta::clear_full_method_name() {
full_method_name_.ClearToEmpty();
_has_bits_[0] &= ~0x00000001u;
}
inline const std::string& NsheadMeta::full_method_name() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.full_method_name)
return _internal_full_method_name();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void NsheadMeta::set_full_method_name(ArgT0&& arg0, ArgT... args) {
_has_bits_[0] |= 0x00000001u;
full_method_name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.full_method_name)
}
inline std::string* NsheadMeta::mutable_full_method_name() {
std::string* _s = _internal_mutable_full_method_name();
// @@protoc_insertion_point(field_mutable:brpc.NsheadMeta.full_method_name)
return _s;
}
inline const std::string& NsheadMeta::_internal_full_method_name() const {
return full_method_name_.Get();
}
inline void NsheadMeta::_internal_set_full_method_name(const std::string& value) {
_has_bits_[0] |= 0x00000001u;
full_method_name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* NsheadMeta::_internal_mutable_full_method_name() {
_has_bits_[0] |= 0x00000001u;
return full_method_name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* NsheadMeta::release_full_method_name() {
// @@protoc_insertion_point(field_release:brpc.NsheadMeta.full_method_name)
if (!_internal_has_full_method_name()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000001u;
return full_method_name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
}
inline void NsheadMeta::set_allocated_full_method_name(std::string* full_method_name) {
if (full_method_name != nullptr) {
_has_bits_[0] |= 0x00000001u;
} else {
_has_bits_[0] &= ~0x00000001u;
}
full_method_name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), full_method_name,
GetArenaForAllocation());
// @@protoc_insertion_point(field_set_allocated:brpc.NsheadMeta.full_method_name)
}
// optional int64 correlation_id = 2;
inline bool NsheadMeta::_internal_has_correlation_id() const {
bool value = (_has_bits_[0] & 0x00000004u) != 0;
return value;
}
inline bool NsheadMeta::has_correlation_id() const {
return _internal_has_correlation_id();
}
inline void NsheadMeta::clear_correlation_id() {
correlation_id_ = int64_t{0};
_has_bits_[0] &= ~0x00000004u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::_internal_correlation_id() const {
return correlation_id_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::correlation_id() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.correlation_id)
return _internal_correlation_id();
}
inline void NsheadMeta::_internal_set_correlation_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000004u;
correlation_id_ = value;
}
inline void NsheadMeta::set_correlation_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_correlation_id(value);
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.correlation_id)
}
// optional int64 log_id = 3;
inline bool NsheadMeta::_internal_has_log_id() const {
bool value = (_has_bits_[0] & 0x00000008u) != 0;
return value;
}
inline bool NsheadMeta::has_log_id() const {
return _internal_has_log_id();
}
inline void NsheadMeta::clear_log_id() {
log_id_ = int64_t{0};
_has_bits_[0] &= ~0x00000008u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::_internal_log_id() const {
return log_id_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::log_id() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.log_id)
return _internal_log_id();
}
inline void NsheadMeta::_internal_set_log_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000008u;
log_id_ = value;
}
inline void NsheadMeta::set_log_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_log_id(value);
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.log_id)
}
// optional int32 attachment_size = 4;
inline bool NsheadMeta::_internal_has_attachment_size() const {
bool value = (_has_bits_[0] & 0x00000010u) != 0;
return value;
}
inline bool NsheadMeta::has_attachment_size() const {
return _internal_has_attachment_size();
}
inline void NsheadMeta::clear_attachment_size() {
attachment_size_ = 0;
_has_bits_[0] &= ~0x00000010u;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 NsheadMeta::_internal_attachment_size() const {
return attachment_size_;
}
inline ::PROTOBUF_NAMESPACE_ID::int32 NsheadMeta::attachment_size() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.attachment_size)
return _internal_attachment_size();
}
inline void NsheadMeta::_internal_set_attachment_size(::PROTOBUF_NAMESPACE_ID::int32 value) {
_has_bits_[0] |= 0x00000010u;
attachment_size_ = value;
}
inline void NsheadMeta::set_attachment_size(::PROTOBUF_NAMESPACE_ID::int32 value) {
_internal_set_attachment_size(value);
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.attachment_size)
}
// optional .brpc.CompressType compress_type = 5;
inline bool NsheadMeta::_internal_has_compress_type() const {
bool value = (_has_bits_[0] & 0x00000020u) != 0;
return value;
}
inline bool NsheadMeta::has_compress_type() const {
return _internal_has_compress_type();
}
inline void NsheadMeta::clear_compress_type() {
compress_type_ = 0;
_has_bits_[0] &= ~0x00000020u;
}
inline ::brpc::CompressType NsheadMeta::_internal_compress_type() const {
return static_cast< ::brpc::CompressType >(compress_type_);
}
inline ::brpc::CompressType NsheadMeta::compress_type() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.compress_type)
return _internal_compress_type();
}
inline void NsheadMeta::_internal_set_compress_type(::brpc::CompressType value) {
assert(::brpc::CompressType_IsValid(value));
_has_bits_[0] |= 0x00000020u;
compress_type_ = value;
}
inline void NsheadMeta::set_compress_type(::brpc::CompressType value) {
_internal_set_compress_type(value);
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.compress_type)
}
// optional int64 trace_id = 6;
inline bool NsheadMeta::_internal_has_trace_id() const {
bool value = (_has_bits_[0] & 0x00000040u) != 0;
return value;
}
inline bool NsheadMeta::has_trace_id() const {
return _internal_has_trace_id();
}
inline void NsheadMeta::clear_trace_id() {
trace_id_ = int64_t{0};
_has_bits_[0] &= ~0x00000040u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::_internal_trace_id() const {
return trace_id_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::trace_id() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.trace_id)
return _internal_trace_id();
}
inline void NsheadMeta::_internal_set_trace_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000040u;
trace_id_ = value;
}
inline void NsheadMeta::set_trace_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_trace_id(value);
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.trace_id)
}
// optional int64 span_id = 7;
inline bool NsheadMeta::_internal_has_span_id() const {
bool value = (_has_bits_[0] & 0x00000080u) != 0;
return value;
}
inline bool NsheadMeta::has_span_id() const {
return _internal_has_span_id();
}
inline void NsheadMeta::clear_span_id() {
span_id_ = int64_t{0};
_has_bits_[0] &= ~0x00000080u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::_internal_span_id() const {
return span_id_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::span_id() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.span_id)
return _internal_span_id();
}
inline void NsheadMeta::_internal_set_span_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000080u;
span_id_ = value;
}
inline void NsheadMeta::set_span_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_span_id(value);
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.span_id)
}
// optional int64 parent_span_id = 8;
inline bool NsheadMeta::_internal_has_parent_span_id() const {
bool value = (_has_bits_[0] & 0x00000100u) != 0;
return value;
}
inline bool NsheadMeta::has_parent_span_id() const {
return _internal_has_parent_span_id();
}
inline void NsheadMeta::clear_parent_span_id() {
parent_span_id_ = int64_t{0};
_has_bits_[0] &= ~0x00000100u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::_internal_parent_span_id() const {
return parent_span_id_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 NsheadMeta::parent_span_id() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.parent_span_id)
return _internal_parent_span_id();
}
inline void NsheadMeta::_internal_set_parent_span_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000100u;
parent_span_id_ = value;
}
inline void NsheadMeta::set_parent_span_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_parent_span_id(value);
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.parent_span_id)
}
// optional bytes user_string = 9;
inline bool NsheadMeta::_internal_has_user_string() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool NsheadMeta::has_user_string() const {
return _internal_has_user_string();
}
inline void NsheadMeta::clear_user_string() {
user_string_.ClearToEmpty();
_has_bits_[0] &= ~0x00000002u;
}
inline const std::string& NsheadMeta::user_string() const {
// @@protoc_insertion_point(field_get:brpc.NsheadMeta.user_string)
return _internal_user_string();
}
template <typename ArgT0, typename... ArgT>
inline PROTOBUF_ALWAYS_INLINE
void NsheadMeta::set_user_string(ArgT0&& arg0, ArgT... args) {
_has_bits_[0] |= 0x00000002u;
user_string_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation());
// @@protoc_insertion_point(field_set:brpc.NsheadMeta.user_string)
}
inline std::string* NsheadMeta::mutable_user_string() {
std::string* _s = _internal_mutable_user_string();
// @@protoc_insertion_point(field_mutable:brpc.NsheadMeta.user_string)
return _s;
}
inline const std::string& NsheadMeta::_internal_user_string() const {
return user_string_.Get();
}
inline void NsheadMeta::_internal_set_user_string(const std::string& value) {
_has_bits_[0] |= 0x00000002u;
user_string_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation());
}
inline std::string* NsheadMeta::_internal_mutable_user_string() {
_has_bits_[0] |= 0x00000002u;
return user_string_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation());
}
inline std::string* NsheadMeta::release_user_string() {
// @@protoc_insertion_point(field_release:brpc.NsheadMeta.user_string)
if (!_internal_has_user_string()) {
return nullptr;
}
_has_bits_[0] &= ~0x00000002u;
return user_string_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation());
}
inline void NsheadMeta::set_allocated_user_string(std::string* user_string) {
if (user_string != nullptr) {
_has_bits_[0] |= 0x00000002u;
} else {
_has_bits_[0] &= ~0x00000002u;
}
user_string_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), user_string,
GetArenaForAllocation());
// @@protoc_insertion_point(field_set_allocated:brpc.NsheadMeta.user_string)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
} // namespace brpc
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_brpc_2fnshead_5fmeta_2eproto
+95
View File
@@ -0,0 +1,95 @@
// 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.
#ifndef BRPC_NSHEAD_PB_SERVICE_ADAPTOR_H
#define BRPC_NSHEAD_PB_SERVICE_ADAPTOR_H
#include "brpc/nshead_service.h" // NsheadService
#include "brpc/nshead_meta.pb.h" // NsheadMeta
namespace brpc {
class NsheadPbServiceAdaptor;
extern const size_t SendNsheadPbResponseSize;
// Adapt nshead requests to use protobuf-based service.
// What RPC does:
// * Call ParseNsheadMeta() to understand the nshead header, user must
// tell RPC which pb method to call in the callback.
// * Call ParseRequestFromIOBuf() to convert the body after nshead header
// to pb request, then call the pb method.
// * When user calls server's done to end the RPC, SerializeResponseToIOBuf()
// is called to convert pb response to binary data that will be appended
// after nshead header and sent back to client.
class NsheadPbServiceAdaptor : public NsheadService {
public:
NsheadPbServiceAdaptor() : NsheadService(
NsheadServiceOptions(false, SendNsheadPbResponseSize)) {}
virtual ~NsheadPbServiceAdaptor() {}
// Fetch meta from `nshead_req' into `meta'.
// Params:
// server: where the RPC runs.
// nshead_req: the nshead request that server received.
// controller: If something goes wrong, call controller->SetFailed()
// meta: Set meta information into this structure. `full_method_name'
// must be set if controller is not SetFailed()-ed
// FIXME: server is not needed anymore, controller->server() is same
virtual void ParseNsheadMeta(const Server& server,
const NsheadMessage& nshead_req,
Controller* controller,
NsheadMeta* meta) const = 0;
// Transform `nshead_req' to `pb_req'.
// Params:
// meta: was set by ParseNsheadMeta()
// nshead_req: the nshead request that server received.
// controller: you can set attachment into the controller. If something
// goes wrong, call controller->SetFailed()
// pb_req: the pb request should be set by your implementation.
virtual void ParseRequestFromIOBuf(const NsheadMeta& meta,
const NsheadMessage& nshead_req,
Controller* controller,
google::protobuf::Message* pb_req) const = 0;
// Transform `pb_res' (and controller) to `nshead_res'.
// Params:
// meta: was set by ParseNsheadMeta()
// controller: If something goes wrong, call controller->SetFailed()
// pb_res: the pb response that returned by pb method. [NOTE] `pb_res'
// can be NULL or uninitialized when RPC failed (indicated by
// Controller::Failed()), in which case you may put error
// information into `nshead_res'.
// nshead_res: the nshead response that will be sent back to client.
virtual void SerializeResponseToIOBuf(const NsheadMeta& meta,
Controller* controller,
const google::protobuf::Message* pb_res,
NsheadMessage* nshead_res) const = 0;
private:
void ProcessNsheadRequest(
const Server& server, Controller* controller,
const NsheadMessage& request, NsheadMessage* response,
NsheadClosure* done);
};
} // namespace brpc
#endif // BRPC_NSHEAD_PB_SERVICE_ADAPTOR_H
+128
View File
@@ -0,0 +1,128 @@
// 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.
#ifndef BRPC_NSHEAD_SERVICE_H
#define BRPC_NSHEAD_SERVICE_H
#include "brpc/controller.h" // Controller
#include "brpc/nshead_message.h" // NsheadMessage
#include "brpc/describable.h"
namespace brpc {
class Server;
class MethodStatus;
class StatusService;
namespace policy {
void ProcessNsheadRequest(InputMessageBase* msg_base);
}
// The continuation of request processing. Namely send response back to client.
// NOTE: you DON'T need to inherit this class or create instance of this class.
class NsheadClosure : public google::protobuf::Closure {
public:
explicit NsheadClosure(void* additional_space);
// [Required] Call this to send response back to the client.
void Run();
// [Optional] Set the full method name. If unset, use name of the service.
void SetMethodName(const std::string& full_method_name);
// The space required by subclass at NsheadServiceOptions. subclass may
// utilizes this feature to save the cost of allocating closure separately.
// If subclass does not require space, this return value is NULL.
void* additional_space() { return _additional_space; }
int64_t received_us() const { return _received_us; }
// Don't send response back, used by MIMO.
void DoNotRespond();
private:
friend void policy::ProcessNsheadRequest(InputMessageBase* msg_base);
friend class DeleteNsheadClosure;
// Only callable by Run().
~NsheadClosure();
const Server* _server;
int64_t _received_us;
NsheadMessage _request;
NsheadMessage _response;
bool _do_respond;
void* _additional_space;
Controller _controller;
};
struct NsheadServiceOptions {
NsheadServiceOptions() : generate_status(true), additional_space(0) {}
NsheadServiceOptions(bool generate_status2, size_t additional_space2)
: generate_status(generate_status2)
, additional_space(additional_space2) {}
bool generate_status;
size_t additional_space;
};
// Inherit this class to let brpc server understands nshead requests.
class NsheadService : public Describable {
public:
NsheadService();
NsheadService(const NsheadServiceOptions&);
virtual ~NsheadService();
// Implement this method to handle nshead requests. Notice that this
// method can be called with a failed Controller(something wrong with the
// request before calling this method), in which case the implemenetation
// shall send specific response with error information back to client.
// Parameters:
// server The server receiving the request.
// controller per-rpc settings.
// request The nshead request received.
// response The nshead response that you should fill in.
// done You must call done->Run() to end the processing.
virtual void ProcessNsheadRequest(const Server& server,
Controller* controller,
const NsheadMessage& request,
NsheadMessage* response,
NsheadClosure* done) = 0;
// Put descriptions into the stream.
void Describe(std::ostream &os, const DescribeOptions&) const;
private:
DISALLOW_COPY_AND_ASSIGN(NsheadService);
friend class NsheadClosure;
friend void policy::ProcessNsheadRequest(InputMessageBase* msg_base);
friend class StatusService;
friend class Server;
private:
void Expose(const butil::StringPiece& prefix);
// Tracking status of non NsheadPbService
MethodStatus* _status;
size_t _additional_space;
std::string _cached_name;
};
} // namespace brpc
#endif // BRPC_NSHEAD_SERVICE_H
+486
View File
@@ -0,0 +1,486 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: brpc/options.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_brpc_2foptions_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_brpc_2foptions_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 3017000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3017003 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/descriptor.pb.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_brpc_2foptions_2eproto
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct TableStruct_brpc_2foptions_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_brpc_2foptions_2eproto;
namespace brpc {
class ChunkInfo;
struct ChunkInfoDefaultTypeInternal;
extern ChunkInfoDefaultTypeInternal _ChunkInfo_default_instance_;
} // namespace brpc
PROTOBUF_NAMESPACE_OPEN
template<> ::brpc::ChunkInfo* Arena::CreateMaybeMessage<::brpc::ChunkInfo>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
namespace brpc {
enum TalkType : int {
TALK_TYPE_NORMAL = 0,
TALK_TYPE_ONEWAY = 1
};
bool TalkType_IsValid(int value);
constexpr TalkType TalkType_MIN = TALK_TYPE_NORMAL;
constexpr TalkType TalkType_MAX = TALK_TYPE_ONEWAY;
constexpr int TalkType_ARRAYSIZE = TalkType_MAX + 1;
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* TalkType_descriptor();
template<typename T>
inline const std::string& TalkType_Name(T enum_t_value) {
static_assert(::std::is_same<T, TalkType>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function TalkType_Name.");
return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
TalkType_descriptor(), enum_t_value);
}
inline bool TalkType_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, TalkType* value) {
return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<TalkType>(
TalkType_descriptor(), name, value);
}
enum ConnectionType : int {
CONNECTION_TYPE_UNKNOWN = 0,
CONNECTION_TYPE_SINGLE = 1,
CONNECTION_TYPE_POOLED = 2,
CONNECTION_TYPE_SHORT = 4
};
bool ConnectionType_IsValid(int value);
constexpr ConnectionType ConnectionType_MIN = CONNECTION_TYPE_UNKNOWN;
constexpr ConnectionType ConnectionType_MAX = CONNECTION_TYPE_SHORT;
constexpr int ConnectionType_ARRAYSIZE = ConnectionType_MAX + 1;
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* ConnectionType_descriptor();
template<typename T>
inline const std::string& ConnectionType_Name(T enum_t_value) {
static_assert(::std::is_same<T, ConnectionType>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function ConnectionType_Name.");
return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
ConnectionType_descriptor(), enum_t_value);
}
inline bool ConnectionType_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, ConnectionType* value) {
return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<ConnectionType>(
ConnectionType_descriptor(), name, value);
}
enum ProtocolType : int {
PROTOCOL_UNKNOWN = 0,
PROTOCOL_BAIDU_STD = 1,
PROTOCOL_STREAMING_RPC = 2,
PROTOCOL_HULU_PBRPC = 3,
PROTOCOL_SOFA_PBRPC = 4,
PROTOCOL_RTMP = 5,
PROTOCOL_THRIFT = 6,
PROTOCOL_HTTP = 7,
PROTOCOL_PUBLIC_PBRPC = 8,
PROTOCOL_NOVA_PBRPC = 9,
PROTOCOL_REDIS = 10,
PROTOCOL_NSHEAD_CLIENT = 11,
PROTOCOL_NSHEAD = 12,
PROTOCOL_HADOOP_RPC = 13,
PROTOCOL_HADOOP_SERVER_RPC = 14,
PROTOCOL_MONGO = 15,
PROTOCOL_UBRPC_COMPACK = 16,
PROTOCOL_DIDX_CLIENT = 17,
PROTOCOL_MEMCACHE = 18,
PROTOCOL_ITP = 19,
PROTOCOL_NSHEAD_MCPACK = 20,
PROTOCOL_DISP_IDL = 21,
PROTOCOL_ERSDA_CLIENT = 22,
PROTOCOL_UBRPC_MCPACK2 = 23,
PROTOCOL_CDS_AGENT = 24,
PROTOCOL_ESP = 25,
PROTOCOL_H2 = 26
};
bool ProtocolType_IsValid(int value);
constexpr ProtocolType ProtocolType_MIN = PROTOCOL_UNKNOWN;
constexpr ProtocolType ProtocolType_MAX = PROTOCOL_H2;
constexpr int ProtocolType_ARRAYSIZE = ProtocolType_MAX + 1;
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* ProtocolType_descriptor();
template<typename T>
inline const std::string& ProtocolType_Name(T enum_t_value) {
static_assert(::std::is_same<T, ProtocolType>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function ProtocolType_Name.");
return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
ProtocolType_descriptor(), enum_t_value);
}
inline bool ProtocolType_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, ProtocolType* value) {
return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<ProtocolType>(
ProtocolType_descriptor(), name, value);
}
enum CompressType : int {
COMPRESS_TYPE_NONE = 0,
COMPRESS_TYPE_SNAPPY = 1,
COMPRESS_TYPE_GZIP = 2,
COMPRESS_TYPE_ZLIB = 3,
COMPRESS_TYPE_LZ4 = 4
};
bool CompressType_IsValid(int value);
constexpr CompressType CompressType_MIN = COMPRESS_TYPE_NONE;
constexpr CompressType CompressType_MAX = COMPRESS_TYPE_LZ4;
constexpr int CompressType_ARRAYSIZE = CompressType_MAX + 1;
const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CompressType_descriptor();
template<typename T>
inline const std::string& CompressType_Name(T enum_t_value) {
static_assert(::std::is_same<T, CompressType>::value ||
::std::is_integral<T>::value,
"Incorrect type passed to function CompressType_Name.");
return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum(
CompressType_descriptor(), enum_t_value);
}
inline bool CompressType_Parse(
::PROTOBUF_NAMESPACE_ID::ConstStringParam name, CompressType* value) {
return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum<CompressType>(
CompressType_descriptor(), name, value);
}
// ===================================================================
class ChunkInfo final :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:brpc.ChunkInfo) */ {
public:
inline ChunkInfo() : ChunkInfo(nullptr) {}
~ChunkInfo() override;
explicit constexpr ChunkInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
ChunkInfo(const ChunkInfo& from);
ChunkInfo(ChunkInfo&& from) noexcept
: ChunkInfo() {
*this = ::std::move(from);
}
inline ChunkInfo& operator=(const ChunkInfo& from) {
CopyFrom(from);
return *this;
}
inline ChunkInfo& operator=(ChunkInfo&& from) noexcept {
if (this == &from) return *this;
if (GetOwningArena() == from.GetOwningArena()) {
InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance);
}
inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return default_instance().GetMetadata().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return default_instance().GetMetadata().reflection;
}
static const ChunkInfo& default_instance() {
return *internal_default_instance();
}
static inline const ChunkInfo* internal_default_instance() {
return reinterpret_cast<const ChunkInfo*>(
&_ChunkInfo_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(ChunkInfo& a, ChunkInfo& b) {
a.Swap(&b);
}
inline void Swap(ChunkInfo* other) {
if (other == this) return;
if (GetOwningArena() == other->GetOwningArena()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(ChunkInfo* other) {
if (other == this) return;
GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline ChunkInfo* New() const final {
return new ChunkInfo();
}
ChunkInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<ChunkInfo>(arena);
}
using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
void CopyFrom(const ChunkInfo& from);
using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
void MergeFrom(const ChunkInfo& from);
private:
static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from);
public:
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(ChunkInfo* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "brpc.ChunkInfo";
}
protected:
explicit ChunkInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena,
bool is_message_owned = false);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
public:
static const ClassData _class_data_;
const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kStreamIdFieldNumber = 1,
kChunkIdFieldNumber = 2,
};
// required int64 stream_id = 1;
bool has_stream_id() const;
private:
bool _internal_has_stream_id() const;
public:
void clear_stream_id();
::PROTOBUF_NAMESPACE_ID::int64 stream_id() const;
void set_stream_id(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_stream_id() const;
void _internal_set_stream_id(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// required int64 chunk_id = 2;
bool has_chunk_id() const;
private:
bool _internal_has_chunk_id() const;
public:
void clear_chunk_id();
::PROTOBUF_NAMESPACE_ID::int64 chunk_id() const;
void set_chunk_id(::PROTOBUF_NAMESPACE_ID::int64 value);
private:
::PROTOBUF_NAMESPACE_ID::int64 _internal_chunk_id() const;
void _internal_set_chunk_id(::PROTOBUF_NAMESPACE_ID::int64 value);
public:
// @@protoc_insertion_point(class_scope:brpc.ChunkInfo)
private:
class _Internal;
// helper for ByteSizeLong()
size_t RequiredFieldsByteSizeFallback() const;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
::PROTOBUF_NAMESPACE_ID::int64 stream_id_;
::PROTOBUF_NAMESPACE_ID::int64 chunk_id_;
friend struct ::TableStruct_brpc_2foptions_2eproto;
};
// ===================================================================
static const int kServiceTimeoutFieldNumber = 90000;
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::google::protobuf::ServiceOptions,
::PROTOBUF_NAMESPACE_ID::internal::PrimitiveTypeTraits< ::PROTOBUF_NAMESPACE_ID::int64 >, 3, false >
service_timeout;
static const int kRequestTalkTypeFieldNumber = 90001;
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::google::protobuf::MethodOptions,
::PROTOBUF_NAMESPACE_ID::internal::EnumTypeTraits< ::brpc::TalkType, ::brpc::TalkType_IsValid>, 14, false >
request_talk_type;
static const int kResponseTalkTypeFieldNumber = 90002;
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::google::protobuf::MethodOptions,
::PROTOBUF_NAMESPACE_ID::internal::EnumTypeTraits< ::brpc::TalkType, ::brpc::TalkType_IsValid>, 14, false >
response_talk_type;
static const int kMethodTimeoutFieldNumber = 90003;
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::google::protobuf::MethodOptions,
::PROTOBUF_NAMESPACE_ID::internal::PrimitiveTypeTraits< ::PROTOBUF_NAMESPACE_ID::int64 >, 3, false >
method_timeout;
static const int kRequestCompressionFieldNumber = 90004;
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::google::protobuf::MethodOptions,
::PROTOBUF_NAMESPACE_ID::internal::EnumTypeTraits< ::brpc::CompressType, ::brpc::CompressType_IsValid>, 14, false >
request_compression;
static const int kResponseCompressionFieldNumber = 90005;
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::google::protobuf::MethodOptions,
::PROTOBUF_NAMESPACE_ID::internal::EnumTypeTraits< ::brpc::CompressType, ::brpc::CompressType_IsValid>, 14, false >
response_compression;
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// ChunkInfo
// required int64 stream_id = 1;
inline bool ChunkInfo::_internal_has_stream_id() const {
bool value = (_has_bits_[0] & 0x00000001u) != 0;
return value;
}
inline bool ChunkInfo::has_stream_id() const {
return _internal_has_stream_id();
}
inline void ChunkInfo::clear_stream_id() {
stream_id_ = int64_t{0};
_has_bits_[0] &= ~0x00000001u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 ChunkInfo::_internal_stream_id() const {
return stream_id_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 ChunkInfo::stream_id() const {
// @@protoc_insertion_point(field_get:brpc.ChunkInfo.stream_id)
return _internal_stream_id();
}
inline void ChunkInfo::_internal_set_stream_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000001u;
stream_id_ = value;
}
inline void ChunkInfo::set_stream_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_stream_id(value);
// @@protoc_insertion_point(field_set:brpc.ChunkInfo.stream_id)
}
// required int64 chunk_id = 2;
inline bool ChunkInfo::_internal_has_chunk_id() const {
bool value = (_has_bits_[0] & 0x00000002u) != 0;
return value;
}
inline bool ChunkInfo::has_chunk_id() const {
return _internal_has_chunk_id();
}
inline void ChunkInfo::clear_chunk_id() {
chunk_id_ = int64_t{0};
_has_bits_[0] &= ~0x00000002u;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 ChunkInfo::_internal_chunk_id() const {
return chunk_id_;
}
inline ::PROTOBUF_NAMESPACE_ID::int64 ChunkInfo::chunk_id() const {
// @@protoc_insertion_point(field_get:brpc.ChunkInfo.chunk_id)
return _internal_chunk_id();
}
inline void ChunkInfo::_internal_set_chunk_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_has_bits_[0] |= 0x00000002u;
chunk_id_ = value;
}
inline void ChunkInfo::set_chunk_id(::PROTOBUF_NAMESPACE_ID::int64 value) {
_internal_set_chunk_id(value);
// @@protoc_insertion_point(field_set:brpc.ChunkInfo.chunk_id)
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
} // namespace brpc
PROTOBUF_NAMESPACE_OPEN
template <> struct is_proto_enum< ::brpc::TalkType> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::brpc::TalkType>() {
return ::brpc::TalkType_descriptor();
}
template <> struct is_proto_enum< ::brpc::ConnectionType> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::brpc::ConnectionType>() {
return ::brpc::ConnectionType_descriptor();
}
template <> struct is_proto_enum< ::brpc::ProtocolType> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::brpc::ProtocolType>() {
return ::brpc::ProtocolType_descriptor();
}
template <> struct is_proto_enum< ::brpc::CompressType> : ::std::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::brpc::CompressType>() {
return ::brpc::CompressType_descriptor();
}
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_brpc_2foptions_2eproto

Some files were not shown because too many files have changed in this diff Show More