mirror of https://github.com/grpc/grpc.git
commit
13c0940f66
128 changed files with 11390 additions and 220 deletions
@ -0,0 +1,85 @@ |
||||
GRPC C++ STYLE GUIDE |
||||
===================== |
||||
|
||||
Background |
||||
---------- |
||||
|
||||
Here we document style rules for C++ usage in the gRPC C++ bindings |
||||
and tests. |
||||
|
||||
General |
||||
------- |
||||
|
||||
- The majority of gRPC's C++ requirements are drawn from the [Google C++ style |
||||
guide] (https://google.github.io/styleguide/cppguide.html) |
||||
- However, gRPC has some additional requirements to maintain |
||||
[portability] (#portability) |
||||
- As in C, layout rules are defined by clang-format, and all code |
||||
should be passed through clang-format. A (docker-based) script to do |
||||
so is included in [tools/distrib/clang\_format\_code.sh] |
||||
(../tools/distrib/clang_format_code.sh). |
||||
|
||||
<a name="portability"></a> |
||||
Portability Restrictions |
||||
------------------- |
||||
|
||||
gRPC supports a large number of compilers, ranging from those that are |
||||
missing many key C++11 features to those that have quite detailed |
||||
analysis. As a result, gRPC compiles with a high level of warnings and |
||||
treat all warnings as errors. gRPC also forbids the use of some common |
||||
C++11 constructs. Here are some guidelines, to be extended as needed: |
||||
- Do not use range-based for. Expressions of the form |
||||
```c |
||||
for (auto& i: vec) { |
||||
// code |
||||
} |
||||
``` |
||||
|
||||
are not allowed and should be replaced with code such as |
||||
```c |
||||
for (auto it = vec.begin; it != vec.end(); it++) { |
||||
auto& i = *it; |
||||
// code |
||||
} |
||||
``` |
||||
|
||||
- Do not use lambda of any kind (no capture, explicit capture, or |
||||
default capture). Other C++ functional features such as |
||||
`std::function` or `std::bind` are allowed |
||||
- Do not use brace-list initializers. |
||||
- Do not compare a pointer to `nullptr` . This is because gcc 4.4 |
||||
does not support `nullptr` directly and gRPC implements a subset of |
||||
its features in [include/grpc++/impl/codegen/config.h] |
||||
(../include/grpc++/impl/codegen/config.h). Instead, pointers should |
||||
be checked for validity using their implicit conversion to `bool`. |
||||
In other words, use `if (p)` rather than `if (p != nullptr)` |
||||
- Do not use `final` or `override` as these are not supported by some |
||||
compilers. Instead use `GRPC_FINAL` and `GRPC_OVERRIDE` . These |
||||
compile down to the traditional C++ forms for compilers that support |
||||
them but are just elided if the compiler does not support those features. |
||||
- In the [include] (../../../tree/master/include/grpc++) and [src] |
||||
(../../../tree/master/src/cpp) directory trees, you should also not |
||||
use certain STL objects like `std::mutex`, `std::lock_guard`, |
||||
`std::unique_lock`, `std::nullptr`, `std::thread` . Instead, use |
||||
`grpc::mutex`, `grpc::lock_guard`, etc., which are gRPC |
||||
implementations of the prominent features of these objects that are |
||||
not always available. You can use the `std` versions of those in [test] |
||||
(../../../tree/master/test/cpp) |
||||
- Similarly, in the same directories, do not use `std::chrono` unless |
||||
it is guarded by `#ifndef GRPC_CXX0X_NO_CHRONO` . For platforms that |
||||
lack`std::chrono,` there is a C-language timer called gpr_timespec that can |
||||
be used instead. |
||||
- `std::unique_ptr` must be used with extreme care in any kind of |
||||
collection. For example `vector<std::unique_ptr>` does not work in |
||||
gcc 4.4 if the vector is constructed to its full size at |
||||
initialization but does work if elements are added to the vector |
||||
using functions like `push_back`. `map` and other pair-based |
||||
collections do not work with `unique_ptr` under gcc 4.4. The issue |
||||
is that many of these collection implementations assume a copy |
||||
constructor |
||||
to be available. |
||||
- Don't use `std::this_thread` . Use `gpr_sleep_until` for sleeping a thread. |
||||
- [Some adjacent character combinations cause problems] |
||||
(https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C). If declaring a |
||||
template against some class relative to the global namespace, |
||||
`<::name` will be non-portable. Separate the `<` from the `:` and use `< ::name`. |
@ -0,0 +1,69 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015, 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. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCXX_EXT_PROTO_SERVER_REFLECTION_PLUGIN_H |
||||
#define GRPCXX_EXT_PROTO_SERVER_REFLECTION_PLUGIN_H |
||||
|
||||
#include <grpc++/impl/server_builder_plugin.h> |
||||
#include <grpc++/support/config.h> |
||||
|
||||
namespace grpc { |
||||
class ServerInitializer; |
||||
class ProtoServerReflection; |
||||
} // namespace grpc
|
||||
|
||||
namespace grpc { |
||||
namespace reflection { |
||||
|
||||
class ProtoServerReflectionPlugin : public ::grpc::ServerBuilderPlugin { |
||||
public: |
||||
ProtoServerReflectionPlugin(); |
||||
::grpc::string name() GRPC_OVERRIDE; |
||||
void InitServer(::grpc::ServerInitializer* si) GRPC_OVERRIDE; |
||||
void Finish(::grpc::ServerInitializer* si) GRPC_OVERRIDE; |
||||
void ChangeArguments(const ::grpc::string& name, void* value) GRPC_OVERRIDE; |
||||
bool has_async_methods() const GRPC_OVERRIDE; |
||||
bool has_sync_methods() const GRPC_OVERRIDE; |
||||
|
||||
private: |
||||
std::shared_ptr<::grpc::ProtoServerReflection> reflection_service_; |
||||
}; |
||||
|
||||
// Add proto reflection plugin to ServerBuilder. This function should be called
|
||||
// at the static initialization time.
|
||||
void InitProtoReflectionServerBuilderPlugin(); |
||||
|
||||
} // namespace reflection
|
||||
} // namespace grpc
|
||||
|
||||
#endif // GRPCXX_EXT_PROTO_SERVER_REFLECTION_PLUGIN_H
|
@ -0,0 +1,184 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015, 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. |
||||
* |
||||
*/ |
||||
|
||||
|
||||
// Generated by the gRPC protobuf plugin.
|
||||
// If you make any local change, they will be lost.
|
||||
// source: reflection.proto
|
||||
// Original file comments:
|
||||
// Copyright 2016, 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.
|
||||
//
|
||||
// Service exported by server reflection
|
||||
//
|
||||
#ifndef GRPC_reflection_2eproto__INCLUDED |
||||
#define GRPC_reflection_2eproto__INCLUDED |
||||
|
||||
#include <grpc++/ext/reflection.pb.h> |
||||
|
||||
#include <grpc++/impl/codegen/async_stream.h> |
||||
#include <grpc++/impl/codegen/async_unary_call.h> |
||||
#include <grpc++/impl/codegen/proto_utils.h> |
||||
#include <grpc++/impl/codegen/rpc_method.h> |
||||
#include <grpc++/impl/codegen/service_type.h> |
||||
#include <grpc++/impl/codegen/status.h> |
||||
#include <grpc++/impl/codegen/stub_options.h> |
||||
#include <grpc++/impl/codegen/sync_stream.h> |
||||
|
||||
namespace grpc { |
||||
class CompletionQueue; |
||||
class Channel; |
||||
class RpcService; |
||||
class ServerCompletionQueue; |
||||
class ServerContext; |
||||
} // namespace grpc
|
||||
|
||||
namespace grpc { |
||||
namespace reflection { |
||||
namespace v1alpha { |
||||
|
||||
class ServerReflection GRPC_FINAL { |
||||
public: |
||||
class StubInterface { |
||||
public: |
||||
virtual ~StubInterface() {} |
||||
// The reflection service is structured as a bidirectional stream, ensuring
|
||||
// all related requests go to a single server.
|
||||
std::unique_ptr< ::grpc::ClientReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>> ServerReflectionInfo(::grpc::ClientContext* context) { |
||||
return std::unique_ptr< ::grpc::ClientReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>>(ServerReflectionInfoRaw(context)); |
||||
} |
||||
std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>> AsyncServerReflectionInfo(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { |
||||
return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>>(AsyncServerReflectionInfoRaw(context, cq, tag)); |
||||
} |
||||
private: |
||||
virtual ::grpc::ClientReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* ServerReflectionInfoRaw(::grpc::ClientContext* context) = 0; |
||||
virtual ::grpc::ClientAsyncReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* AsyncServerReflectionInfoRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0; |
||||
}; |
||||
class Stub GRPC_FINAL : public StubInterface { |
||||
public: |
||||
Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); |
||||
std::unique_ptr< ::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>> ServerReflectionInfo(::grpc::ClientContext* context) { |
||||
return std::unique_ptr< ::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>>(ServerReflectionInfoRaw(context)); |
||||
} |
||||
std::unique_ptr< ::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>> AsyncServerReflectionInfo(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { |
||||
return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>>(AsyncServerReflectionInfoRaw(context, cq, tag)); |
||||
} |
||||
|
||||
private: |
||||
std::shared_ptr< ::grpc::ChannelInterface> channel_; |
||||
::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* ServerReflectionInfoRaw(::grpc::ClientContext* context) GRPC_OVERRIDE; |
||||
::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* AsyncServerReflectionInfoRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) GRPC_OVERRIDE; |
||||
const ::grpc::RpcMethod rpcmethod_ServerReflectionInfo_; |
||||
}; |
||||
static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); |
||||
|
||||
class Service : public ::grpc::Service { |
||||
public: |
||||
Service(); |
||||
virtual ~Service(); |
||||
// The reflection service is structured as a bidirectional stream, ensuring
|
||||
// all related requests go to a single server.
|
||||
virtual ::grpc::Status ServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream); |
||||
}; |
||||
template <class BaseClass> |
||||
class WithAsyncMethod_ServerReflectionInfo : public BaseClass { |
||||
private: |
||||
void BaseClassMustBeDerivedFromService(const Service *service) {} |
||||
public: |
||||
WithAsyncMethod_ServerReflectionInfo() { |
||||
::grpc::Service::MarkMethodAsync(0); |
||||
} |
||||
~WithAsyncMethod_ServerReflectionInfo() GRPC_OVERRIDE { |
||||
BaseClassMustBeDerivedFromService(this); |
||||
} |
||||
// disable synchronous version of this method
|
||||
::grpc::Status ServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream) GRPC_FINAL GRPC_OVERRIDE { |
||||
abort(); |
||||
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); |
||||
} |
||||
void RequestServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { |
||||
::grpc::Service::RequestAsyncBidiStreaming(0, context, stream, new_call_cq, notification_cq, tag); |
||||
} |
||||
}; |
||||
typedef WithAsyncMethod_ServerReflectionInfo<Service > AsyncService; |
||||
template <class BaseClass> |
||||
class WithGenericMethod_ServerReflectionInfo : public BaseClass { |
||||
private: |
||||
void BaseClassMustBeDerivedFromService(const Service *service) {} |
||||
public: |
||||
WithGenericMethod_ServerReflectionInfo() { |
||||
::grpc::Service::MarkMethodGeneric(0); |
||||
} |
||||
~WithGenericMethod_ServerReflectionInfo() GRPC_OVERRIDE { |
||||
BaseClassMustBeDerivedFromService(this); |
||||
} |
||||
// disable synchronous version of this method
|
||||
::grpc::Status ServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream) GRPC_FINAL GRPC_OVERRIDE { |
||||
abort(); |
||||
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); |
||||
} |
||||
}; |
||||
}; |
||||
|
||||
} // namespace v1alpha
|
||||
} // namespace reflection
|
||||
} // namespace grpc
|
||||
|
||||
|
||||
#endif // GRPC_reflection_2eproto__INCLUDED
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,232 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016, 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. |
||||
* |
||||
*/ |
||||
|
||||
#include "src/core/ext/transport/chttp2/transport/bin_decoder.h" |
||||
#include <grpc/support/alloc.h> |
||||
#include <grpc/support/log.h> |
||||
#include "src/core/lib/support/string.h" |
||||
|
||||
static uint8_t decode_table[] = { |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 62, 0x40, 0x40, 0x40, 63, |
||||
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0, 1, 2, 3, 4, 5, 6, |
||||
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, |
||||
19, 20, 21, 22, 23, 24, 25, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, |
||||
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, |
||||
49, 50, 51, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, |
||||
0x40, 0x40, 0x40, 0x40}; |
||||
|
||||
static const uint8_t tail_xtra[4] = {0, 0, 1, 2}; |
||||
|
||||
static bool input_is_valid(uint8_t *input_ptr, size_t length) { |
||||
size_t i; |
||||
|
||||
for (i = 0; i < length; ++i) { |
||||
if ((decode_table[input_ptr[i]] & 0xC0) != 0) { |
||||
gpr_log(GPR_ERROR, |
||||
"Base64 decoding failed, invalid character '%c' in base64 " |
||||
"input.\n", |
||||
(char)(*input_ptr)); |
||||
return false; |
||||
} |
||||
} |
||||
return true; |
||||
} |
||||
|
||||
#define COMPOSE_OUTPUT_BYTE_0(input_ptr) \ |
||||
(uint8_t)((decode_table[input_ptr[0]] << 2) | \
|
||||
(decode_table[input_ptr[1]] >> 4)) |
||||
|
||||
#define COMPOSE_OUTPUT_BYTE_1(input_ptr) \ |
||||
(uint8_t)((decode_table[input_ptr[1]] << 4) | \
|
||||
(decode_table[input_ptr[2]] >> 2)) |
||||
|
||||
#define COMPOSE_OUTPUT_BYTE_2(input_ptr) \ |
||||
(uint8_t)((decode_table[input_ptr[2]] << 6) | decode_table[input_ptr[3]]) |
||||
|
||||
bool grpc_base64_decode_partial(struct grpc_base64_decode_context *ctx) { |
||||
size_t input_tail; |
||||
|
||||
if (ctx->input_cur > ctx->input_end || ctx->output_cur > ctx->output_end) { |
||||
return false; |
||||
} |
||||
|
||||
// Process a block of 4 input characters and 3 output bytes
|
||||
while (ctx->input_end >= ctx->input_cur + 4 && |
||||
ctx->output_end >= ctx->output_cur + 3) { |
||||
if (!input_is_valid(ctx->input_cur, 4)) return false; |
||||
ctx->output_cur[0] = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur); |
||||
ctx->output_cur[1] = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur); |
||||
ctx->output_cur[2] = COMPOSE_OUTPUT_BYTE_2(ctx->input_cur); |
||||
ctx->output_cur += 3; |
||||
ctx->input_cur += 4; |
||||
} |
||||
|
||||
// Process the tail of input data
|
||||
input_tail = (size_t)(ctx->input_end - ctx->input_cur); |
||||
if (input_tail == 4) { |
||||
// Process the input data with pad chars
|
||||
if (ctx->input_cur[3] == '=') { |
||||
if (ctx->input_cur[2] == '=' && ctx->output_end >= ctx->output_cur + 1) { |
||||
if (!input_is_valid(ctx->input_cur, 2)) return false; |
||||
*(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur); |
||||
ctx->input_cur += 4; |
||||
} else if (ctx->output_end >= ctx->output_cur + 2) { |
||||
if (!input_is_valid(ctx->input_cur, 3)) return false; |
||||
*(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur); |
||||
*(ctx->output_cur++) = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur); |
||||
; |
||||
ctx->input_cur += 4; |
||||
} |
||||
} |
||||
|
||||
} else if (ctx->contains_tail && input_tail > 1) { |
||||
// Process the input data without pad chars, but constains_tail is set
|
||||
if (ctx->output_end >= ctx->output_cur + tail_xtra[input_tail]) { |
||||
if (!input_is_valid(ctx->input_cur, input_tail)) return false; |
||||
switch (input_tail) { |
||||
case 3: |
||||
ctx->output_cur[1] = COMPOSE_OUTPUT_BYTE_1(ctx->input_cur); |
||||
case 2: |
||||
ctx->output_cur[0] = COMPOSE_OUTPUT_BYTE_0(ctx->input_cur); |
||||
} |
||||
ctx->output_cur += tail_xtra[input_tail]; |
||||
ctx->input_cur += input_tail; |
||||
} |
||||
} |
||||
|
||||
return true; |
||||
} |
||||
|
||||
gpr_slice grpc_chttp2_base64_decode(gpr_slice input) { |
||||
size_t input_length = GPR_SLICE_LENGTH(input); |
||||
size_t output_length = input_length / 4 * 3; |
||||
struct grpc_base64_decode_context ctx; |
||||
gpr_slice output; |
||||
|
||||
if (input_length % 4 != 0) { |
||||
gpr_log(GPR_ERROR, |
||||
"Base64 decoding failed, input of " |
||||
"grpc_chttp2_base64_decode has a length of %d, which is not a " |
||||
"multiple of 4.\n", |
||||
(int)input_length); |
||||
return gpr_empty_slice(); |
||||
} |
||||
|
||||
if (input_length > 0) { |
||||
uint8_t *input_end = GPR_SLICE_END_PTR(input); |
||||
if (*(--input_end) == '=') { |
||||
output_length--; |
||||
if (*(--input_end) == '=') { |
||||
output_length--; |
||||
} |
||||
} |
||||
} |
||||
output = gpr_slice_malloc(output_length); |
||||
|
||||
ctx.input_cur = GPR_SLICE_START_PTR(input); |
||||
ctx.input_end = GPR_SLICE_END_PTR(input); |
||||
ctx.output_cur = GPR_SLICE_START_PTR(output); |
||||
ctx.output_end = GPR_SLICE_END_PTR(output); |
||||
ctx.contains_tail = false; |
||||
|
||||
if (!grpc_base64_decode_partial(&ctx)) { |
||||
char *s = gpr_dump_slice(input, GPR_DUMP_ASCII); |
||||
gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s); |
||||
gpr_free(s); |
||||
gpr_slice_unref(output); |
||||
return gpr_empty_slice(); |
||||
} |
||||
GPR_ASSERT(ctx.output_cur == GPR_SLICE_END_PTR(output)); |
||||
GPR_ASSERT(ctx.input_cur == GPR_SLICE_END_PTR(input)); |
||||
return output; |
||||
} |
||||
|
||||
gpr_slice grpc_chttp2_base64_decode_with_length(gpr_slice input, |
||||
size_t output_length) { |
||||
size_t input_length = GPR_SLICE_LENGTH(input); |
||||
gpr_slice output = gpr_slice_malloc(output_length); |
||||
struct grpc_base64_decode_context ctx; |
||||
|
||||
// The length of a base64 string cannot be 4 * n + 1
|
||||
if (input_length % 4 == 1) { |
||||
gpr_log(GPR_ERROR, |
||||
"Base64 decoding failed, input of " |
||||
"grpc_chttp2_base64_decode_with_length has a length of %d, which " |
||||
"has a tail of 1 byte.\n", |
||||
(int)input_length); |
||||
gpr_slice_unref(output); |
||||
return gpr_empty_slice(); |
||||
} |
||||
|
||||
if (output_length > input_length / 4 * 3 + tail_xtra[input_length % 4]) { |
||||
gpr_log(GPR_ERROR, |
||||
"Base64 decoding failed, output_length %d is longer " |
||||
"than the max possible output length %d.\n", |
||||
(int)output_length, |
||||
(int)(input_length / 4 * 3 + tail_xtra[input_length % 4])); |
||||
gpr_slice_unref(output); |
||||
return gpr_empty_slice(); |
||||
} |
||||
|
||||
ctx.input_cur = GPR_SLICE_START_PTR(input); |
||||
ctx.input_end = GPR_SLICE_END_PTR(input); |
||||
ctx.output_cur = GPR_SLICE_START_PTR(output); |
||||
ctx.output_end = GPR_SLICE_END_PTR(output); |
||||
ctx.contains_tail = true; |
||||
|
||||
if (!grpc_base64_decode_partial(&ctx)) { |
||||
char *s = gpr_dump_slice(input, GPR_DUMP_ASCII); |
||||
gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s); |
||||
gpr_free(s); |
||||
gpr_slice_unref(output); |
||||
return gpr_empty_slice(); |
||||
} |
||||
GPR_ASSERT(ctx.output_cur == GPR_SLICE_END_PTR(output)); |
||||
GPR_ASSERT(ctx.input_cur <= GPR_SLICE_END_PTR(input)); |
||||
return output; |
||||
} |
@ -0,0 +1,66 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016, 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. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_DECODER_H |
||||
#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_DECODER_H |
||||
|
||||
#include <grpc/support/slice.h> |
||||
#include <stdbool.h> |
||||
|
||||
struct grpc_base64_decode_context { |
||||
/* input/output: */ |
||||
uint8_t *input_cur; |
||||
uint8_t *input_end; |
||||
uint8_t *output_cur; |
||||
uint8_t *output_end; |
||||
/* Indicate if the decoder should handle the tail of input data*/ |
||||
bool contains_tail; |
||||
}; |
||||
|
||||
/* base64 decode a grpc_base64_decode_context util either input_end is reached
|
||||
or output_end is reached. When input_end is reached, (input_end - input_cur) |
||||
is less than 4. When output_end is reached, (output_end - output_cur) is less |
||||
than 3. Returns false if decoding is failed. */ |
||||
bool grpc_base64_decode_partial(struct grpc_base64_decode_context *ctx); |
||||
|
||||
/* base64 decode a slice with pad chars. Returns a new slice, does not take
|
||||
ownership of the input. Returns an empty slice if decoding is failed. */ |
||||
gpr_slice grpc_chttp2_base64_decode(gpr_slice input); |
||||
|
||||
/* base64 decode a slice without pad chars, data length is needed. Returns a new
|
||||
slice, does not take ownership of the input. Returns an empty slice if |
||||
decoding is failed. */ |
||||
gpr_slice grpc_chttp2_base64_decode_with_length(gpr_slice input, |
||||
size_t output_length); |
||||
|
||||
#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_DECODER_H */ |
@ -0,0 +1,227 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016, 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. |
||||
* |
||||
*/ |
||||
|
||||
#include <unordered_set> |
||||
#include <vector> |
||||
|
||||
#include <grpc++/grpc++.h> |
||||
|
||||
#include "src/cpp/ext/proto_server_reflection.h" |
||||
|
||||
using grpc::Status; |
||||
using grpc::StatusCode; |
||||
using grpc::reflection::v1alpha::ServerReflectionRequest; |
||||
using grpc::reflection::v1alpha::ExtensionRequest; |
||||
using grpc::reflection::v1alpha::ServerReflectionResponse; |
||||
using grpc::reflection::v1alpha::ListServiceResponse; |
||||
using grpc::reflection::v1alpha::ServiceResponse; |
||||
using grpc::reflection::v1alpha::ExtensionNumberResponse; |
||||
using grpc::reflection::v1alpha::ErrorResponse; |
||||
using grpc::reflection::v1alpha::FileDescriptorResponse; |
||||
|
||||
namespace grpc { |
||||
|
||||
ProtoServerReflection::ProtoServerReflection() |
||||
: descriptor_pool_(protobuf::DescriptorPool::generated_pool()) {} |
||||
|
||||
void ProtoServerReflection::SetServiceList( |
||||
const std::vector<grpc::string>* services) { |
||||
services_ = services; |
||||
} |
||||
|
||||
Status ProtoServerReflection::ServerReflectionInfo( |
||||
ServerContext* context, |
||||
ServerReaderWriter<ServerReflectionResponse, ServerReflectionRequest>* |
||||
stream) { |
||||
ServerReflectionRequest request; |
||||
ServerReflectionResponse response; |
||||
Status status; |
||||
while (stream->Read(&request)) { |
||||
switch (request.message_request_case()) { |
||||
case ServerReflectionRequest::MessageRequestCase::kFileByFilename: |
||||
status = GetFileByName(context, request.file_by_filename(), &response); |
||||
break; |
||||
case ServerReflectionRequest::MessageRequestCase::kFileContainingSymbol: |
||||
status = GetFileContainingSymbol( |
||||
context, request.file_containing_symbol(), &response); |
||||
break; |
||||
case ServerReflectionRequest::MessageRequestCase:: |
||||
kFileContainingExtension: |
||||
status = GetFileContainingExtension( |
||||
context, &request.file_containing_extension(), &response); |
||||
break; |
||||
case ServerReflectionRequest::MessageRequestCase:: |
||||
kAllExtensionNumbersOfType: |
||||
status = GetAllExtensionNumbers( |
||||
context, request.all_extension_numbers_of_type(), |
||||
response.mutable_all_extension_numbers_response()); |
||||
break; |
||||
case ServerReflectionRequest::MessageRequestCase::kListServices: |
||||
status = |
||||
ListService(context, response.mutable_list_services_response()); |
||||
break; |
||||
default: |
||||
status = Status(StatusCode::UNIMPLEMENTED, ""); |
||||
} |
||||
|
||||
if (!status.ok()) { |
||||
FillErrorResponse(status, response.mutable_error_response()); |
||||
} |
||||
response.set_valid_host(request.host()); |
||||
response.set_allocated_original_request( |
||||
new ServerReflectionRequest(request)); |
||||
stream->Write(response); |
||||
} |
||||
|
||||
return Status::OK; |
||||
} |
||||
|
||||
void ProtoServerReflection::FillErrorResponse(const Status& status, |
||||
ErrorResponse* error_response) { |
||||
error_response->set_error_code(status.error_code()); |
||||
error_response->set_error_message(status.error_message()); |
||||
} |
||||
|
||||
Status ProtoServerReflection::ListService(ServerContext* context, |
||||
ListServiceResponse* response) { |
||||
if (services_ == nullptr) { |
||||
return Status(StatusCode::NOT_FOUND, "Services not found."); |
||||
} |
||||
for (auto it = services_->begin(); it != services_->end(); ++it) { |
||||
ServiceResponse* service_response = response->add_service(); |
||||
service_response->set_name(*it); |
||||
} |
||||
return Status::OK; |
||||
} |
||||
|
||||
Status ProtoServerReflection::GetFileByName( |
||||
ServerContext* context, const grpc::string& filename, |
||||
ServerReflectionResponse* response) { |
||||
if (descriptor_pool_ == nullptr) { |
||||
return Status::CANCELLED; |
||||
} |
||||
|
||||
const protobuf::FileDescriptor* file_desc = |
||||
descriptor_pool_->FindFileByName(filename); |
||||
if (file_desc == nullptr) { |
||||
return Status(StatusCode::NOT_FOUND, "File not found."); |
||||
} |
||||
std::unordered_set<grpc::string> seen_files; |
||||
FillFileDescriptorResponse(file_desc, response, &seen_files); |
||||
return Status::OK; |
||||
} |
||||
|
||||
Status ProtoServerReflection::GetFileContainingSymbol( |
||||
ServerContext* context, const grpc::string& symbol, |
||||
ServerReflectionResponse* response) { |
||||
if (descriptor_pool_ == nullptr) { |
||||
return Status::CANCELLED; |
||||
} |
||||
|
||||
const protobuf::FileDescriptor* file_desc = |
||||
descriptor_pool_->FindFileContainingSymbol(symbol); |
||||
if (file_desc == nullptr) { |
||||
return Status(StatusCode::NOT_FOUND, "Symbol not found."); |
||||
} |
||||
std::unordered_set<grpc::string> seen_files; |
||||
FillFileDescriptorResponse(file_desc, response, &seen_files); |
||||
return Status::OK; |
||||
} |
||||
|
||||
Status ProtoServerReflection::GetFileContainingExtension( |
||||
ServerContext* context, const ExtensionRequest* request, |
||||
ServerReflectionResponse* response) { |
||||
if (descriptor_pool_ == nullptr) { |
||||
return Status::CANCELLED; |
||||
} |
||||
|
||||
const protobuf::Descriptor* desc = |
||||
descriptor_pool_->FindMessageTypeByName(request->containing_type()); |
||||
if (desc == nullptr) { |
||||
return Status(StatusCode::NOT_FOUND, "Type not found."); |
||||
} |
||||
|
||||
const protobuf::FieldDescriptor* field_desc = |
||||
descriptor_pool_->FindExtensionByNumber(desc, |
||||
request->extension_number()); |
||||
if (field_desc == nullptr) { |
||||
return Status(StatusCode::NOT_FOUND, "Extension not found."); |
||||
} |
||||
std::unordered_set<grpc::string> seen_files; |
||||
FillFileDescriptorResponse(field_desc->file(), response, &seen_files); |
||||
return Status::OK; |
||||
} |
||||
|
||||
Status ProtoServerReflection::GetAllExtensionNumbers( |
||||
ServerContext* context, const grpc::string& type, |
||||
ExtensionNumberResponse* response) { |
||||
if (descriptor_pool_ == nullptr) { |
||||
return Status::CANCELLED; |
||||
} |
||||
|
||||
const protobuf::Descriptor* desc = |
||||
descriptor_pool_->FindMessageTypeByName(type); |
||||
if (desc == nullptr) { |
||||
return Status(StatusCode::NOT_FOUND, "Type not found."); |
||||
} |
||||
|
||||
std::vector<const protobuf::FieldDescriptor*> extensions; |
||||
descriptor_pool_->FindAllExtensions(desc, &extensions); |
||||
for (auto extension : extensions) { |
||||
response->add_extension_number(extension->number()); |
||||
} |
||||
response->set_base_type_name(type); |
||||
return Status::OK; |
||||
} |
||||
|
||||
void ProtoServerReflection::FillFileDescriptorResponse( |
||||
const protobuf::FileDescriptor* file_desc, |
||||
ServerReflectionResponse* response, |
||||
std::unordered_set<grpc::string>* seen_files) { |
||||
if (seen_files->find(file_desc->name()) != seen_files->end()) { |
||||
return; |
||||
} |
||||
seen_files->insert(file_desc->name()); |
||||
|
||||
protobuf::FileDescriptorProto file_desc_proto; |
||||
grpc::string data; |
||||
file_desc->CopyTo(&file_desc_proto); |
||||
file_desc_proto.SerializeToString(&data); |
||||
response->mutable_file_descriptor_response()->add_file_descriptor_proto(data); |
||||
|
||||
for (int i = 0; i < file_desc->dependency_count(); ++i) { |
||||
FillFileDescriptorResponse(file_desc->dependency(i), response, seen_files); |
||||
} |
||||
} |
||||
|
||||
} // namespace grpc
|
@ -0,0 +1,94 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015, 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. |
||||
* |
||||
*/ |
||||
#ifndef GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H |
||||
#define GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H |
||||
|
||||
#include <unordered_set> |
||||
#include <vector> |
||||
|
||||
#include <grpc++/ext/reflection.grpc.pb.h> |
||||
#include <grpc++/grpc++.h> |
||||
|
||||
namespace grpc { |
||||
|
||||
class ProtoServerReflection GRPC_FINAL |
||||
: public reflection::v1alpha::ServerReflection::Service { |
||||
public: |
||||
ProtoServerReflection(); |
||||
|
||||
// Add the full names of registered services
|
||||
void SetServiceList(const std::vector<grpc::string>* services); |
||||
|
||||
// implementation of ServerReflectionInfo(stream ServerReflectionRequest) rpc
|
||||
// in ServerReflection service
|
||||
Status ServerReflectionInfo( |
||||
ServerContext* context, |
||||
ServerReaderWriter<reflection::v1alpha::ServerReflectionResponse, |
||||
reflection::v1alpha::ServerReflectionRequest>* stream) |
||||
GRPC_OVERRIDE; |
||||
|
||||
private: |
||||
Status ListService(ServerContext* context, |
||||
reflection::v1alpha::ListServiceResponse* response); |
||||
|
||||
Status GetFileByName(ServerContext* context, const grpc::string& file_name, |
||||
reflection::v1alpha::ServerReflectionResponse* response); |
||||
|
||||
Status GetFileContainingSymbol( |
||||
ServerContext* context, const grpc::string& symbol, |
||||
reflection::v1alpha::ServerReflectionResponse* response); |
||||
|
||||
Status GetFileContainingExtension( |
||||
ServerContext* context, |
||||
const reflection::v1alpha::ExtensionRequest* request, |
||||
reflection::v1alpha::ServerReflectionResponse* response); |
||||
|
||||
Status GetAllExtensionNumbers( |
||||
ServerContext* context, const grpc::string& type, |
||||
reflection::v1alpha::ExtensionNumberResponse* response); |
||||
|
||||
void FillFileDescriptorResponse( |
||||
const protobuf::FileDescriptor* file_desc, |
||||
reflection::v1alpha::ServerReflectionResponse* response, |
||||
std::unordered_set<grpc::string>* seen_files); |
||||
|
||||
void FillErrorResponse(const Status& status, |
||||
reflection::v1alpha::ErrorResponse* error_response); |
||||
|
||||
const protobuf::DescriptorPool* descriptor_pool_; |
||||
const std::vector<string>* services_; |
||||
}; |
||||
|
||||
} // namespace grpc
|
||||
|
||||
#endif // GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H
|
@ -0,0 +1,97 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015, 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. |
||||
* |
||||
*/ |
||||
|
||||
#include <grpc++/ext/proto_server_reflection_plugin.h> |
||||
#include <grpc++/impl/server_builder_plugin.h> |
||||
#include <grpc++/impl/server_initializer.h> |
||||
#include <grpc++/server.h> |
||||
|
||||
#include "src/cpp/ext/proto_server_reflection.h" |
||||
|
||||
namespace grpc { |
||||
namespace reflection { |
||||
|
||||
ProtoServerReflectionPlugin::ProtoServerReflectionPlugin() |
||||
: reflection_service_(new grpc::ProtoServerReflection()) {} |
||||
|
||||
grpc::string ProtoServerReflectionPlugin::name() { |
||||
return "proto_server_reflection"; |
||||
} |
||||
|
||||
void ProtoServerReflectionPlugin::InitServer(grpc::ServerInitializer* si) { |
||||
si->RegisterService(reflection_service_); |
||||
} |
||||
|
||||
void ProtoServerReflectionPlugin::Finish(grpc::ServerInitializer* si) { |
||||
reflection_service_->SetServiceList(si->GetServiceList()); |
||||
} |
||||
|
||||
void ProtoServerReflectionPlugin::ChangeArguments(const grpc::string& name, |
||||
void* value) {} |
||||
|
||||
bool ProtoServerReflectionPlugin::has_sync_methods() const { |
||||
if (reflection_service_ != nullptr) { |
||||
return reflection_service_->has_synchronous_methods(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
bool ProtoServerReflectionPlugin::has_async_methods() const { |
||||
if (reflection_service_ != nullptr) { |
||||
return reflection_service_->has_async_methods(); |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
static std::unique_ptr<::grpc::ServerBuilderPlugin> CreateProtoReflection() { |
||||
return std::unique_ptr<::grpc::ServerBuilderPlugin>( |
||||
new ProtoServerReflectionPlugin()); |
||||
} |
||||
|
||||
void InitProtoReflectionServerBuilderPlugin() { |
||||
static bool already_here = false; |
||||
if (already_here) return; |
||||
already_here = true; |
||||
::grpc::ServerBuilder::InternalAddPluginFactory(&CreateProtoReflection); |
||||
} |
||||
|
||||
// Force InitProtoReflectionServerBuilderPlugin() to be called at static
|
||||
// initialization time.
|
||||
struct StaticProtoReflectionPluginInitializer { |
||||
StaticProtoReflectionPluginInitializer() { |
||||
InitProtoReflectionServerBuilderPlugin(); |
||||
} |
||||
} static_proto_reflection_plugin_initializer; |
||||
|
||||
} // namespace reflection
|
||||
} // namespace grpc
|
@ -0,0 +1,97 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015, 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. |
||||
* |
||||
*/ |
||||
|
||||
|
||||
// Generated by the gRPC protobuf plugin.
|
||||
// If you make any local change, they will be lost.
|
||||
// source: reflection.proto
|
||||
|
||||
#include <grpc++/ext/reflection.pb.h> |
||||
#include <grpc++/ext/reflection.grpc.pb.h> |
||||
|
||||
#include <grpc++/impl/codegen/async_stream.h> |
||||
#include <grpc++/impl/codegen/async_unary_call.h> |
||||
#include <grpc++/impl/codegen/channel_interface.h> |
||||
#include <grpc++/impl/codegen/client_unary_call.h> |
||||
#include <grpc++/impl/codegen/method_handler_impl.h> |
||||
#include <grpc++/impl/codegen/rpc_service_method.h> |
||||
#include <grpc++/impl/codegen/service_type.h> |
||||
#include <grpc++/impl/codegen/sync_stream.h> |
||||
namespace grpc { |
||||
namespace reflection { |
||||
namespace v1alpha { |
||||
|
||||
static const char* ServerReflection_method_names[] = { |
||||
"/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", |
||||
}; |
||||
|
||||
std::unique_ptr< ServerReflection::Stub> ServerReflection::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { |
||||
std::unique_ptr< ServerReflection::Stub> stub(new ServerReflection::Stub(channel)); |
||||
return stub; |
||||
} |
||||
|
||||
ServerReflection::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) |
||||
: channel_(channel), rpcmethod_ServerReflectionInfo_(ServerReflection_method_names[0], ::grpc::RpcMethod::BIDI_STREAMING, channel) |
||||
{} |
||||
|
||||
::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* ServerReflection::Stub::ServerReflectionInfoRaw(::grpc::ClientContext* context) { |
||||
return new ::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>(channel_.get(), rpcmethod_ServerReflectionInfo_, context); |
||||
} |
||||
|
||||
::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* ServerReflection::Stub::AsyncServerReflectionInfoRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { |
||||
return new ::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>(channel_.get(), cq, rpcmethod_ServerReflectionInfo_, context, tag); |
||||
} |
||||
|
||||
ServerReflection::Service::Service() { |
||||
(void)ServerReflection_method_names; |
||||
AddMethod(new ::grpc::RpcServiceMethod( |
||||
ServerReflection_method_names[0], |
||||
::grpc::RpcMethod::BIDI_STREAMING, |
||||
new ::grpc::BidiStreamingHandler< ServerReflection::Service, ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>( |
||||
std::mem_fn(&ServerReflection::Service::ServerReflectionInfo), this))); |
||||
} |
||||
|
||||
ServerReflection::Service::~Service() { |
||||
} |
||||
|
||||
::grpc::Status ServerReflection::Service::ServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream) { |
||||
(void) context; |
||||
(void) stream; |
||||
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); |
||||
} |
||||
|
||||
|
||||
} // namespace grpc
|
||||
} // namespace reflection
|
||||
} // namespace v1alpha
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,59 @@ |
||||
#region Copyright notice and license |
||||
|
||||
// Copyright 2015, 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. |
||||
|
||||
#endregion |
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
|
||||
namespace Grpc.Core.Logging |
||||
{ |
||||
/// <summary>Standard logging levels.</summary> |
||||
public enum LogLevel |
||||
{ |
||||
/// <summary> |
||||
/// Debug severity. |
||||
/// </summary> |
||||
Debug = 0, |
||||
/// <summary> |
||||
/// Info severity. |
||||
/// </summary> |
||||
Info, |
||||
/// <summary> |
||||
/// Warning severity. |
||||
/// </summary> |
||||
Warning, |
||||
/// <summary> |
||||
/// Error severity. |
||||
/// </summary> |
||||
Error |
||||
} |
||||
} |
@ -0,0 +1,160 @@ |
||||
#region Copyright notice and license |
||||
|
||||
// Copyright 2015, 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. |
||||
|
||||
#endregion |
||||
|
||||
using System; |
||||
using System.Collections.Generic; |
||||
using System.Globalization; |
||||
using System.IO; |
||||
using Grpc.Core.Utils; |
||||
|
||||
namespace Grpc.Core.Logging |
||||
{ |
||||
/// <summary>Logger that filters out messages below certain log level.</summary> |
||||
public class LogLevelFilterLogger : ILogger |
||||
{ |
||||
readonly ILogger innerLogger; |
||||
readonly LogLevel logLevel; |
||||
|
||||
/// <summary> |
||||
/// Creates and instance of <c>LogLevelFilter.</c> |
||||
/// </summary> |
||||
public LogLevelFilterLogger(ILogger logger, LogLevel logLevel) |
||||
{ |
||||
this.innerLogger = GrpcPreconditions.CheckNotNull(logger); |
||||
this.logLevel = logLevel; |
||||
} |
||||
|
||||
/// <summary> |
||||
/// Returns a logger associated with the specified type. |
||||
/// </summary> |
||||
public virtual ILogger ForType<T>() |
||||
{ |
||||
var newInnerLogger = innerLogger.ForType<T>(); |
||||
if (object.ReferenceEquals(this.innerLogger, newInnerLogger)) |
||||
{ |
||||
return this; |
||||
} |
||||
return new LogLevelFilterLogger(newInnerLogger, logLevel); |
||||
} |
||||
|
||||
/// <summary>Logs a message with severity Debug.</summary> |
||||
public void Debug(string message) |
||||
{ |
||||
if (logLevel <= LogLevel.Debug) |
||||
{ |
||||
innerLogger.Debug(message); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a formatted message with severity Debug.</summary> |
||||
public void Debug(string format, params object[] formatArgs) |
||||
{ |
||||
if (logLevel <= LogLevel.Debug) |
||||
{ |
||||
innerLogger.Debug(format, formatArgs); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a message with severity Info.</summary> |
||||
public void Info(string message) |
||||
{ |
||||
if (logLevel <= LogLevel.Info) |
||||
{ |
||||
innerLogger.Info(message); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a formatted message with severity Info.</summary> |
||||
public void Info(string format, params object[] formatArgs) |
||||
{ |
||||
if (logLevel <= LogLevel.Info) |
||||
{ |
||||
innerLogger.Info(format, formatArgs); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a message with severity Warning.</summary> |
||||
public void Warning(string message) |
||||
{ |
||||
if (logLevel <= LogLevel.Warning) |
||||
{ |
||||
innerLogger.Warning(message); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a formatted message with severity Warning.</summary> |
||||
public void Warning(string format, params object[] formatArgs) |
||||
{ |
||||
if (logLevel <= LogLevel.Warning) |
||||
{ |
||||
innerLogger.Warning(format, formatArgs); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a message and an associated exception with severity Warning.</summary> |
||||
public void Warning(Exception exception, string message) |
||||
{ |
||||
if (logLevel <= LogLevel.Warning) |
||||
{ |
||||
innerLogger.Warning(exception, message); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a message with severity Error.</summary> |
||||
public void Error(string message) |
||||
{ |
||||
if (logLevel <= LogLevel.Error) |
||||
{ |
||||
innerLogger.Error(message); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a formatted message with severity Error.</summary> |
||||
public void Error(string format, params object[] formatArgs) |
||||
{ |
||||
if (logLevel <= LogLevel.Error) |
||||
{ |
||||
innerLogger.Error(format, formatArgs); |
||||
} |
||||
} |
||||
|
||||
/// <summary>Logs a message and an associated exception with severity Error.</summary> |
||||
public void Error(Exception exception, string message) |
||||
{ |
||||
if (logLevel <= LogLevel.Error) |
||||
{ |
||||
innerLogger.Error(exception, message); |
||||
} |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,583 @@ |
||||
# Copyright 2015, 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. |
||||
|
||||
import collections |
||||
from concurrent import futures |
||||
import contextlib |
||||
import distutils.spawn |
||||
import errno |
||||
import os |
||||
import shutil |
||||
import subprocess |
||||
import sys |
||||
import tempfile |
||||
import threading |
||||
import unittest |
||||
|
||||
from six import moves |
||||
|
||||
import grpc |
||||
from tests.unit.framework.common import test_constants |
||||
|
||||
# Identifiers of entities we expect to find in the generated module. |
||||
STUB_IDENTIFIER = 'TestServiceStub' |
||||
SERVICER_IDENTIFIER = 'TestServiceServicer' |
||||
ADD_SERVICER_TO_SERVER_IDENTIFIER = 'add_TestServiceServicer_to_server' |
||||
|
||||
|
||||
class _ServicerMethods(object): |
||||
|
||||
def __init__(self, response_pb2, payload_pb2): |
||||
self._condition = threading.Condition() |
||||
self._paused = False |
||||
self._fail = False |
||||
self._response_pb2 = response_pb2 |
||||
self._payload_pb2 = payload_pb2 |
||||
|
||||
@contextlib.contextmanager |
||||
def pause(self): # pylint: disable=invalid-name |
||||
with self._condition: |
||||
self._paused = True |
||||
yield |
||||
with self._condition: |
||||
self._paused = False |
||||
self._condition.notify_all() |
||||
|
||||
@contextlib.contextmanager |
||||
def fail(self): # pylint: disable=invalid-name |
||||
with self._condition: |
||||
self._fail = True |
||||
yield |
||||
with self._condition: |
||||
self._fail = False |
||||
|
||||
def _control(self): # pylint: disable=invalid-name |
||||
with self._condition: |
||||
if self._fail: |
||||
raise ValueError() |
||||
while self._paused: |
||||
self._condition.wait() |
||||
|
||||
def UnaryCall(self, request, unused_rpc_context): |
||||
response = self._response_pb2.SimpleResponse() |
||||
response.payload.payload_type = self._payload_pb2.COMPRESSABLE |
||||
response.payload.payload_compressable = 'a' * request.response_size |
||||
self._control() |
||||
return response |
||||
|
||||
def StreamingOutputCall(self, request, unused_rpc_context): |
||||
for parameter in request.response_parameters: |
||||
response = self._response_pb2.StreamingOutputCallResponse() |
||||
response.payload.payload_type = self._payload_pb2.COMPRESSABLE |
||||
response.payload.payload_compressable = 'a' * parameter.size |
||||
self._control() |
||||
yield response |
||||
|
||||
def StreamingInputCall(self, request_iter, unused_rpc_context): |
||||
response = self._response_pb2.StreamingInputCallResponse() |
||||
aggregated_payload_size = 0 |
||||
for request in request_iter: |
||||
aggregated_payload_size += len(request.payload.payload_compressable) |
||||
response.aggregated_payload_size = aggregated_payload_size |
||||
self._control() |
||||
return response |
||||
|
||||
def FullDuplexCall(self, request_iter, unused_rpc_context): |
||||
for request in request_iter: |
||||
for parameter in request.response_parameters: |
||||
response = self._response_pb2.StreamingOutputCallResponse() |
||||
response.payload.payload_type = self._payload_pb2.COMPRESSABLE |
||||
response.payload.payload_compressable = 'a' * parameter.size |
||||
self._control() |
||||
yield response |
||||
|
||||
def HalfDuplexCall(self, request_iter, unused_rpc_context): |
||||
responses = [] |
||||
for request in request_iter: |
||||
for parameter in request.response_parameters: |
||||
response = self._response_pb2.StreamingOutputCallResponse() |
||||
response.payload.payload_type = self._payload_pb2.COMPRESSABLE |
||||
response.payload.payload_compressable = 'a' * parameter.size |
||||
self._control() |
||||
responses.append(response) |
||||
for response in responses: |
||||
yield response |
||||
|
||||
|
||||
class _Service( |
||||
collections.namedtuple( |
||||
'_Service', ('servicer_methods', 'server', 'stub',))): |
||||
"""A live and running service. |
||||
|
||||
Attributes: |
||||
servicer_methods: The _ServicerMethods servicing RPCs. |
||||
server: The grpc.Server servicing RPCs. |
||||
stub: A stub on which to invoke RPCs. |
||||
""" |
||||
|
||||
|
||||
def _CreateService(service_pb2, response_pb2, payload_pb2): |
||||
"""Provides a servicer backend and a stub. |
||||
|
||||
Args: |
||||
service_pb2: The service_pb2 module generated by this test. |
||||
response_pb2: The response_pb2 module generated by this test. |
||||
payload_pb2: The payload_pb2 module generated by this test. |
||||
|
||||
Returns: |
||||
A _Service with which to test RPCs. |
||||
""" |
||||
servicer_methods = _ServicerMethods(response_pb2, payload_pb2) |
||||
|
||||
class Servicer(getattr(service_pb2, SERVICER_IDENTIFIER)): |
||||
|
||||
def UnaryCall(self, request, context): |
||||
return servicer_methods.UnaryCall(request, context) |
||||
|
||||
def StreamingOutputCall(self, request, context): |
||||
return servicer_methods.StreamingOutputCall(request, context) |
||||
|
||||
def StreamingInputCall(self, request_iter, context): |
||||
return servicer_methods.StreamingInputCall(request_iter, context) |
||||
|
||||
def FullDuplexCall(self, request_iter, context): |
||||
return servicer_methods.FullDuplexCall(request_iter, context) |
||||
|
||||
def HalfDuplexCall(self, request_iter, context): |
||||
return servicer_methods.HalfDuplexCall(request_iter, context) |
||||
|
||||
server = grpc.server( |
||||
(), futures.ThreadPoolExecutor(max_workers=test_constants.POOL_SIZE)) |
||||
getattr(service_pb2, ADD_SERVICER_TO_SERVER_IDENTIFIER)(Servicer(), server) |
||||
port = server.add_insecure_port('[::]:0') |
||||
server.start() |
||||
channel = grpc.insecure_channel('localhost:{}'.format(port)) |
||||
stub = getattr(service_pb2, STUB_IDENTIFIER)(channel) |
||||
return _Service(servicer_methods, server, stub) |
||||
|
||||
|
||||
def _CreateIncompleteService(service_pb2): |
||||
"""Provides a servicer backend that fails to implement methods and its stub. |
||||
|
||||
Args: |
||||
service_pb2: The service_pb2 module generated by this test. |
||||
|
||||
Returns: |
||||
A _Service with which to test RPCs. The returned _Service's |
||||
servicer_methods implements none of the methods required of it. |
||||
""" |
||||
|
||||
class Servicer(getattr(service_pb2, SERVICER_IDENTIFIER)): |
||||
pass |
||||
|
||||
server = grpc.server( |
||||
(), futures.ThreadPoolExecutor(max_workers=test_constants.POOL_SIZE)) |
||||
getattr(service_pb2, ADD_SERVICER_TO_SERVER_IDENTIFIER)(Servicer(), server) |
||||
port = server.add_insecure_port('[::]:0') |
||||
server.start() |
||||
channel = grpc.insecure_channel('localhost:{}'.format(port)) |
||||
stub = getattr(service_pb2, STUB_IDENTIFIER)(channel) |
||||
return _Service(None, server, stub) |
||||
|
||||
|
||||
def _streaming_input_request_iterator(request_pb2, payload_pb2): |
||||
for _ in range(3): |
||||
request = request_pb2.StreamingInputCallRequest() |
||||
request.payload.payload_type = payload_pb2.COMPRESSABLE |
||||
request.payload.payload_compressable = 'a' |
||||
yield request |
||||
|
||||
|
||||
def _streaming_output_request(request_pb2): |
||||
request = request_pb2.StreamingOutputCallRequest() |
||||
sizes = [1, 2, 3] |
||||
request.response_parameters.add(size=sizes[0], interval_us=0) |
||||
request.response_parameters.add(size=sizes[1], interval_us=0) |
||||
request.response_parameters.add(size=sizes[2], interval_us=0) |
||||
return request |
||||
|
||||
|
||||
def _full_duplex_request_iterator(request_pb2): |
||||
request = request_pb2.StreamingOutputCallRequest() |
||||
request.response_parameters.add(size=1, interval_us=0) |
||||
yield request |
||||
request = request_pb2.StreamingOutputCallRequest() |
||||
request.response_parameters.add(size=2, interval_us=0) |
||||
request.response_parameters.add(size=3, interval_us=0) |
||||
yield request |
||||
|
||||
|
||||
class PythonPluginTest(unittest.TestCase): |
||||
"""Test case for the gRPC Python protoc-plugin. |
||||
|
||||
While reading these tests, remember that the futures API |
||||
(`stub.method.future()`) only gives futures for the *response-unary* |
||||
methods and does not exist for response-streaming methods. |
||||
""" |
||||
|
||||
def setUp(self): |
||||
# Assume that the appropriate protoc and grpc_python_plugins are on the |
||||
# path. |
||||
protoc_command = 'protoc' |
||||
protoc_plugin_filename = distutils.spawn.find_executable( |
||||
'grpc_python_plugin') |
||||
if not os.path.isfile(protoc_command): |
||||
# Assume that if we haven't built protoc that it's on the system. |
||||
protoc_command = 'protoc' |
||||
|
||||
# Ensure that the output directory exists. |
||||
self.outdir = tempfile.mkdtemp() |
||||
|
||||
# Find all proto files |
||||
paths = [] |
||||
root_dir = os.path.dirname(os.path.realpath(__file__)) |
||||
proto_dir = os.path.join(root_dir, 'protos') |
||||
for walk_root, _, filenames in os.walk(proto_dir): |
||||
for filename in filenames: |
||||
if filename.endswith('.proto'): |
||||
path = os.path.join(walk_root, filename) |
||||
paths.append(path) |
||||
|
||||
# Invoke protoc with the plugin. |
||||
cmd = [ |
||||
protoc_command, |
||||
'--plugin=protoc-gen-python-grpc=%s' % protoc_plugin_filename, |
||||
'-I %s' % root_dir, |
||||
'--python_out=%s' % self.outdir, |
||||
'--python-grpc_out=%s' % self.outdir |
||||
] + paths |
||||
subprocess.check_call(' '.join(cmd), shell=True, env=os.environ, |
||||
cwd=os.path.dirname(os.path.realpath(__file__))) |
||||
|
||||
# Generated proto directories dont include __init__.py, but |
||||
# these are needed for python package resolution |
||||
for walk_root, _, _ in os.walk(os.path.join(self.outdir, 'protos')): |
||||
path = os.path.join(walk_root, '__init__.py') |
||||
open(path, 'a').close() |
||||
|
||||
sys.path.insert(0, self.outdir) |
||||
|
||||
import protos.payload.test_payload_pb2 as payload_pb2 |
||||
import protos.requests.r.test_requests_pb2 as request_pb2 |
||||
import protos.responses.test_responses_pb2 as response_pb2 |
||||
import protos.service.test_service_pb2 as service_pb2 |
||||
self._payload_pb2 = payload_pb2 |
||||
self._request_pb2 = request_pb2 |
||||
self._response_pb2 = response_pb2 |
||||
self._service_pb2 = service_pb2 |
||||
|
||||
def tearDown(self): |
||||
try: |
||||
shutil.rmtree(self.outdir) |
||||
except OSError as exc: |
||||
if exc.errno != errno.ENOENT: |
||||
raise |
||||
sys.path.remove(self.outdir) |
||||
|
||||
def testImportAttributes(self): |
||||
# check that we can access the generated module and its members. |
||||
self.assertIsNotNone( |
||||
getattr(self._service_pb2, STUB_IDENTIFIER, None)) |
||||
self.assertIsNotNone( |
||||
getattr(self._service_pb2, SERVICER_IDENTIFIER, None)) |
||||
self.assertIsNotNone( |
||||
getattr(self._service_pb2, ADD_SERVICER_TO_SERVER_IDENTIFIER, None)) |
||||
|
||||
def testUpDown(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
self.assertIsNotNone(service.servicer_methods) |
||||
self.assertIsNotNone(service.server) |
||||
self.assertIsNotNone(service.stub) |
||||
|
||||
def testIncompleteServicer(self): |
||||
service = _CreateIncompleteService(self._service_pb2) |
||||
request = self._request_pb2.SimpleRequest(response_size=13) |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
service.stub.UnaryCall(request) |
||||
self.assertIs( |
||||
exception_context.exception.code(), grpc.StatusCode.UNIMPLEMENTED) |
||||
|
||||
def testUnaryCall(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = self._request_pb2.SimpleRequest(response_size=13) |
||||
response = service.stub.UnaryCall(request) |
||||
expected_response = service.servicer_methods.UnaryCall( |
||||
request, 'not a real context!') |
||||
self.assertEqual(expected_response, response) |
||||
|
||||
def testUnaryCallFuture(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = self._request_pb2.SimpleRequest(response_size=13) |
||||
# Check that the call does not block waiting for the server to respond. |
||||
with service.servicer_methods.pause(): |
||||
response_future = service.stub.UnaryCall.future(request) |
||||
response = response_future.result() |
||||
expected_response = service.servicer_methods.UnaryCall( |
||||
request, 'not a real RpcContext!') |
||||
self.assertEqual(expected_response, response) |
||||
|
||||
def testUnaryCallFutureExpired(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = self._request_pb2.SimpleRequest(response_size=13) |
||||
with service.servicer_methods.pause(): |
||||
response_future = service.stub.UnaryCall.future( |
||||
request, timeout=test_constants.SHORT_TIMEOUT) |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
response_future.result() |
||||
self.assertIs( |
||||
exception_context.exception.code(), grpc.StatusCode.DEADLINE_EXCEEDED) |
||||
self.assertIs(response_future.code(), grpc.StatusCode.DEADLINE_EXCEEDED) |
||||
|
||||
def testUnaryCallFutureCancelled(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = self._request_pb2.SimpleRequest(response_size=13) |
||||
with service.servicer_methods.pause(): |
||||
response_future = service.stub.UnaryCall.future(request) |
||||
response_future.cancel() |
||||
self.assertTrue(response_future.cancelled()) |
||||
self.assertIs(response_future.code(), grpc.StatusCode.CANCELLED) |
||||
|
||||
def testUnaryCallFutureFailed(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = self._request_pb2.SimpleRequest(response_size=13) |
||||
with service.servicer_methods.fail(): |
||||
response_future = service.stub.UnaryCall.future(request) |
||||
self.assertIsNotNone(response_future.exception()) |
||||
self.assertIs(response_future.code(), grpc.StatusCode.UNKNOWN) |
||||
|
||||
def testStreamingOutputCall(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = _streaming_output_request(self._request_pb2) |
||||
responses = service.stub.StreamingOutputCall(request) |
||||
expected_responses = service.servicer_methods.StreamingOutputCall( |
||||
request, 'not a real RpcContext!') |
||||
for expected_response, response in moves.zip_longest( |
||||
expected_responses, responses): |
||||
self.assertEqual(expected_response, response) |
||||
|
||||
def testStreamingOutputCallExpired(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = _streaming_output_request(self._request_pb2) |
||||
with service.servicer_methods.pause(): |
||||
responses = service.stub.StreamingOutputCall( |
||||
request, timeout=test_constants.SHORT_TIMEOUT) |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
list(responses) |
||||
self.assertIs( |
||||
exception_context.exception.code(), grpc.StatusCode.DEADLINE_EXCEEDED) |
||||
|
||||
def testStreamingOutputCallCancelled(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = _streaming_output_request(self._request_pb2) |
||||
responses = service.stub.StreamingOutputCall(request) |
||||
next(responses) |
||||
responses.cancel() |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
next(responses) |
||||
self.assertIs(responses.code(), grpc.StatusCode.CANCELLED) |
||||
|
||||
def testStreamingOutputCallFailed(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request = _streaming_output_request(self._request_pb2) |
||||
with service.servicer_methods.fail(): |
||||
responses = service.stub.StreamingOutputCall(request) |
||||
self.assertIsNotNone(responses) |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
next(responses) |
||||
self.assertIs(exception_context.exception.code(), grpc.StatusCode.UNKNOWN) |
||||
|
||||
def testStreamingInputCall(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
response = service.stub.StreamingInputCall( |
||||
_streaming_input_request_iterator( |
||||
self._request_pb2, self._payload_pb2)) |
||||
expected_response = service.servicer_methods.StreamingInputCall( |
||||
_streaming_input_request_iterator(self._request_pb2, self._payload_pb2), |
||||
'not a real RpcContext!') |
||||
self.assertEqual(expected_response, response) |
||||
|
||||
def testStreamingInputCallFuture(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
with service.servicer_methods.pause(): |
||||
response_future = service.stub.StreamingInputCall.future( |
||||
_streaming_input_request_iterator( |
||||
self._request_pb2, self._payload_pb2)) |
||||
response = response_future.result() |
||||
expected_response = service.servicer_methods.StreamingInputCall( |
||||
_streaming_input_request_iterator(self._request_pb2, self._payload_pb2), |
||||
'not a real RpcContext!') |
||||
self.assertEqual(expected_response, response) |
||||
|
||||
def testStreamingInputCallFutureExpired(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
with service.servicer_methods.pause(): |
||||
response_future = service.stub.StreamingInputCall.future( |
||||
_streaming_input_request_iterator( |
||||
self._request_pb2, self._payload_pb2), |
||||
timeout=test_constants.SHORT_TIMEOUT) |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
response_future.result() |
||||
self.assertIsInstance(response_future.exception(), grpc.RpcError) |
||||
self.assertIs( |
||||
response_future.exception().code(), grpc.StatusCode.DEADLINE_EXCEEDED) |
||||
self.assertIs( |
||||
exception_context.exception.code(), grpc.StatusCode.DEADLINE_EXCEEDED) |
||||
|
||||
def testStreamingInputCallFutureCancelled(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
with service.servicer_methods.pause(): |
||||
response_future = service.stub.StreamingInputCall.future( |
||||
_streaming_input_request_iterator( |
||||
self._request_pb2, self._payload_pb2)) |
||||
response_future.cancel() |
||||
self.assertTrue(response_future.cancelled()) |
||||
with self.assertRaises(grpc.FutureCancelledError): |
||||
response_future.result() |
||||
|
||||
def testStreamingInputCallFutureFailed(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
with service.servicer_methods.fail(): |
||||
response_future = service.stub.StreamingInputCall.future( |
||||
_streaming_input_request_iterator( |
||||
self._request_pb2, self._payload_pb2)) |
||||
self.assertIsNotNone(response_future.exception()) |
||||
self.assertIs(response_future.code(), grpc.StatusCode.UNKNOWN) |
||||
|
||||
def testFullDuplexCall(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
responses = service.stub.FullDuplexCall( |
||||
_full_duplex_request_iterator(self._request_pb2)) |
||||
expected_responses = service.servicer_methods.FullDuplexCall( |
||||
_full_duplex_request_iterator(self._request_pb2), |
||||
'not a real RpcContext!') |
||||
for expected_response, response in moves.zip_longest( |
||||
expected_responses, responses): |
||||
self.assertEqual(expected_response, response) |
||||
|
||||
def testFullDuplexCallExpired(self): |
||||
request_iterator = _full_duplex_request_iterator(self._request_pb2) |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
with service.servicer_methods.pause(): |
||||
responses = service.stub.FullDuplexCall( |
||||
request_iterator, timeout=test_constants.SHORT_TIMEOUT) |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
list(responses) |
||||
self.assertIs( |
||||
exception_context.exception.code(), grpc.StatusCode.DEADLINE_EXCEEDED) |
||||
|
||||
def testFullDuplexCallCancelled(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
request_iterator = _full_duplex_request_iterator(self._request_pb2) |
||||
responses = service.stub.FullDuplexCall(request_iterator) |
||||
next(responses) |
||||
responses.cancel() |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
next(responses) |
||||
self.assertIs( |
||||
exception_context.exception.code(), grpc.StatusCode.CANCELLED) |
||||
|
||||
def testFullDuplexCallFailed(self): |
||||
request_iterator = _full_duplex_request_iterator(self._request_pb2) |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
with service.servicer_methods.fail(): |
||||
responses = service.stub.FullDuplexCall(request_iterator) |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
next(responses) |
||||
self.assertIs(exception_context.exception.code(), grpc.StatusCode.UNKNOWN) |
||||
|
||||
def testHalfDuplexCall(self): |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
def half_duplex_request_iterator(): |
||||
request = self._request_pb2.StreamingOutputCallRequest() |
||||
request.response_parameters.add(size=1, interval_us=0) |
||||
yield request |
||||
request = self._request_pb2.StreamingOutputCallRequest() |
||||
request.response_parameters.add(size=2, interval_us=0) |
||||
request.response_parameters.add(size=3, interval_us=0) |
||||
yield request |
||||
responses = service.stub.HalfDuplexCall(half_duplex_request_iterator()) |
||||
expected_responses = service.servicer_methods.HalfDuplexCall( |
||||
half_duplex_request_iterator(), 'not a real RpcContext!') |
||||
for expected_response, response in moves.zip_longest( |
||||
expected_responses, responses): |
||||
self.assertEqual(expected_response, response) |
||||
|
||||
def testHalfDuplexCallWedged(self): |
||||
condition = threading.Condition() |
||||
wait_cell = [False] |
||||
@contextlib.contextmanager |
||||
def wait(): # pylint: disable=invalid-name |
||||
# Where's Python 3's 'nonlocal' statement when you need it? |
||||
with condition: |
||||
wait_cell[0] = True |
||||
yield |
||||
with condition: |
||||
wait_cell[0] = False |
||||
condition.notify_all() |
||||
def half_duplex_request_iterator(): |
||||
request = self._request_pb2.StreamingOutputCallRequest() |
||||
request.response_parameters.add(size=1, interval_us=0) |
||||
yield request |
||||
with condition: |
||||
while wait_cell[0]: |
||||
condition.wait() |
||||
service = _CreateService( |
||||
self._service_pb2, self._response_pb2, self._payload_pb2) |
||||
with wait(): |
||||
responses = service.stub.HalfDuplexCall( |
||||
half_duplex_request_iterator(), timeout=test_constants.SHORT_TIMEOUT) |
||||
# half-duplex waits for the client to send all info |
||||
with self.assertRaises(grpc.RpcError) as exception_context: |
||||
next(responses) |
||||
self.assertIs( |
||||
exception_context.exception.code(), grpc.StatusCode.DEADLINE_EXCEEDED) |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
unittest.main(verbosity=2) |
@ -0,0 +1,117 @@ |
||||
# Copyright 2016, 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. |
||||
"""Tests for CleanupThread.""" |
||||
|
||||
import threading |
||||
import time |
||||
import unittest |
||||
|
||||
from grpc import _common |
||||
|
||||
_SHORT_TIME = 0.5 |
||||
_LONG_TIME = 2.0 |
||||
_EPSILON = 0.1 |
||||
|
||||
|
||||
def cleanup(timeout): |
||||
if timeout is not None: |
||||
time.sleep(timeout) |
||||
else: |
||||
time.sleep(_LONG_TIME) |
||||
|
||||
|
||||
def slow_cleanup(timeout): |
||||
# Don't respect timeout |
||||
time.sleep(_LONG_TIME) |
||||
|
||||
|
||||
class CleanupThreadTest(unittest.TestCase): |
||||
|
||||
def testTargetInvocation(self): |
||||
event = threading.Event() |
||||
def target(arg1, arg2, arg3=None): |
||||
self.assertEqual('arg1', arg1) |
||||
self.assertEqual('arg2', arg2) |
||||
self.assertEqual('arg3', arg3) |
||||
event.set() |
||||
|
||||
cleanup_thread = _common.CleanupThread(behavior=lambda x: None, |
||||
target=target, name='test-name', |
||||
args=('arg1', 'arg2'), kwargs={'arg3': 'arg3'}) |
||||
cleanup_thread.start() |
||||
cleanup_thread.join() |
||||
self.assertEqual(cleanup_thread.name, 'test-name') |
||||
self.assertTrue(event.is_set()) |
||||
|
||||
def testJoinNoTimeout(self): |
||||
cleanup_thread = _common.CleanupThread(behavior=cleanup) |
||||
cleanup_thread.start() |
||||
start_time = time.time() |
||||
cleanup_thread.join() |
||||
end_time = time.time() |
||||
self.assertAlmostEqual(_LONG_TIME, end_time - start_time, delta=_EPSILON) |
||||
|
||||
def testJoinTimeout(self): |
||||
cleanup_thread = _common.CleanupThread(behavior=cleanup) |
||||
cleanup_thread.start() |
||||
start_time = time.time() |
||||
cleanup_thread.join(_SHORT_TIME) |
||||
end_time = time.time() |
||||
self.assertAlmostEqual(_SHORT_TIME, end_time - start_time, delta=_EPSILON) |
||||
|
||||
def testJoinTimeoutSlowBehavior(self): |
||||
cleanup_thread = _common.CleanupThread(behavior=slow_cleanup) |
||||
cleanup_thread.start() |
||||
start_time = time.time() |
||||
cleanup_thread.join(_SHORT_TIME) |
||||
end_time = time.time() |
||||
self.assertAlmostEqual(_LONG_TIME, end_time - start_time, delta=_EPSILON) |
||||
|
||||
def testJoinTimeoutSlowTarget(self): |
||||
event = threading.Event() |
||||
def target(): |
||||
event.wait(_LONG_TIME) |
||||
cleanup_thread = _common.CleanupThread(behavior=cleanup, target=target) |
||||
cleanup_thread.start() |
||||
start_time = time.time() |
||||
cleanup_thread.join(_SHORT_TIME) |
||||
end_time = time.time() |
||||
self.assertAlmostEqual(_SHORT_TIME, end_time - start_time, delta=_EPSILON) |
||||
event.set() |
||||
|
||||
def testJoinZeroTimeout(self): |
||||
cleanup_thread = _common.CleanupThread(behavior=cleanup) |
||||
cleanup_thread.start() |
||||
start_time = time.time() |
||||
cleanup_thread.join(0) |
||||
end_time = time.time() |
||||
self.assertAlmostEqual(0, end_time - start_time, delta=_EPSILON) |
||||
|
||||
if __name__ == '__main__': |
||||
unittest.main(verbosity=2) |
@ -0,0 +1,144 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016, 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. |
||||
* |
||||
*/ |
||||
|
||||
#include "src/core/ext/transport/chttp2/transport/bin_decoder.h" |
||||
|
||||
#include <string.h> |
||||
|
||||
#include <grpc/support/alloc.h> |
||||
#include <grpc/support/log.h> |
||||
#include "src/core/ext/transport/chttp2/transport/bin_encoder.h" |
||||
#include "src/core/lib/support/string.h" |
||||
|
||||
static int all_ok = 1; |
||||
|
||||
static void expect_slice_eq(gpr_slice expected, gpr_slice slice, char *debug, |
||||
int line) { |
||||
if (0 != gpr_slice_cmp(slice, expected)) { |
||||
char *hs = gpr_dump_slice(slice, GPR_DUMP_HEX | GPR_DUMP_ASCII); |
||||
char *he = gpr_dump_slice(expected, GPR_DUMP_HEX | GPR_DUMP_ASCII); |
||||
gpr_log(GPR_ERROR, "FAILED:%d: %s\ngot: %s\nwant: %s", line, debug, hs, |
||||
he); |
||||
gpr_free(hs); |
||||
gpr_free(he); |
||||
all_ok = 0; |
||||
} |
||||
gpr_slice_unref(expected); |
||||
gpr_slice_unref(slice); |
||||
} |
||||
|
||||
static gpr_slice base64_encode(const char *s) { |
||||
gpr_slice ss = gpr_slice_from_copied_string(s); |
||||
gpr_slice out = grpc_chttp2_base64_encode(ss); |
||||
gpr_slice_unref(ss); |
||||
return out; |
||||
} |
||||
|
||||
static gpr_slice base64_decode(const char *s) { |
||||
gpr_slice ss = gpr_slice_from_copied_string(s); |
||||
gpr_slice out = grpc_chttp2_base64_decode(ss); |
||||
gpr_slice_unref(ss); |
||||
return out; |
||||
} |
||||
|
||||
static gpr_slice base64_decode_with_length(const char *s, |
||||
size_t output_length) { |
||||
gpr_slice ss = gpr_slice_from_copied_string(s); |
||||
gpr_slice out = grpc_chttp2_base64_decode_with_length(ss, output_length); |
||||
gpr_slice_unref(ss); |
||||
return out; |
||||
} |
||||
|
||||
#define EXPECT_SLICE_EQ(expected, slice) \ |
||||
expect_slice_eq( \
|
||||
gpr_slice_from_copied_buffer(expected, sizeof(expected) - 1), slice, \
|
||||
#slice, __LINE__); |
||||
|
||||
#define ENCODE_AND_DECODE(s) \ |
||||
EXPECT_SLICE_EQ( \
|
||||
s, grpc_chttp2_base64_decode_with_length(base64_encode(s), strlen(s))); |
||||
|
||||
int main(int argc, char **argv) { |
||||
/* ENCODE_AND_DECODE tests grpc_chttp2_base64_decode_with_length(), which
|
||||
takes encoded base64 strings without pad chars, but output length is |
||||
required. */ |
||||
/* Base64 test vectors from RFC 4648 */ |
||||
ENCODE_AND_DECODE(""); |
||||
ENCODE_AND_DECODE("f"); |
||||
ENCODE_AND_DECODE("foo"); |
||||
ENCODE_AND_DECODE("fo"); |
||||
ENCODE_AND_DECODE("foob"); |
||||
ENCODE_AND_DECODE("fooba"); |
||||
ENCODE_AND_DECODE("foobar"); |
||||
|
||||
ENCODE_AND_DECODE("\xc0\xc1\xc2\xc3\xc4\xc5"); |
||||
|
||||
/* Base64 test vectors from RFC 4648, with pad chars */ |
||||
/* BASE64("") = "" */ |
||||
EXPECT_SLICE_EQ("", base64_decode("")); |
||||
/* BASE64("f") = "Zg==" */ |
||||
EXPECT_SLICE_EQ("f", base64_decode("Zg==")); |
||||
/* BASE64("fo") = "Zm8=" */ |
||||
EXPECT_SLICE_EQ("fo", base64_decode("Zm8=")); |
||||
/* BASE64("foo") = "Zm9v" */ |
||||
EXPECT_SLICE_EQ("foo", base64_decode("Zm9v")); |
||||
/* BASE64("foob") = "Zm9vYg==" */ |
||||
EXPECT_SLICE_EQ("foob", base64_decode("Zm9vYg==")); |
||||
/* BASE64("fooba") = "Zm9vYmE=" */ |
||||
EXPECT_SLICE_EQ("fooba", base64_decode("Zm9vYmE=")); |
||||
/* BASE64("foobar") = "Zm9vYmFy" */ |
||||
EXPECT_SLICE_EQ("foobar", base64_decode("Zm9vYmFy")); |
||||
|
||||
EXPECT_SLICE_EQ("\xc0\xc1\xc2\xc3\xc4\xc5", base64_decode("wMHCw8TF")); |
||||
|
||||
// Test illegal input length in grpc_chttp2_base64_decode
|
||||
EXPECT_SLICE_EQ("", base64_decode("a")); |
||||
EXPECT_SLICE_EQ("", base64_decode("ab")); |
||||
EXPECT_SLICE_EQ("", base64_decode("abc")); |
||||
|
||||
// Test illegal charactors in grpc_chttp2_base64_decode
|
||||
EXPECT_SLICE_EQ("", base64_decode("Zm:v")); |
||||
EXPECT_SLICE_EQ("", base64_decode("Zm=v")); |
||||
|
||||
// Test output_length longer than max possible output length in
|
||||
// grpc_chttp2_base64_decode_with_length
|
||||
EXPECT_SLICE_EQ("", base64_decode_with_length("Zg", 2)); |
||||
EXPECT_SLICE_EQ("", base64_decode_with_length("Zm8", 3)); |
||||
EXPECT_SLICE_EQ("", base64_decode_with_length("Zm9v", 4)); |
||||
|
||||
// Test illegal charactors in grpc_chttp2_base64_decode_with_length
|
||||
EXPECT_SLICE_EQ("", base64_decode_with_length("Zm:v", 3)); |
||||
EXPECT_SLICE_EQ("", base64_decode_with_length("Zm=v", 3)); |
||||
|
||||
return all_ok ? 0 : 1; |
||||
} |
@ -0,0 +1,166 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016, 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. |
||||
* |
||||
*/ |
||||
|
||||
#include <google/protobuf/descriptor.h> |
||||
#include <grpc++/channel.h> |
||||
#include <grpc++/client_context.h> |
||||
#include <grpc++/create_channel.h> |
||||
#include <grpc++/ext/proto_server_reflection_plugin.h> |
||||
#include <grpc++/security/credentials.h> |
||||
#include <grpc++/security/server_credentials.h> |
||||
#include <grpc++/server.h> |
||||
#include <grpc++/server_builder.h> |
||||
#include <grpc++/server_context.h> |
||||
#include <grpc/grpc.h> |
||||
#include <gtest/gtest.h> |
||||
|
||||
#include "src/proto/grpc/testing/echo.grpc.pb.h" |
||||
#include "test/core/util/port.h" |
||||
#include "test/core/util/test_config.h" |
||||
#include "test/cpp/end2end/test_service_impl.h" |
||||
#include "test/cpp/util/proto_reflection_descriptor_database.h" |
||||
|
||||
namespace grpc { |
||||
namespace testing { |
||||
|
||||
class ProtoServerReflectionTest : public ::testing::Test { |
||||
public: |
||||
ProtoServerReflectionTest() {} |
||||
|
||||
void SetUp() GRPC_OVERRIDE { |
||||
port_ = grpc_pick_unused_port_or_die(); |
||||
ref_desc_pool_ = google::protobuf::DescriptorPool::generated_pool(); |
||||
|
||||
ServerBuilder builder; |
||||
grpc::string server_address = "localhost:" + to_string(port_); |
||||
builder.AddListeningPort(server_address, InsecureServerCredentials()); |
||||
server_ = builder.BuildAndStart(); |
||||
} |
||||
|
||||
void ResetStub() { |
||||
string target = "dns:localhost:" + to_string(port_); |
||||
std::shared_ptr<Channel> channel = |
||||
CreateChannel(target, InsecureChannelCredentials()); |
||||
stub_ = grpc::testing::EchoTestService::NewStub(channel); |
||||
desc_db_.reset(new ProtoReflectionDescriptorDatabase(channel)); |
||||
desc_pool_.reset(new google::protobuf::DescriptorPool(desc_db_.get())); |
||||
} |
||||
|
||||
string to_string(const int number) { |
||||
std::stringstream strs; |
||||
strs << number; |
||||
return strs.str(); |
||||
} |
||||
|
||||
void CompareService(const grpc::string& service) { |
||||
const google::protobuf::ServiceDescriptor* service_desc = |
||||
desc_pool_->FindServiceByName(service); |
||||
const google::protobuf::ServiceDescriptor* ref_service_desc = |
||||
ref_desc_pool_->FindServiceByName(service); |
||||
EXPECT_TRUE(service_desc != nullptr); |
||||
EXPECT_TRUE(ref_service_desc != nullptr); |
||||
EXPECT_EQ(service_desc->DebugString(), ref_service_desc->DebugString()); |
||||
|
||||
const google::protobuf::FileDescriptor* file_desc = service_desc->file(); |
||||
if (known_files_.find(file_desc->package() + "/" + file_desc->name()) != |
||||
known_files_.end()) { |
||||
EXPECT_EQ(file_desc->DebugString(), |
||||
ref_service_desc->file()->DebugString()); |
||||
known_files_.insert(file_desc->package() + "/" + file_desc->name()); |
||||
} |
||||
|
||||
for (int i = 0; i < service_desc->method_count(); ++i) { |
||||
CompareMethod(service_desc->method(i)->full_name()); |
||||
} |
||||
} |
||||
|
||||
void CompareMethod(const grpc::string& method) { |
||||
const google::protobuf::MethodDescriptor* method_desc = |
||||
desc_pool_->FindMethodByName(method); |
||||
const google::protobuf::MethodDescriptor* ref_method_desc = |
||||
ref_desc_pool_->FindMethodByName(method); |
||||
EXPECT_TRUE(method_desc != nullptr); |
||||
EXPECT_TRUE(ref_method_desc != nullptr); |
||||
EXPECT_EQ(method_desc->DebugString(), ref_method_desc->DebugString()); |
||||
|
||||
CompareType(method_desc->input_type()->full_name()); |
||||
CompareType(method_desc->output_type()->full_name()); |
||||
} |
||||
|
||||
void CompareType(const grpc::string& type) { |
||||
if (known_types_.find(type) != known_types_.end()) { |
||||
return; |
||||
} |
||||
|
||||
const google::protobuf::Descriptor* desc = |
||||
desc_pool_->FindMessageTypeByName(type); |
||||
const google::protobuf::Descriptor* ref_desc = |
||||
ref_desc_pool_->FindMessageTypeByName(type); |
||||
EXPECT_TRUE(desc != nullptr); |
||||
EXPECT_TRUE(ref_desc != nullptr); |
||||
EXPECT_EQ(desc->DebugString(), ref_desc->DebugString()); |
||||
} |
||||
|
||||
protected: |
||||
std::unique_ptr<Server> server_; |
||||
std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_; |
||||
std::unique_ptr<ProtoReflectionDescriptorDatabase> desc_db_; |
||||
std::unique_ptr<google::protobuf::DescriptorPool> desc_pool_; |
||||
std::unordered_set<string> known_files_; |
||||
std::unordered_set<string> known_types_; |
||||
const google::protobuf::DescriptorPool* ref_desc_pool_; |
||||
int port_; |
||||
reflection::ProtoServerReflectionPlugin plugin_; |
||||
}; |
||||
|
||||
TEST_F(ProtoServerReflectionTest, CheckResponseWithLocalDescriptorPool) { |
||||
ResetStub(); |
||||
|
||||
std::vector<std::string> services; |
||||
desc_db_->GetServices(&services); |
||||
// The service list has at least one service (reflection servcie).
|
||||
EXPECT_TRUE(services.size() > 0); |
||||
|
||||
for (auto it = services.begin(); it != services.end(); ++it) { |
||||
CompareService(*it); |
||||
} |
||||
} |
||||
|
||||
} // namespace testing
|
||||
} // namespace grpc
|
||||
|
||||
int main(int argc, char** argv) { |
||||
grpc_test_init(argc, argv); |
||||
::testing::InitGoogleTest(&argc, argv); |
||||
return RUN_ALL_TESTS(); |
||||
} |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue