mirror of https://github.com/grpc/grpc.git
commit
a32b1eb765
354 changed files with 11018 additions and 2640 deletions
@ -0,0 +1,16 @@ |
||||
load("//third_party/py:python_configure.bzl", "python_configure") |
||||
load("@io_bazel_rules_python//python:pip.bzl", "pip_repositories") |
||||
load("@grpc_python_dependencies//:requirements.bzl", "pip_install") |
||||
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_repositories") |
||||
|
||||
def grpc_python_deps(): |
||||
# TODO(https://github.com/grpc/grpc/issues/18256): Remove conditional. |
||||
if hasattr(native, "http_archive"): |
||||
python_configure(name = "local_config_python") |
||||
pip_repositories() |
||||
pip_install() |
||||
py_proto_repositories() |
||||
else: |
||||
print("Building Python gRPC with bazel 23.0+ is disabled pending " + |
||||
"resolution of https://github.com/grpc/grpc/issues/18256.") |
||||
|
@ -0,0 +1,56 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
|
||||
load("@grpc_python_dependencies//:requirements.bzl", "requirement") |
||||
|
||||
py_library( |
||||
name = "client", |
||||
testonly = 1, |
||||
srcs = ["client.py"], |
||||
deps = [ |
||||
"//src/python/grpcio/grpc:grpcio", |
||||
"//src/python/grpcio_status/grpc_status:grpc_status", |
||||
"//examples:py_helloworld", |
||||
requirement('googleapis-common-protos'), |
||||
], |
||||
) |
||||
|
||||
py_library( |
||||
name = "server", |
||||
testonly = 1, |
||||
srcs = ["server.py"], |
||||
deps = [ |
||||
"//src/python/grpcio/grpc:grpcio", |
||||
"//src/python/grpcio_status/grpc_status:grpc_status", |
||||
"//examples:py_helloworld", |
||||
] + select({ |
||||
"//conditions:default": [requirement("futures")], |
||||
"//:python3": [], |
||||
}), |
||||
) |
||||
|
||||
py_test( |
||||
name = "test/_error_handling_example_test", |
||||
srcs = ["test/_error_handling_example_test.py"], |
||||
deps = [ |
||||
":client", |
||||
":server", |
||||
"//src/python/grpcio_tests/tests:bazel_namespace_package_hack", |
||||
], |
||||
size = "small", |
||||
imports = [ |
||||
"../../../src/python/grpcio_status", |
||||
"../../../src/python/grpcio_tests", |
||||
], |
||||
) |
@ -0,0 +1,107 @@ |
||||
# gRPC Python Error Handling Example |
||||
|
||||
The goal of this example is sending error status from server that is more complicated than a code and detail string. |
||||
|
||||
The definition for an RPC method in proto files contains request message and response message. There are many error states that can be shared across RPC methods (e.g. stack trace, insufficient quota). Using a different path to handle error will make the code more maintainable. |
||||
|
||||
Ideally, the final status of an RPC should be described in the trailing headers of HTTP2, and gRPC Python provides helper functions in `grpcio-status` package to assist the packing and unpacking of error status. |
||||
|
||||
|
||||
### Requirement |
||||
``` |
||||
grpcio>=1.18.0 |
||||
grpcio-status>=1.18.0 |
||||
googleapis-common-protos>=1.5.5 |
||||
``` |
||||
|
||||
|
||||
### Error Detail Proto |
||||
|
||||
You may provide any custom proto message as error detail in your implementation. Here are protos are defined by Google Cloud Library Team: |
||||
|
||||
* [code.proto]([https://github.com/googleapis/api-common-protos/blob/master/google/rpc/code.proto](https://github.com/googleapis/api-common-protos/blob/87185dfffad4afa5a33a8c153f0e1ea53b4f85dc/google/rpc/code.proto)) contains definition of RPC error codes. |
||||
* [error_details.proto]([https://github.com/googleapis/api-common-protos/blob/master/google/rpc/error_details.proto](https://github.com/googleapis/api-common-protos/blob/87185dfffad4afa5a33a8c153f0e1ea53b4f85dc/google/rpc/error_details.proto)) contains definitions of common error details. |
||||
|
||||
|
||||
### Definition of Status Proto |
||||
|
||||
Here is the definition of Status proto. For full text, please see [status.proto](https://github.com/googleapis/api-common-protos/blob/87185dfffad4afa5a33a8c153f0e1ea53b4f85dc/google/rpc/status.proto). |
||||
|
||||
```proto |
||||
// The `Status` type defines a logical error model that is suitable for different |
||||
// programming environments, including REST APIs and RPC APIs. It is used by |
||||
// [gRPC](https://github.com/grpc). The error model is designed to be: |
||||
// |
||||
// - Simple to use and understand for most users |
||||
// - Flexible enough to meet unexpected needs |
||||
// |
||||
// # Overview |
||||
// |
||||
// The `Status` message contains three pieces of data: error code, error message, |
||||
// and error details. The error code should be an enum value of |
||||
// [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The |
||||
// error message should be a developer-facing English message that helps |
||||
// developers *understand* and *resolve* the error. If a localized user-facing |
||||
// error message is needed, put the localized message in the error details or |
||||
// localize it in the client. The optional error details may contain arbitrary |
||||
// information about the error. There is a predefined set of error detail types |
||||
// in the package `google.rpc` that can be used for common error conditions. |
||||
// |
||||
// # Language mapping |
||||
// |
||||
// The `Status` message is the logical representation of the error model, but it |
||||
// is not necessarily the actual wire format. When the `Status` message is |
||||
// exposed in different client libraries and different wire protocols, it can be |
||||
// mapped differently. For example, it will likely be mapped to some exceptions |
||||
// in Java, but more likely mapped to some error codes in C. |
||||
// |
||||
// # Other uses |
||||
// |
||||
// The error model and the `Status` message can be used in a variety of |
||||
// environments, either with or without APIs, to provide a |
||||
// consistent developer experience across different environments. |
||||
// |
||||
// Example uses of this error model include: |
||||
// |
||||
// - Partial errors. If a service needs to return partial errors to the client, |
||||
// it may embed the `Status` in the normal response to indicate the partial |
||||
// errors. |
||||
// |
||||
// - Workflow errors. A typical workflow has multiple steps. Each step may |
||||
// have a `Status` message for error reporting. |
||||
// |
||||
// - Batch operations. If a client uses batch request and batch response, the |
||||
// `Status` message should be used directly inside batch response, one for |
||||
// each error sub-response. |
||||
// |
||||
// - Asynchronous operations. If an API call embeds asynchronous operation |
||||
// results in its response, the status of those operations should be |
||||
// represented directly using the `Status` message. |
||||
// |
||||
// - Logging. If some API errors are stored in logs, the message `Status` could |
||||
// be used directly after any stripping needed for security/privacy reasons. |
||||
message Status { |
||||
// The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. |
||||
int32 code = 1; |
||||
|
||||
// A developer-facing error message, which should be in English. Any |
||||
// user-facing error message should be localized and sent in the |
||||
// [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. |
||||
string message = 2; |
||||
|
||||
// A list of messages that carry the error details. There is a common set of |
||||
// message types for APIs to use. |
||||
repeated google.protobuf.Any details = 3; |
||||
} |
||||
``` |
||||
|
||||
|
||||
### Usage of Well-Known-Proto `Any` |
||||
|
||||
Please check [ProtoBuf Document: Any](https://developers.google.com/protocol-buffers/docs/reference/python-generated#any) |
||||
|
||||
```Python |
||||
any_message.Pack(message) |
||||
any_message.Unpack(message) |
||||
assert any_message.Is(message.DESCRIPTOR) |
||||
``` |
@ -0,0 +1,56 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""This example handles rich error status in client-side.""" |
||||
|
||||
from __future__ import print_function |
||||
import logging |
||||
|
||||
import grpc |
||||
from grpc_status import rpc_status |
||||
from google.rpc import error_details_pb2 |
||||
|
||||
from examples.protos import helloworld_pb2 |
||||
from examples.protos import helloworld_pb2_grpc |
||||
|
||||
_LOGGER = logging.getLogger(__name__) |
||||
|
||||
|
||||
def process(stub): |
||||
try: |
||||
response = stub.SayHello(helloworld_pb2.HelloRequest(name='Alice')) |
||||
_LOGGER.info('Call success: %s', response.message) |
||||
except grpc.RpcError as rpc_error: |
||||
_LOGGER.error('Call failure: %s', rpc_error) |
||||
status = rpc_status.from_call(rpc_error) |
||||
for detail in status.details: |
||||
if detail.Is(error_details_pb2.QuotaFailure.DESCRIPTOR): |
||||
info = error_details_pb2.QuotaFailure() |
||||
detail.Unpack(info) |
||||
_LOGGER.error('Quota failure: %s', info) |
||||
else: |
||||
raise RuntimeError('Unexpected failure: %s' % detail) |
||||
|
||||
|
||||
def main(): |
||||
# NOTE(gRPC Python Team): .close() is possible on a channel and should be |
||||
# used in circumstances in which the with statement does not fit the needs |
||||
# of the code. |
||||
with grpc.insecure_channel('localhost:50051') as channel: |
||||
stub = helloworld_pb2_grpc.GreeterStub(channel) |
||||
process(stub) |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
logging.basicConfig() |
||||
main() |
@ -0,0 +1,90 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""This example sends out rich error status from server-side.""" |
||||
|
||||
from concurrent import futures |
||||
import time |
||||
import logging |
||||
import threading |
||||
|
||||
import grpc |
||||
from grpc_status import rpc_status |
||||
|
||||
from google.protobuf import any_pb2 |
||||
from google.rpc import code_pb2, status_pb2, error_details_pb2 |
||||
|
||||
from examples.protos import helloworld_pb2 |
||||
from examples.protos import helloworld_pb2_grpc |
||||
|
||||
_ONE_DAY_IN_SECONDS = 60 * 60 * 24 |
||||
|
||||
|
||||
def create_greet_limit_exceed_error_status(name): |
||||
detail = any_pb2.Any() |
||||
detail.Pack( |
||||
error_details_pb2.QuotaFailure( |
||||
violations=[ |
||||
error_details_pb2.QuotaFailure.Violation( |
||||
subject="name: %s" % name, |
||||
description="Limit one greeting per person", |
||||
) |
||||
],)) |
||||
return status_pb2.Status( |
||||
code=code_pb2.RESOURCE_EXHAUSTED, |
||||
message='Request limit exceeded.', |
||||
details=[detail], |
||||
) |
||||
|
||||
|
||||
class LimitedGreeter(helloworld_pb2_grpc.GreeterServicer): |
||||
|
||||
def __init__(self): |
||||
self._lock = threading.RLock() |
||||
self._greeted = set() |
||||
|
||||
def SayHello(self, request, context): |
||||
with self._lock: |
||||
if request.name in self._greeted: |
||||
rich_status = create_greet_limit_exceed_error_status( |
||||
request.name) |
||||
context.abort_with_status(rpc_status.to_status(rich_status)) |
||||
else: |
||||
self._greeted.add(request.name) |
||||
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) |
||||
|
||||
|
||||
def create_server(server_address): |
||||
server = grpc.server(futures.ThreadPoolExecutor()) |
||||
helloworld_pb2_grpc.add_GreeterServicer_to_server(LimitedGreeter(), server) |
||||
port = server.add_insecure_port(server_address) |
||||
return server, port |
||||
|
||||
|
||||
def serve(server): |
||||
server.start() |
||||
try: |
||||
while True: |
||||
time.sleep(_ONE_DAY_IN_SECONDS) |
||||
except KeyboardInterrupt: |
||||
server.stop(None) |
||||
|
||||
|
||||
def main(): |
||||
server, unused_port = create_server('[::]:50051') |
||||
serve(server) |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
logging.basicConfig() |
||||
main() |
@ -0,0 +1,54 @@ |
||||
# Copyright 2019 The gRPC Authors |
||||
# |
||||
# Licensed under the Apache License, Version 2.0 (the "License"); |
||||
# you may not use this file except in compliance with the License. |
||||
# You may obtain a copy of the License at |
||||
# |
||||
# http://www.apache.org/licenses/LICENSE-2.0 |
||||
# |
||||
# Unless required by applicable law or agreed to in writing, software |
||||
# distributed under the License is distributed on an "AS IS" BASIS, |
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
# See the License for the specific language governing permissions and |
||||
# limitations under the License. |
||||
"""Tests of the error handling example.""" |
||||
|
||||
# NOTE(lidiz) This module only exists in Bazel BUILD file, for more details |
||||
# please refer to comments in the "bazel_namespace_package_hack" module. |
||||
try: |
||||
from tests import bazel_namespace_package_hack |
||||
bazel_namespace_package_hack.sys_path_to_site_dir_hack() |
||||
except ImportError: |
||||
pass |
||||
|
||||
import unittest |
||||
import logging |
||||
|
||||
import grpc |
||||
|
||||
from examples.protos import helloworld_pb2_grpc |
||||
from examples.python.errors import client as error_handling_client |
||||
from examples.python.errors import server as error_handling_server |
||||
|
||||
|
||||
class ErrorHandlingExampleTest(unittest.TestCase): |
||||
|
||||
def setUp(self): |
||||
self._server, port = error_handling_server.create_server('[::]:0') |
||||
self._server.start() |
||||
self._channel = grpc.insecure_channel('localhost:%d' % port) |
||||
|
||||
def tearDown(self): |
||||
self._channel.close() |
||||
self._server.stop(None) |
||||
|
||||
def test_error_handling_example(self): |
||||
stub = helloworld_pb2_grpc.GreeterStub(self._channel) |
||||
error_handling_client.process(stub) |
||||
error_handling_client.process(stub) |
||||
# No unhandled exception raised, test passed! |
||||
|
||||
|
||||
if __name__ == '__main__': |
||||
logging.basicConfig() |
||||
unittest.main(verbosity=2) |
@ -0,0 +1,79 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_CREATE_CHANNEL_IMPL_H |
||||
#define GRPCPP_CREATE_CHANNEL_IMPL_H |
||||
|
||||
#include <memory> |
||||
|
||||
#include <grpcpp/channel.h> |
||||
#include <grpcpp/impl/codegen/client_interceptor.h> |
||||
#include <grpcpp/security/credentials.h> |
||||
#include <grpcpp/support/channel_arguments.h> |
||||
#include <grpcpp/support/config.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
/// Create a new \a Channel pointing to \a target.
|
||||
///
|
||||
/// \param target The URI of the endpoint to connect to.
|
||||
/// \param creds Credentials to use for the created channel. If it does not
|
||||
/// hold an object or is invalid, a lame channel (one on which all operations
|
||||
/// fail) is returned.
|
||||
std::shared_ptr<grpc::Channel> CreateChannel( |
||||
const grpc::string& target, |
||||
const std::shared_ptr<grpc::ChannelCredentials>& creds); |
||||
|
||||
/// Create a new \em custom \a Channel pointing to \a target.
|
||||
///
|
||||
/// \warning For advanced use and testing ONLY. Override default channel
|
||||
/// arguments only if necessary.
|
||||
///
|
||||
/// \param target The URI of the endpoint to connect to.
|
||||
/// \param creds Credentials to use for the created channel. If it does not
|
||||
/// hold an object or is invalid, a lame channel (one on which all operations
|
||||
/// fail) is returned.
|
||||
/// \param args Options for channel creation.
|
||||
std::shared_ptr<grpc::Channel> CreateCustomChannel( |
||||
const grpc::string& target, |
||||
const std::shared_ptr<grpc::ChannelCredentials>& creds, |
||||
const grpc::ChannelArguments& args); |
||||
|
||||
namespace experimental { |
||||
/// Create a new \em custom \a Channel pointing to \a target with \a
|
||||
/// interceptors being invoked per call.
|
||||
///
|
||||
/// \warning For advanced use and testing ONLY. Override default channel
|
||||
/// arguments only if necessary.
|
||||
///
|
||||
/// \param target The URI of the endpoint to connect to.
|
||||
/// \param creds Credentials to use for the created channel. If it does not
|
||||
/// hold an object or is invalid, a lame channel (one on which all operations
|
||||
/// fail) is returned.
|
||||
/// \param args Options for channel creation.
|
||||
std::shared_ptr<grpc::Channel> CreateCustomChannelWithInterceptors( |
||||
const grpc::string& target, |
||||
const std::shared_ptr<grpc::ChannelCredentials>& creds, |
||||
const grpc::ChannelArguments& args, |
||||
std::vector< |
||||
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> |
||||
interceptor_creators); |
||||
} // namespace experimental
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_CREATE_CHANNEL_IMPL_H
|
@ -0,0 +1,70 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_CREATE_CHANNEL_POSIX_IMPL_H |
||||
#define GRPCPP_CREATE_CHANNEL_POSIX_IMPL_H |
||||
|
||||
#include <memory> |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
#include <grpcpp/channel.h> |
||||
#include <grpcpp/support/channel_arguments.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
#ifdef GPR_SUPPORT_CHANNELS_FROM_FD |
||||
|
||||
/// Create a new \a Channel communicating over the given file descriptor.
|
||||
///
|
||||
/// \param target The name of the target.
|
||||
/// \param fd The file descriptor representing a socket.
|
||||
std::shared_ptr<grpc::Channel> CreateInsecureChannelFromFd( |
||||
const grpc::string& target, int fd); |
||||
|
||||
/// Create a new \a Channel communicating over given file descriptor with custom
|
||||
/// channel arguments.
|
||||
///
|
||||
/// \param target The name of the target.
|
||||
/// \param fd The file descriptor representing a socket.
|
||||
/// \param args Options for channel creation.
|
||||
std::shared_ptr<grpc::Channel> CreateCustomInsecureChannelFromFd( |
||||
const grpc::string& target, int fd, const grpc::ChannelArguments& args); |
||||
|
||||
namespace experimental { |
||||
|
||||
/// Create a new \a Channel communicating over given file descriptor with custom
|
||||
/// channel arguments.
|
||||
///
|
||||
/// \param target The name of the target.
|
||||
/// \param fd The file descriptor representing a socket.
|
||||
/// \param args Options for channel creation.
|
||||
/// \param interceptor_creators Vector of interceptor factory objects.
|
||||
std::shared_ptr<grpc::Channel> |
||||
CreateCustomInsecureChannelWithInterceptorsFromFd( |
||||
const grpc::string& target, int fd, const grpc::ChannelArguments& args, |
||||
std::unique_ptr<std::vector< |
||||
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>> |
||||
interceptor_creators); |
||||
|
||||
} // namespace experimental
|
||||
|
||||
#endif // GPR_SUPPORT_CHANNELS_FROM_FD
|
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_CREATE_CHANNEL_POSIX_IMPL_H
|
@ -0,0 +1,41 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2018 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H |
||||
#define GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include <grpcpp/impl/server_builder_plugin.h> |
||||
#include <grpcpp/impl/server_initializer.h> |
||||
#include <grpcpp/support/config.h> |
||||
|
||||
namespace grpc_impl { |
||||
namespace channelz { |
||||
namespace experimental { |
||||
|
||||
/// Add channelz server plugin to \a ServerBuilder. This function should
|
||||
/// be called at static initialization time. This service is experimental
|
||||
/// for now. Track progress in https://github.com/grpc/grpc/issues/15988.
|
||||
void InitChannelzService(); |
||||
|
||||
} // namespace experimental
|
||||
} // namespace channelz
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_IMPL_H
|
@ -0,0 +1,55 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_EXT_PROTO_SERVER_REFLECTION_PLUGIN_IMPL_H |
||||
#define GRPCPP_EXT_PROTO_SERVER_REFLECTION_PLUGIN_IMPL_H |
||||
|
||||
#include <grpcpp/impl/server_builder_plugin.h> |
||||
#include <grpcpp/support/config.h> |
||||
|
||||
namespace grpc { |
||||
class ProtoServerReflection; |
||||
} // namespace grpc
|
||||
|
||||
namespace grpc_impl { |
||||
class ServerInitializer; |
||||
|
||||
namespace reflection { |
||||
|
||||
class ProtoServerReflectionPlugin : public ::grpc::ServerBuilderPlugin { |
||||
public: |
||||
ProtoServerReflectionPlugin(); |
||||
::grpc::string name() override; |
||||
void InitServer(::grpc_impl::ServerInitializer* si) override; |
||||
void Finish(::grpc_impl::ServerInitializer* si) override; |
||||
void ChangeArguments(const ::grpc::string& name, void* value) override; |
||||
bool has_async_methods() const override; |
||||
bool has_sync_methods() const override; |
||||
|
||||
private: |
||||
std::shared_ptr<grpc::ProtoServerReflection> reflection_service_; |
||||
}; |
||||
|
||||
/// Add proto reflection plugin to \a ServerBuilder.
|
||||
/// This function should be called at the static initialization time.
|
||||
void InitProtoReflectionServerBuilderPlugin(); |
||||
|
||||
} // namespace reflection
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_EXT_PROTO_SERVER_REFLECTION_PLUGIN_IMPL_H
|
@ -0,0 +1,54 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2018 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_EXT_SERVER_LOAD_REPORTING_IMPL_H |
||||
#define GRPCPP_EXT_SERVER_LOAD_REPORTING_IMPL_H |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include <grpc/load_reporting.h> |
||||
#include <grpcpp/impl/codegen/config.h> |
||||
#include <grpcpp/impl/codegen/server_context.h> |
||||
#include <grpcpp/impl/server_builder_option.h> |
||||
|
||||
namespace grpc_impl { |
||||
namespace load_reporter { |
||||
namespace experimental { |
||||
|
||||
// The ServerBuilderOption to enable server-side load reporting feature. To
|
||||
// enable the feature, please make sure the binary builds with the
|
||||
// grpcpp_server_load_reporting library and set this option in the
|
||||
// ServerBuilder.
|
||||
class LoadReportingServiceServerBuilderOption |
||||
: public grpc::ServerBuilderOption { |
||||
public: |
||||
void UpdateArguments(::grpc::ChannelArguments* args) override; |
||||
void UpdatePlugins(std::vector<std::unique_ptr<::grpc::ServerBuilderPlugin>>* |
||||
plugins) override; |
||||
}; |
||||
|
||||
// Adds the load reporting cost with \a cost_name and \a cost_value in the
|
||||
// trailing metadata of the server context.
|
||||
void AddLoadReportingCost(grpc::ServerContext* ctx, |
||||
const grpc::string& cost_name, double cost_value); |
||||
|
||||
} // namespace experimental
|
||||
} // namespace load_reporter
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_EXT_SERVER_LOAD_REPORTING_IMPL_H
|
@ -0,0 +1,108 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_GENERIC_GENERIC_STUB_IMPL_H |
||||
#define GRPCPP_GENERIC_GENERIC_STUB_IMPL_H |
||||
|
||||
#include <functional> |
||||
|
||||
#include <grpcpp/support/async_stream.h> |
||||
#include <grpcpp/support/async_unary_call.h> |
||||
#include <grpcpp/support/byte_buffer.h> |
||||
#include <grpcpp/support/client_callback.h> |
||||
#include <grpcpp/support/status.h> |
||||
|
||||
namespace grpc { |
||||
|
||||
class CompletionQueue; |
||||
typedef ClientAsyncReaderWriter<ByteBuffer, ByteBuffer> |
||||
GenericClientAsyncReaderWriter; |
||||
typedef ClientAsyncResponseReader<ByteBuffer> GenericClientAsyncResponseReader; |
||||
} // namespace grpc
|
||||
namespace grpc_impl { |
||||
|
||||
/// Generic stubs provide a type-unsafe interface to call gRPC methods
|
||||
/// by name.
|
||||
class GenericStub final { |
||||
public: |
||||
explicit GenericStub(std::shared_ptr<grpc::ChannelInterface> channel) |
||||
: channel_(channel) {} |
||||
|
||||
/// Setup a call to a named method \a method using \a context, but don't
|
||||
/// start it. Let it be started explicitly with StartCall and a tag.
|
||||
/// The return value only indicates whether or not registration of the call
|
||||
/// succeeded (i.e. the call won't proceed if the return value is nullptr).
|
||||
std::unique_ptr<grpc::GenericClientAsyncReaderWriter> PrepareCall( |
||||
grpc::ClientContext* context, const grpc::string& method, |
||||
grpc::CompletionQueue* cq); |
||||
|
||||
/// Setup a unary call to a named method \a method using \a context, and don't
|
||||
/// start it. Let it be started explicitly with StartCall.
|
||||
/// The return value only indicates whether or not registration of the call
|
||||
/// succeeded (i.e. the call won't proceed if the return value is nullptr).
|
||||
std::unique_ptr<grpc::GenericClientAsyncResponseReader> PrepareUnaryCall( |
||||
grpc::ClientContext* context, const grpc::string& method, |
||||
const grpc::ByteBuffer& request, grpc::CompletionQueue* cq); |
||||
|
||||
/// DEPRECATED for multi-threaded use
|
||||
/// Begin a call to a named method \a method using \a context.
|
||||
/// A tag \a tag will be delivered to \a cq when the call has been started
|
||||
/// (i.e, initial metadata has been sent).
|
||||
/// The return value only indicates whether or not registration of the call
|
||||
/// succeeded (i.e. the call won't proceed if the return value is nullptr).
|
||||
std::unique_ptr<grpc::GenericClientAsyncReaderWriter> Call( |
||||
grpc::ClientContext* context, const grpc::string& method, |
||||
grpc::CompletionQueue* cq, void* tag); |
||||
|
||||
/// NOTE: class experimental_type is not part of the public API of this class
|
||||
/// TODO(vjpai): Move these contents to the public API of GenericStub when
|
||||
/// they are no longer experimental
|
||||
class experimental_type { |
||||
public: |
||||
explicit experimental_type(GenericStub* stub) : stub_(stub) {} |
||||
|
||||
/// Setup and start a unary call to a named method \a method using
|
||||
/// \a context and specifying the \a request and \a response buffers.
|
||||
void UnaryCall(grpc::ClientContext* context, const grpc::string& method, |
||||
const grpc::ByteBuffer* request, grpc::ByteBuffer* response, |
||||
std::function<void(grpc::Status)> on_completion); |
||||
|
||||
/// Setup a call to a named method \a method using \a context and tied to
|
||||
/// \a reactor . Like any other bidi streaming RPC, it will not be activated
|
||||
/// until StartCall is invoked on its reactor.
|
||||
void PrepareBidiStreamingCall( |
||||
grpc::ClientContext* context, const grpc::string& method, |
||||
grpc::experimental::ClientBidiReactor<grpc::ByteBuffer, |
||||
grpc::ByteBuffer>* reactor); |
||||
|
||||
private: |
||||
GenericStub* stub_; |
||||
}; |
||||
|
||||
/// NOTE: The function experimental() is not stable public API. It is a view
|
||||
/// to the experimental components of this class. It may be changed or removed
|
||||
/// at any time.
|
||||
experimental_type experimental() { return experimental_type(this); } |
||||
|
||||
private: |
||||
std::shared_ptr<grpc::ChannelInterface> channel_; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_GENERIC_GENERIC_STUB_IMPL_H
|
@ -0,0 +1,55 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_HEALTH_CHECK_SERVICE_INTERFACE_IMPL_H |
||||
#define GRPCPP_HEALTH_CHECK_SERVICE_INTERFACE_IMPL_H |
||||
|
||||
#include <grpcpp/support/config.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
/// The gRPC server uses this interface to expose the health checking service
|
||||
/// without depending on protobuf.
|
||||
class HealthCheckServiceInterface { |
||||
public: |
||||
virtual ~HealthCheckServiceInterface() {} |
||||
|
||||
/// Set or change the serving status of the given \a service_name.
|
||||
virtual void SetServingStatus(const grpc::string& service_name, |
||||
bool serving) = 0; |
||||
/// Apply to all registered service names.
|
||||
virtual void SetServingStatus(bool serving) = 0; |
||||
|
||||
/// Set all registered service names to not serving and prevent future
|
||||
/// state changes.
|
||||
virtual void Shutdown() {} |
||||
}; |
||||
|
||||
/// Enable/disable the default health checking service. This applies to all C++
|
||||
/// servers created afterwards. For each server, user can override the default
|
||||
/// with a HealthCheckServiceServerBuilderOption.
|
||||
/// NOT thread safe.
|
||||
void EnableDefaultHealthCheckService(bool enable); |
||||
|
||||
/// Returns whether the default health checking service is enabled.
|
||||
/// NOT thread safe.
|
||||
bool DefaultHealthCheckServiceEnabled(); |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_HEALTH_CHECK_SERVICE_INTERFACE_IMPL_H
|
@ -0,0 +1,138 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_IMPL_CODEGEN_SYNC_H |
||||
#define GRPCPP_IMPL_CODEGEN_SYNC_H |
||||
|
||||
#include <grpc/impl/codegen/log.h> |
||||
#include <grpc/impl/codegen/port_platform.h> |
||||
#include <grpc/impl/codegen/sync.h> |
||||
|
||||
#include <grpcpp/impl/codegen/core_codegen_interface.h> |
||||
|
||||
// The core library is not accessible in C++ codegen headers, and vice versa.
|
||||
// Thus, we need to have duplicate headers with similar functionality.
|
||||
// Make sure any change to this file is also reflected in
|
||||
// src/core/lib/gprpp/sync.h too.
|
||||
//
|
||||
// Whenever possible, prefer "src/core/lib/gprpp/sync.h" over this file,
|
||||
// since in core we do not rely on g_core_codegen_interface and hence do not
|
||||
// pay the costs of virtual function calls.
|
||||
|
||||
namespace grpc { |
||||
namespace internal { |
||||
|
||||
class Mutex { |
||||
public: |
||||
Mutex() { g_core_codegen_interface->gpr_mu_init(&mu_); } |
||||
~Mutex() { g_core_codegen_interface->gpr_mu_destroy(&mu_); } |
||||
|
||||
Mutex(const Mutex&) = delete; |
||||
Mutex& operator=(const Mutex&) = delete; |
||||
|
||||
gpr_mu* get() { return &mu_; } |
||||
const gpr_mu* get() const { return &mu_; } |
||||
|
||||
private: |
||||
gpr_mu mu_; |
||||
}; |
||||
|
||||
// MutexLock is a std::
|
||||
class MutexLock { |
||||
public: |
||||
explicit MutexLock(Mutex* mu) : mu_(mu->get()) { |
||||
g_core_codegen_interface->gpr_mu_lock(mu_); |
||||
} |
||||
explicit MutexLock(gpr_mu* mu) : mu_(mu) { |
||||
g_core_codegen_interface->gpr_mu_lock(mu_); |
||||
} |
||||
~MutexLock() { g_core_codegen_interface->gpr_mu_unlock(mu_); } |
||||
|
||||
MutexLock(const MutexLock&) = delete; |
||||
MutexLock& operator=(const MutexLock&) = delete; |
||||
|
||||
private: |
||||
gpr_mu* const mu_; |
||||
}; |
||||
|
||||
class ReleasableMutexLock { |
||||
public: |
||||
explicit ReleasableMutexLock(Mutex* mu) : mu_(mu->get()) { |
||||
g_core_codegen_interface->gpr_mu_lock(mu_); |
||||
} |
||||
explicit ReleasableMutexLock(gpr_mu* mu) : mu_(mu) { |
||||
g_core_codegen_interface->gpr_mu_lock(mu_); |
||||
} |
||||
~ReleasableMutexLock() { |
||||
if (!released_) g_core_codegen_interface->gpr_mu_unlock(mu_); |
||||
} |
||||
|
||||
ReleasableMutexLock(const ReleasableMutexLock&) = delete; |
||||
ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete; |
||||
|
||||
void Lock() { |
||||
GPR_DEBUG_ASSERT(released_); |
||||
g_core_codegen_interface->gpr_mu_lock(mu_); |
||||
released_ = false; |
||||
} |
||||
|
||||
void Unlock() { |
||||
GPR_DEBUG_ASSERT(!released_); |
||||
released_ = true; |
||||
g_core_codegen_interface->gpr_mu_unlock(mu_); |
||||
} |
||||
|
||||
private: |
||||
gpr_mu* const mu_; |
||||
bool released_ = false; |
||||
}; |
||||
|
||||
class CondVar { |
||||
public: |
||||
CondVar() { g_core_codegen_interface->gpr_cv_init(&cv_); } |
||||
~CondVar() { g_core_codegen_interface->gpr_cv_destroy(&cv_); } |
||||
|
||||
CondVar(const CondVar&) = delete; |
||||
CondVar& operator=(const CondVar&) = delete; |
||||
|
||||
void Signal() { g_core_codegen_interface->gpr_cv_signal(&cv_); } |
||||
void Broadcast() { g_core_codegen_interface->gpr_cv_broadcast(&cv_); } |
||||
|
||||
int Wait(Mutex* mu) { |
||||
return Wait(mu, |
||||
g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME)); |
||||
} |
||||
int Wait(Mutex* mu, const gpr_timespec& deadline) { |
||||
return g_core_codegen_interface->gpr_cv_wait(&cv_, mu->get(), deadline); |
||||
} |
||||
|
||||
template <typename Predicate> |
||||
void WaitUntil(Mutex* mu, Predicate pred) { |
||||
while (!pred()) { |
||||
Wait(mu, g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME)); |
||||
} |
||||
} |
||||
|
||||
private: |
||||
gpr_cv cv_; |
||||
}; |
||||
|
||||
} // namespace internal
|
||||
} // namespace grpc
|
||||
|
||||
#endif // GRPCPP_IMPL_CODEGEN_SYNC_H
|
@ -0,0 +1,43 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_IMPL_SERVER_BUILDER_OPTION_IMPL_H |
||||
#define GRPCPP_IMPL_SERVER_BUILDER_OPTION_IMPL_H |
||||
|
||||
#include <map> |
||||
#include <memory> |
||||
|
||||
#include <grpcpp/impl/server_builder_plugin.h> |
||||
#include <grpcpp/support/channel_arguments.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
/// Interface to pass an option to a \a ServerBuilder.
|
||||
class ServerBuilderOption { |
||||
public: |
||||
virtual ~ServerBuilderOption() {} |
||||
/// Alter the \a ChannelArguments used to create the gRPC server.
|
||||
virtual void UpdateArguments(grpc::ChannelArguments* args) = 0; |
||||
/// Alter the ServerBuilderPlugin map that will be added into ServerBuilder.
|
||||
virtual void UpdatePlugins( |
||||
std::vector<std::unique_ptr<grpc::ServerBuilderPlugin>>* plugins) = 0; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_IMPL_SERVER_BUILDER_OPTION_IMPL_H
|
@ -0,0 +1,57 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_IMPL_SERVER_INITIALIZER_IMPL_H |
||||
#define GRPCPP_IMPL_SERVER_INITIALIZER_IMPL_H |
||||
|
||||
#include <memory> |
||||
#include <vector> |
||||
|
||||
#include <grpcpp/server.h> |
||||
|
||||
namespace grpc { |
||||
|
||||
class Server; |
||||
class Service; |
||||
} // namespace grpc
|
||||
namespace grpc_impl { |
||||
|
||||
class ServerInitializer { |
||||
public: |
||||
ServerInitializer(grpc::Server* server) : server_(server) {} |
||||
|
||||
bool RegisterService(std::shared_ptr<grpc::Service> service) { |
||||
if (!server_->RegisterService(nullptr, service.get())) { |
||||
return false; |
||||
} |
||||
default_services_.push_back(service); |
||||
return true; |
||||
} |
||||
|
||||
const std::vector<grpc::string>* GetServiceList() { |
||||
return &server_->services_; |
||||
} |
||||
|
||||
private: |
||||
grpc::Server* server_; |
||||
std::vector<std::shared_ptr<grpc::Service> > default_services_; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_IMPL_SERVER_INITIALIZER_IMPL_H
|
@ -0,0 +1,51 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2019 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_OPENCENSUS_IMPL_H |
||||
#define GRPCPP_OPENCENSUS_IMPL_H |
||||
|
||||
#include "opencensus/trace/span.h" |
||||
|
||||
namespace grpc { |
||||
|
||||
class ServerContext; |
||||
} |
||||
namespace grpc_impl { |
||||
// These symbols in this file will not be included in the binary unless
|
||||
// grpc_opencensus_plugin build target was added as a dependency. At the moment
|
||||
// it is only setup to be built with Bazel.
|
||||
|
||||
// Registers the OpenCensus plugin with gRPC, so that it will be used for future
|
||||
// RPCs. This must be called before any views are created.
|
||||
void RegisterOpenCensusPlugin(); |
||||
|
||||
// RPC stats definitions, defined by
|
||||
// https://github.com/census-instrumentation/opencensus-specs/blob/master/stats/gRPC.md
|
||||
|
||||
// Registers the cumulative gRPC views so that they will be exported by any
|
||||
// registered stats exporter. For on-task stats, construct a View using the
|
||||
// ViewDescriptors below.
|
||||
void RegisterOpenCensusViewsForExport(); |
||||
|
||||
// Returns the tracing Span for the current RPC.
|
||||
::opencensus::trace::Span GetSpanFromServerContext( |
||||
grpc::ServerContext* context); |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_OPENCENSUS_IMPL_H
|
@ -0,0 +1,68 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_RESOURCE_QUOTA_IMPL_H |
||||
#define GRPCPP_RESOURCE_QUOTA_IMPL_H |
||||
|
||||
struct grpc_resource_quota; |
||||
|
||||
#include <grpcpp/impl/codegen/config.h> |
||||
#include <grpcpp/impl/codegen/grpc_library.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
/// ResourceQuota represents a bound on memory and thread usage by the gRPC
|
||||
/// library. A ResourceQuota can be attached to a server (via \a ServerBuilder),
|
||||
/// or a client channel (via \a ChannelArguments).
|
||||
/// gRPC will attempt to keep memory and threads used by all attached entities
|
||||
/// below the ResourceQuota bound.
|
||||
class ResourceQuota final : private ::grpc::GrpcLibraryCodegen { |
||||
public: |
||||
/// \param name - a unique name for this ResourceQuota.
|
||||
explicit ResourceQuota(const grpc::string& name); |
||||
ResourceQuota(); |
||||
~ResourceQuota(); |
||||
|
||||
/// Resize this \a ResourceQuota to a new size. If \a new_size is smaller
|
||||
/// than the current size of the pool, memory usage will be monotonically
|
||||
/// decreased until it falls under \a new_size.
|
||||
/// No time bound is given for this to occur however.
|
||||
ResourceQuota& Resize(size_t new_size); |
||||
|
||||
/// Set the max number of threads that can be allocated from this
|
||||
/// ResourceQuota object.
|
||||
///
|
||||
/// If the new_max_threads value is smaller than the current value, no new
|
||||
/// threads are allocated until the number of active threads fall below
|
||||
/// new_max_threads. There is no time bound on when this may happen i.e none
|
||||
/// of the current threads are forcefully destroyed and all threads run their
|
||||
/// normal course.
|
||||
ResourceQuota& SetMaxThreads(int new_max_threads); |
||||
|
||||
grpc_resource_quota* c_resource_quota() const { return impl_; } |
||||
|
||||
private: |
||||
ResourceQuota(const ResourceQuota& rhs); |
||||
ResourceQuota& operator=(const ResourceQuota& rhs); |
||||
|
||||
grpc_resource_quota* const impl_; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_RESOURCE_QUOTA_IMPL_H
|
@ -0,0 +1,61 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SECURITY_AUTH_METADATA_PROCESSOR_IMPL_H |
||||
#define GRPCPP_SECURITY_AUTH_METADATA_PROCESSOR_IMPL_H |
||||
|
||||
#include <map> |
||||
|
||||
#include <grpcpp/security/auth_context.h> |
||||
#include <grpcpp/support/status.h> |
||||
#include <grpcpp/support/string_ref.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
/// Interface allowing custom server-side authorization based on credentials
|
||||
/// encoded in metadata. Objects of this type can be passed to
|
||||
/// \a ServerCredentials::SetAuthMetadataProcessor().
|
||||
class AuthMetadataProcessor { |
||||
public: |
||||
typedef std::multimap<grpc::string_ref, grpc::string_ref> InputMetadata; |
||||
typedef std::multimap<grpc::string, grpc::string> OutputMetadata; |
||||
|
||||
virtual ~AuthMetadataProcessor() {} |
||||
|
||||
/// If this method returns true, the \a Process function will be scheduled in
|
||||
/// a different thread from the one processing the call.
|
||||
virtual bool IsBlocking() const { return true; } |
||||
|
||||
/// context is read/write: it contains the properties of the channel peer and
|
||||
/// it is the job of the Process method to augment it with properties derived
|
||||
/// from the passed-in auth_metadata.
|
||||
/// consumed_auth_metadata needs to be filled with metadata that has been
|
||||
/// consumed by the processor and will be removed from the call.
|
||||
/// response_metadata is the metadata that will be sent as part of the
|
||||
/// response.
|
||||
/// If the return value is not Status::OK, the rpc call will be aborted with
|
||||
/// the error code and error message sent back to the client.
|
||||
virtual grpc::Status Process(const InputMetadata& auth_metadata, |
||||
grpc::AuthContext* context, |
||||
OutputMetadata* consumed_auth_metadata, |
||||
OutputMetadata* response_metadata) = 0; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_SECURITY_AUTH_METADATA_PROCESSOR_IMPL_H
|
@ -0,0 +1,85 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SECURITY_SERVER_CREDENTIALS_IMPL_H |
||||
#define GRPCPP_SECURITY_SERVER_CREDENTIALS_IMPL_H |
||||
|
||||
#include <memory> |
||||
#include <vector> |
||||
|
||||
#include <grpc/grpc_security_constants.h> |
||||
#include <grpcpp/security/auth_metadata_processor.h> |
||||
#include <grpcpp/support/config.h> |
||||
|
||||
struct grpc_server; |
||||
|
||||
namespace grpc { |
||||
|
||||
class Server; |
||||
struct SslServerCredentialsOptions; |
||||
} // namespace grpc
|
||||
namespace grpc_impl { |
||||
|
||||
/// Wrapper around \a grpc_server_credentials, a way to authenticate a server.
|
||||
class ServerCredentials { |
||||
public: |
||||
virtual ~ServerCredentials(); |
||||
|
||||
/// This method is not thread-safe and has to be called before the server is
|
||||
/// started. The last call to this function wins.
|
||||
virtual void SetAuthMetadataProcessor( |
||||
const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) = 0; |
||||
|
||||
private: |
||||
friend class ::grpc::Server; |
||||
|
||||
/// Tries to bind \a server to the given \a addr (eg, localhost:1234,
|
||||
/// 192.168.1.1:31416, [::1]:27182, etc.)
|
||||
///
|
||||
/// \return bound port number on success, 0 on failure.
|
||||
// TODO(dgq): the "port" part seems to be a misnomer.
|
||||
virtual int AddPortToServer(const grpc::string& addr, |
||||
grpc_server* server) = 0; |
||||
}; |
||||
|
||||
/// Builds SSL ServerCredentials given SSL specific options
|
||||
std::shared_ptr<ServerCredentials> SslServerCredentials( |
||||
const grpc::SslServerCredentialsOptions& options); |
||||
|
||||
/// Builds insecure server credentials.
|
||||
std::shared_ptr<ServerCredentials> InsecureServerCredentials(); |
||||
|
||||
namespace experimental { |
||||
|
||||
/// Options to create ServerCredentials with ALTS
|
||||
struct AltsServerCredentialsOptions { |
||||
/// Add fields if needed.
|
||||
}; |
||||
|
||||
/// Builds ALTS ServerCredentials given ALTS specific options
|
||||
std::shared_ptr<ServerCredentials> AltsServerCredentials( |
||||
const AltsServerCredentialsOptions& options); |
||||
|
||||
/// Builds Local ServerCredentials.
|
||||
std::shared_ptr<ServerCredentials> LocalServerCredentials( |
||||
grpc_local_connect_type type); |
||||
|
||||
} // namespace experimental
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_SECURITY_SERVER_CREDENTIALS_IMPL_H
|
@ -0,0 +1,354 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015-2016 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SERVER_BUILDER_IMPL_H |
||||
#define GRPCPP_SERVER_BUILDER_IMPL_H |
||||
|
||||
#include <climits> |
||||
#include <map> |
||||
#include <memory> |
||||
#include <vector> |
||||
|
||||
#include <grpc/compression.h> |
||||
#include <grpc/support/cpu.h> |
||||
#include <grpc/support/workaround_list.h> |
||||
#include <grpcpp/impl/channel_argument_option.h> |
||||
#include <grpcpp/impl/codegen/server_interceptor.h> |
||||
#include <grpcpp/impl/server_builder_option.h> |
||||
#include <grpcpp/impl/server_builder_plugin.h> |
||||
#include <grpcpp/support/config.h> |
||||
|
||||
struct grpc_resource_quota; |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
class ResourceQuota; |
||||
class ServerCredentials; |
||||
} // namespace grpc_impl
|
||||
namespace grpc { |
||||
|
||||
class AsyncGenericService; |
||||
class CompletionQueue; |
||||
class Server; |
||||
class ServerCompletionQueue; |
||||
class Service; |
||||
|
||||
namespace testing { |
||||
class ServerBuilderPluginTest; |
||||
} // namespace testing
|
||||
|
||||
namespace experimental { |
||||
class CallbackGenericService; |
||||
} |
||||
} // namespace grpc
|
||||
namespace grpc_impl { |
||||
|
||||
/// A builder class for the creation and startup of \a grpc::Server instances.
|
||||
class ServerBuilder { |
||||
public: |
||||
ServerBuilder(); |
||||
virtual ~ServerBuilder(); |
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// Primary API's
|
||||
|
||||
/// Return a running server which is ready for processing calls.
|
||||
/// Before calling, one typically needs to ensure that:
|
||||
/// 1. a service is registered - so that the server knows what to serve
|
||||
/// (via RegisterService, or RegisterAsyncGenericService)
|
||||
/// 2. a listening port has been added - so the server knows where to receive
|
||||
/// traffic (via AddListeningPort)
|
||||
/// 3. [for async api only] completion queues have been added via
|
||||
/// AddCompletionQueue
|
||||
virtual std::unique_ptr<grpc::Server> BuildAndStart(); |
||||
|
||||
/// Register a service. This call does not take ownership of the service.
|
||||
/// The service must exist for the lifetime of the \a Server instance returned
|
||||
/// by \a BuildAndStart().
|
||||
/// Matches requests with any :authority
|
||||
ServerBuilder& RegisterService(grpc::Service* service); |
||||
|
||||
/// Enlists an endpoint \a addr (port with an optional IP address) to
|
||||
/// bind the \a grpc::Server object to be created to.
|
||||
///
|
||||
/// It can be invoked multiple times.
|
||||
///
|
||||
/// \param addr_uri The address to try to bind to the server in URI form. If
|
||||
/// the scheme name is omitted, "dns:///" is assumed. To bind to any address,
|
||||
/// please use IPv6 any, i.e., [::]:<port>, which also accepts IPv4
|
||||
/// connections. Valid values include dns:///localhost:1234, /
|
||||
/// 192.168.1.1:31416, dns:///[::1]:27182, etc.).
|
||||
/// \param creds The credentials associated with the server.
|
||||
/// \param selected_port[out] If not `nullptr`, gets populated with the port
|
||||
/// number bound to the \a grpc::Server for the corresponding endpoint after
|
||||
/// it is successfully bound by BuildAndStart(), 0 otherwise. AddListeningPort
|
||||
/// does not modify this pointer.
|
||||
ServerBuilder& AddListeningPort( |
||||
const grpc::string& addr_uri, |
||||
std::shared_ptr<grpc_impl::ServerCredentials> creds, |
||||
int* selected_port = nullptr); |
||||
|
||||
/// Add a completion queue for handling asynchronous services.
|
||||
///
|
||||
/// Best performance is typically obtained by using one thread per polling
|
||||
/// completion queue.
|
||||
///
|
||||
/// Caller is required to shutdown the server prior to shutting down the
|
||||
/// returned completion queue. Caller is also required to drain the
|
||||
/// completion queue after shutting it down. A typical usage scenario:
|
||||
///
|
||||
/// // While building the server:
|
||||
/// ServerBuilder builder;
|
||||
/// ...
|
||||
/// cq_ = builder.AddCompletionQueue();
|
||||
/// server_ = builder.BuildAndStart();
|
||||
///
|
||||
/// // While shutting down the server;
|
||||
/// server_->Shutdown();
|
||||
/// cq_->Shutdown(); // Always *after* the associated server's Shutdown()!
|
||||
/// // Drain the cq_ that was created
|
||||
/// void* ignored_tag;
|
||||
/// bool ignored_ok;
|
||||
/// while (cq_->Next(&ignored_tag, &ignored_ok)) { }
|
||||
///
|
||||
/// \param is_frequently_polled This is an optional parameter to inform gRPC
|
||||
/// library about whether this completion queue would be frequently polled
|
||||
/// (i.e. by calling \a Next() or \a AsyncNext()). The default value is
|
||||
/// 'true' and is the recommended setting. Setting this to 'false' (i.e.
|
||||
/// not polling the completion queue frequently) will have a significantly
|
||||
/// negative performance impact and hence should not be used in production
|
||||
/// use cases.
|
||||
std::unique_ptr<grpc::ServerCompletionQueue> AddCompletionQueue( |
||||
bool is_frequently_polled = true); |
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// Less commonly used RegisterService variants
|
||||
|
||||
/// Register a service. This call does not take ownership of the service.
|
||||
/// The service must exist for the lifetime of the \a Server instance
|
||||
/// returned by \a BuildAndStart(). Only matches requests with :authority \a
|
||||
/// host
|
||||
ServerBuilder& RegisterService(const grpc::string& host, |
||||
grpc::Service* service); |
||||
|
||||
/// Register a generic service.
|
||||
/// Matches requests with any :authority
|
||||
/// This is mostly useful for writing generic gRPC Proxies where the exact
|
||||
/// serialization format is unknown
|
||||
ServerBuilder& RegisterAsyncGenericService( |
||||
grpc::AsyncGenericService* service); |
||||
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
// Fine control knobs
|
||||
|
||||
/// Set max receive message size in bytes.
|
||||
/// The default is GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH.
|
||||
ServerBuilder& SetMaxReceiveMessageSize(int max_receive_message_size) { |
||||
max_receive_message_size_ = max_receive_message_size; |
||||
return *this; |
||||
} |
||||
|
||||
/// Set max send message size in bytes.
|
||||
/// The default is GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH.
|
||||
ServerBuilder& SetMaxSendMessageSize(int max_send_message_size) { |
||||
max_send_message_size_ = max_send_message_size; |
||||
return *this; |
||||
} |
||||
|
||||
/// \deprecated For backward compatibility.
|
||||
ServerBuilder& SetMaxMessageSize(int max_message_size) { |
||||
return SetMaxReceiveMessageSize(max_message_size); |
||||
} |
||||
|
||||
/// Set the support status for compression algorithms. All algorithms are
|
||||
/// enabled by default.
|
||||
///
|
||||
/// Incoming calls compressed with an unsupported algorithm will fail with
|
||||
/// \a GRPC_STATUS_UNIMPLEMENTED.
|
||||
ServerBuilder& SetCompressionAlgorithmSupportStatus( |
||||
grpc_compression_algorithm algorithm, bool enabled); |
||||
|
||||
/// The default compression level to use for all channel calls in the
|
||||
/// absence of a call-specific level.
|
||||
ServerBuilder& SetDefaultCompressionLevel(grpc_compression_level level); |
||||
|
||||
/// The default compression algorithm to use for all channel calls in the
|
||||
/// absence of a call-specific level. Note that it overrides any compression
|
||||
/// level set by \a SetDefaultCompressionLevel.
|
||||
ServerBuilder& SetDefaultCompressionAlgorithm( |
||||
grpc_compression_algorithm algorithm); |
||||
|
||||
/// Set the attached buffer pool for this server
|
||||
ServerBuilder& SetResourceQuota( |
||||
const grpc_impl::ResourceQuota& resource_quota); |
||||
|
||||
ServerBuilder& SetOption(std::unique_ptr<grpc::ServerBuilderOption> option); |
||||
|
||||
/// Options for synchronous servers.
|
||||
enum SyncServerOption { |
||||
NUM_CQS, ///< Number of completion queues.
|
||||
MIN_POLLERS, ///< Minimum number of polling threads.
|
||||
MAX_POLLERS, ///< Maximum number of polling threads.
|
||||
CQ_TIMEOUT_MSEC ///< Completion queue timeout in milliseconds.
|
||||
}; |
||||
|
||||
/// Only useful if this is a Synchronous server.
|
||||
ServerBuilder& SetSyncServerOption(SyncServerOption option, int value); |
||||
|
||||
/// Add a channel argument (an escape hatch to tuning core library parameters
|
||||
/// directly)
|
||||
template <class T> |
||||
ServerBuilder& AddChannelArgument(const grpc::string& arg, const T& value) { |
||||
return SetOption(grpc::MakeChannelArgumentOption(arg, value)); |
||||
} |
||||
|
||||
/// For internal use only: Register a ServerBuilderPlugin factory function.
|
||||
static void InternalAddPluginFactory( |
||||
std::unique_ptr<grpc::ServerBuilderPlugin> (*CreatePlugin)()); |
||||
|
||||
/// Enable a server workaround. Do not use unless you know what the workaround
|
||||
/// does. For explanation and detailed descriptions of workarounds, see
|
||||
/// doc/workarounds.md.
|
||||
ServerBuilder& EnableWorkaround(grpc_workaround_list id); |
||||
|
||||
/// NOTE: class experimental_type is not part of the public API of this class.
|
||||
/// TODO(yashykt): Integrate into public API when this is no longer
|
||||
/// experimental.
|
||||
class experimental_type { |
||||
public: |
||||
explicit experimental_type(grpc_impl::ServerBuilder* builder) |
||||
: builder_(builder) {} |
||||
|
||||
void SetInterceptorCreators( |
||||
std::vector<std::unique_ptr< |
||||
grpc::experimental::ServerInterceptorFactoryInterface>> |
||||
interceptor_creators) { |
||||
builder_->interceptor_creators_ = std::move(interceptor_creators); |
||||
} |
||||
|
||||
/// Register a generic service that uses the callback API.
|
||||
/// Matches requests with any :authority
|
||||
/// This is mostly useful for writing generic gRPC Proxies where the exact
|
||||
/// serialization format is unknown
|
||||
ServerBuilder& RegisterCallbackGenericService( |
||||
grpc::experimental::CallbackGenericService* service); |
||||
|
||||
private: |
||||
ServerBuilder* builder_; |
||||
}; |
||||
|
||||
/// NOTE: The function experimental() is not stable public API. It is a view
|
||||
/// to the experimental components of this class. It may be changed or removed
|
||||
/// at any time.
|
||||
experimental_type experimental() { return experimental_type(this); } |
||||
|
||||
protected: |
||||
/// Experimental, to be deprecated
|
||||
struct Port { |
||||
grpc::string addr; |
||||
std::shared_ptr<grpc_impl::ServerCredentials> creds; |
||||
int* selected_port; |
||||
}; |
||||
|
||||
/// Experimental, to be deprecated
|
||||
typedef std::unique_ptr<grpc::string> HostString; |
||||
struct NamedService { |
||||
explicit NamedService(grpc::Service* s) : service(s) {} |
||||
NamedService(const grpc::string& h, grpc::Service* s) |
||||
: host(new grpc::string(h)), service(s) {} |
||||
HostString host; |
||||
grpc::Service* service; |
||||
}; |
||||
|
||||
/// Experimental, to be deprecated
|
||||
std::vector<Port> ports() { return ports_; } |
||||
|
||||
/// Experimental, to be deprecated
|
||||
std::vector<NamedService*> services() { |
||||
std::vector<NamedService*> service_refs; |
||||
for (auto& ptr : services_) { |
||||
service_refs.push_back(ptr.get()); |
||||
} |
||||
return service_refs; |
||||
} |
||||
|
||||
/// Experimental, to be deprecated
|
||||
std::vector<grpc::ServerBuilderOption*> options() { |
||||
std::vector<grpc::ServerBuilderOption*> option_refs; |
||||
for (auto& ptr : options_) { |
||||
option_refs.push_back(ptr.get()); |
||||
} |
||||
return option_refs; |
||||
} |
||||
|
||||
private: |
||||
friend class ::grpc::testing::ServerBuilderPluginTest; |
||||
|
||||
struct SyncServerSettings { |
||||
SyncServerSettings() |
||||
: num_cqs(1), min_pollers(1), max_pollers(2), cq_timeout_msec(10000) {} |
||||
|
||||
/// Number of server completion queues to create to listen to incoming RPCs.
|
||||
int num_cqs; |
||||
|
||||
/// Minimum number of threads per completion queue that should be listening
|
||||
/// to incoming RPCs.
|
||||
int min_pollers; |
||||
|
||||
/// Maximum number of threads per completion queue that can be listening to
|
||||
/// incoming RPCs.
|
||||
int max_pollers; |
||||
|
||||
/// The timeout for server completion queue's AsyncNext call.
|
||||
int cq_timeout_msec; |
||||
}; |
||||
|
||||
int max_receive_message_size_; |
||||
int max_send_message_size_; |
||||
std::vector<std::unique_ptr<grpc::ServerBuilderOption>> options_; |
||||
std::vector<std::unique_ptr<NamedService>> services_; |
||||
std::vector<Port> ports_; |
||||
|
||||
SyncServerSettings sync_server_settings_; |
||||
|
||||
/// List of completion queues added via \a AddCompletionQueue method.
|
||||
std::vector<grpc::ServerCompletionQueue*> cqs_; |
||||
|
||||
std::shared_ptr<grpc_impl::ServerCredentials> creds_; |
||||
std::vector<std::unique_ptr<grpc::ServerBuilderPlugin>> plugins_; |
||||
grpc_resource_quota* resource_quota_; |
||||
grpc::AsyncGenericService* generic_service_{nullptr}; |
||||
grpc::experimental::CallbackGenericService* callback_generic_service_{ |
||||
nullptr}; |
||||
struct { |
||||
bool is_set; |
||||
grpc_compression_level level; |
||||
} maybe_default_compression_level_; |
||||
struct { |
||||
bool is_set; |
||||
grpc_compression_algorithm algorithm; |
||||
} maybe_default_compression_algorithm_; |
||||
uint32_t enabled_compression_algorithms_bitset_; |
||||
std::vector< |
||||
std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>> |
||||
interceptor_creators_; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_SERVER_BUILDER_IMPL_H
|
@ -0,0 +1,360 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2015 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SERVER_IMPL_H |
||||
#define GRPCPP_SERVER_IMPL_H |
||||
|
||||
#include <condition_variable> |
||||
#include <list> |
||||
#include <memory> |
||||
#include <mutex> |
||||
#include <vector> |
||||
|
||||
#include <grpc/compression.h> |
||||
#include <grpc/support/atm.h> |
||||
#include <grpcpp/completion_queue.h> |
||||
#include <grpcpp/impl/call.h> |
||||
#include <grpcpp/impl/codegen/client_interceptor.h> |
||||
#include <grpcpp/impl/codegen/grpc_library.h> |
||||
#include <grpcpp/impl/codegen/server_interface.h> |
||||
#include <grpcpp/impl/rpc_service_method.h> |
||||
#include <grpcpp/security/server_credentials.h> |
||||
#include <grpcpp/support/channel_arguments.h> |
||||
#include <grpcpp/support/config.h> |
||||
#include <grpcpp/support/status.h> |
||||
|
||||
struct grpc_server; |
||||
|
||||
namespace grpc { |
||||
|
||||
class AsyncGenericService; |
||||
class ServerContext; |
||||
|
||||
} // namespace grpc
|
||||
|
||||
namespace grpc_impl { |
||||
|
||||
class HealthCheckServiceInterface; |
||||
class ServerInitializer; |
||||
|
||||
/// Represents a gRPC server.
|
||||
///
|
||||
/// Use a \a grpc::ServerBuilder to create, configure, and start
|
||||
/// \a Server instances.
|
||||
class Server : public grpc::ServerInterface, private grpc::GrpcLibraryCodegen { |
||||
public: |
||||
~Server(); |
||||
|
||||
/// Block until the server shuts down.
|
||||
///
|
||||
/// \warning The server must be either shutting down or some other thread must
|
||||
/// call \a Shutdown for this function to ever return.
|
||||
void Wait() override; |
||||
|
||||
/// Global callbacks are a set of hooks that are called when server
|
||||
/// events occur. \a SetGlobalCallbacks method is used to register
|
||||
/// the hooks with gRPC. Note that
|
||||
/// the \a GlobalCallbacks instance will be shared among all
|
||||
/// \a Server instances in an application and can be set exactly
|
||||
/// once per application.
|
||||
class GlobalCallbacks { |
||||
public: |
||||
virtual ~GlobalCallbacks() {} |
||||
/// Called before server is created.
|
||||
virtual void UpdateArguments(grpc::ChannelArguments* args) {} |
||||
/// Called before application callback for each synchronous server request
|
||||
virtual void PreSynchronousRequest(grpc::ServerContext* context) = 0; |
||||
/// Called after application callback for each synchronous server request
|
||||
virtual void PostSynchronousRequest(grpc::ServerContext* context) = 0; |
||||
/// Called before server is started.
|
||||
virtual void PreServerStart(Server* server) {} |
||||
/// Called after a server port is added.
|
||||
virtual void AddPort(Server* server, const grpc::string& addr, |
||||
grpc::ServerCredentials* creds, int port) {} |
||||
}; |
||||
/// Set the global callback object. Can only be called once per application.
|
||||
/// Does not take ownership of callbacks, and expects the pointed to object
|
||||
/// to be alive until all server objects in the process have been destroyed.
|
||||
/// The same \a GlobalCallbacks object will be used throughout the
|
||||
/// application and is shared among all \a Server objects.
|
||||
static void SetGlobalCallbacks(GlobalCallbacks* callbacks); |
||||
|
||||
/// Returns a \em raw pointer to the underlying \a grpc_server instance.
|
||||
/// EXPERIMENTAL: for internal/test use only
|
||||
grpc_server* c_server(); |
||||
|
||||
/// Returns the health check service.
|
||||
grpc_impl::HealthCheckServiceInterface* GetHealthCheckService() const { |
||||
return health_check_service_.get(); |
||||
} |
||||
|
||||
/// Establish a channel for in-process communication
|
||||
std::shared_ptr<grpc::Channel> InProcessChannel( |
||||
const grpc::ChannelArguments& args); |
||||
|
||||
/// NOTE: class experimental_type is not part of the public API of this class.
|
||||
/// TODO(yashykt): Integrate into public API when this is no longer
|
||||
/// experimental.
|
||||
class experimental_type { |
||||
public: |
||||
explicit experimental_type(Server* server) : server_(server) {} |
||||
|
||||
/// Establish a channel for in-process communication with client
|
||||
/// interceptors
|
||||
std::shared_ptr<grpc::Channel> InProcessChannelWithInterceptors( |
||||
const grpc::ChannelArguments& args, |
||||
std::vector<std::unique_ptr< |
||||
grpc::experimental::ClientInterceptorFactoryInterface>> |
||||
interceptor_creators); |
||||
|
||||
private: |
||||
Server* server_; |
||||
}; |
||||
|
||||
/// NOTE: The function experimental() is not stable public API. It is a view
|
||||
/// to the experimental components of this class. It may be changed or removed
|
||||
/// at any time.
|
||||
experimental_type experimental() { return experimental_type(this); } |
||||
|
||||
protected: |
||||
/// Register a service. This call does not take ownership of the service.
|
||||
/// The service must exist for the lifetime of the Server instance.
|
||||
bool RegisterService(const grpc::string* host, |
||||
grpc::Service* service) override; |
||||
|
||||
/// Try binding the server to the given \a addr endpoint
|
||||
/// (port, and optionally including IP address to bind to).
|
||||
///
|
||||
/// It can be invoked multiple times. Should be used before
|
||||
/// starting the server.
|
||||
///
|
||||
/// \param addr The address to try to bind to the server (eg, localhost:1234,
|
||||
/// 192.168.1.1:31416, [::1]:27182, etc.).
|
||||
/// \param creds The credentials associated with the server.
|
||||
///
|
||||
/// \return bound port number on success, 0 on failure.
|
||||
///
|
||||
/// \warning It is an error to call this method on an already started server.
|
||||
int AddListeningPort(const grpc::string& addr, |
||||
grpc::ServerCredentials* creds) override; |
||||
|
||||
/// NOTE: This is *NOT* a public API. The server constructors are supposed to
|
||||
/// be used by \a ServerBuilder class only. The constructor will be made
|
||||
/// 'private' very soon.
|
||||
///
|
||||
/// Server constructors. To be used by \a ServerBuilder only.
|
||||
///
|
||||
/// \param max_message_size Maximum message length that the channel can
|
||||
/// receive.
|
||||
///
|
||||
/// \param args The channel args
|
||||
///
|
||||
/// \param sync_server_cqs The completion queues to use if the server is a
|
||||
/// synchronous server (or a hybrid server). The server polls for new RPCs on
|
||||
/// these queues
|
||||
///
|
||||
/// \param min_pollers The minimum number of polling threads per server
|
||||
/// completion queue (in param sync_server_cqs) to use for listening to
|
||||
/// incoming requests (used only in case of sync server)
|
||||
///
|
||||
/// \param max_pollers The maximum number of polling threads per server
|
||||
/// completion queue (in param sync_server_cqs) to use for listening to
|
||||
/// incoming requests (used only in case of sync server)
|
||||
///
|
||||
/// \param sync_cq_timeout_msec The timeout to use when calling AsyncNext() on
|
||||
/// server completion queues passed via sync_server_cqs param.
|
||||
Server( |
||||
int max_message_size, grpc::ChannelArguments* args, |
||||
std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>> |
||||
sync_server_cqs, |
||||
int min_pollers, int max_pollers, int sync_cq_timeout_msec, |
||||
grpc_resource_quota* server_rq = nullptr, |
||||
std::vector<std::unique_ptr< |
||||
grpc::experimental::ServerInterceptorFactoryInterface>> |
||||
interceptor_creators = std::vector<std::unique_ptr< |
||||
grpc::experimental::ServerInterceptorFactoryInterface>>()); |
||||
|
||||
/// Start the server.
|
||||
///
|
||||
/// \param cqs Completion queues for handling asynchronous services. The
|
||||
/// caller is required to keep all completion queues live until the server is
|
||||
/// destroyed.
|
||||
/// \param num_cqs How many completion queues does \a cqs hold.
|
||||
void Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) override; |
||||
|
||||
grpc_server* server() override { return server_; } |
||||
|
||||
private: |
||||
std::vector< |
||||
std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>* |
||||
interceptor_creators() override { |
||||
return &interceptor_creators_; |
||||
} |
||||
|
||||
friend class grpc::AsyncGenericService; |
||||
friend class grpc_impl::ServerBuilder; |
||||
friend class grpc_impl::ServerInitializer; |
||||
|
||||
class SyncRequest; |
||||
class CallbackRequestBase; |
||||
template <class ServerContextType> |
||||
class CallbackRequest; |
||||
class UnimplementedAsyncRequest; |
||||
class UnimplementedAsyncResponse; |
||||
|
||||
/// SyncRequestThreadManager is an implementation of ThreadManager. This class
|
||||
/// is responsible for polling for incoming RPCs and calling the RPC handlers.
|
||||
/// This is only used in case of a Sync server (i.e a server exposing a sync
|
||||
/// interface)
|
||||
class SyncRequestThreadManager; |
||||
|
||||
/// Register a generic service. This call does not take ownership of the
|
||||
/// service. The service must exist for the lifetime of the Server instance.
|
||||
void RegisterAsyncGenericService(grpc::AsyncGenericService* service) override; |
||||
|
||||
/// NOTE: class experimental_registration_type is not part of the public API
|
||||
/// of this class
|
||||
/// TODO(vjpai): Move these contents to the public API of Server when
|
||||
/// they are no longer experimental
|
||||
class experimental_registration_type final |
||||
: public experimental_registration_interface { |
||||
public: |
||||
explicit experimental_registration_type(Server* server) : server_(server) {} |
||||
void RegisterCallbackGenericService( |
||||
grpc::experimental::CallbackGenericService* service) override { |
||||
server_->RegisterCallbackGenericService(service); |
||||
} |
||||
|
||||
private: |
||||
Server* server_; |
||||
}; |
||||
|
||||
/// TODO(vjpai): Mark this override when experimental type above is deleted
|
||||
void RegisterCallbackGenericService( |
||||
grpc::experimental::CallbackGenericService* service); |
||||
|
||||
/// NOTE: The function experimental_registration() is not stable public API.
|
||||
/// It is a view to the experimental components of this class. It may be
|
||||
/// changed or removed at any time.
|
||||
experimental_registration_interface* experimental_registration() override { |
||||
return &experimental_registration_; |
||||
} |
||||
|
||||
void PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops, |
||||
grpc::internal::Call* call) override; |
||||
|
||||
void ShutdownInternal(gpr_timespec deadline) override; |
||||
|
||||
int max_receive_message_size() const override { |
||||
return max_receive_message_size_; |
||||
} |
||||
|
||||
grpc::CompletionQueue* CallbackCQ() override; |
||||
|
||||
grpc_impl::ServerInitializer* initializer(); |
||||
|
||||
// A vector of interceptor factory objects.
|
||||
// This should be destroyed after health_check_service_ and this requirement
|
||||
// is satisfied by declaring interceptor_creators_ before
|
||||
// health_check_service_. (C++ mandates that member objects be destroyed in
|
||||
// the reverse order of initialization.)
|
||||
std::vector< |
||||
std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>> |
||||
interceptor_creators_; |
||||
|
||||
const int max_receive_message_size_; |
||||
|
||||
/// The following completion queues are ONLY used in case of Sync API
|
||||
/// i.e. if the server has any services with sync methods. The server uses
|
||||
/// these completion queues to poll for new RPCs
|
||||
std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>> |
||||
sync_server_cqs_; |
||||
|
||||
/// List of \a ThreadManager instances (one for each cq in
|
||||
/// the \a sync_server_cqs)
|
||||
std::vector<std::unique_ptr<SyncRequestThreadManager>> sync_req_mgrs_; |
||||
|
||||
// Outstanding unmatched callback requests, indexed by method.
|
||||
// NOTE: Using a gpr_atm rather than atomic_int because atomic_int isn't
|
||||
// copyable or movable and thus will cause compilation errors. We
|
||||
// actually only want to extend the vector before the threaded use
|
||||
// starts, but this is still a limitation.
|
||||
std::vector<gpr_atm> callback_unmatched_reqs_count_; |
||||
|
||||
// List of callback requests to start when server actually starts.
|
||||
std::list<CallbackRequestBase*> callback_reqs_to_start_; |
||||
|
||||
// For registering experimental callback generic service; remove when that
|
||||
// method longer experimental
|
||||
experimental_registration_type experimental_registration_{this}; |
||||
|
||||
// Server status
|
||||
grpc::internal::Mutex mu_; |
||||
bool started_; |
||||
bool shutdown_; |
||||
bool shutdown_notified_; // Was notify called on the shutdown_cv_
|
||||
|
||||
grpc::internal::CondVar shutdown_cv_; |
||||
|
||||
// It is ok (but not required) to nest callback_reqs_mu_ under mu_ .
|
||||
// Incrementing callback_reqs_outstanding_ is ok without a lock but it must be
|
||||
// decremented under the lock in case it is the last request and enables the
|
||||
// server shutdown. The increment is performance-critical since it happens
|
||||
// during periods of increasing load; the decrement happens only when memory
|
||||
// is maxed out, during server shutdown, or (possibly in a future version)
|
||||
// during decreasing load, so it is less performance-critical.
|
||||
grpc::internal::Mutex callback_reqs_mu_; |
||||
grpc::internal::CondVar callback_reqs_done_cv_; |
||||
std::atomic_int callback_reqs_outstanding_{0}; |
||||
|
||||
std::shared_ptr<GlobalCallbacks> global_callbacks_; |
||||
|
||||
std::vector<grpc::string> services_; |
||||
bool has_async_generic_service_{false}; |
||||
bool has_callback_generic_service_{false}; |
||||
|
||||
// Pointer to the wrapped grpc_server.
|
||||
grpc_server* server_; |
||||
|
||||
std::unique_ptr<grpc_impl::ServerInitializer> server_initializer_; |
||||
|
||||
std::unique_ptr<grpc_impl::HealthCheckServiceInterface> health_check_service_; |
||||
bool health_check_service_disabled_; |
||||
|
||||
// When appropriate, use a default callback generic service to handle
|
||||
// unimplemented methods
|
||||
std::unique_ptr<grpc::experimental::CallbackGenericService> |
||||
unimplemented_service_; |
||||
|
||||
// A special handler for resource exhausted in sync case
|
||||
std::unique_ptr<grpc::internal::MethodHandler> resource_exhausted_handler_; |
||||
|
||||
// Handler for callback generic service, if any
|
||||
std::unique_ptr<grpc::internal::MethodHandler> generic_handler_; |
||||
|
||||
// callback_cq_ references the callbackable completion queue associated
|
||||
// with this server (if any). It is set on the first call to CallbackCQ().
|
||||
// It is _not owned_ by the server; ownership belongs with its internal
|
||||
// shutdown callback tag (invoked when the CQ is fully shutdown).
|
||||
// It is protected by mu_
|
||||
grpc::CompletionQueue* callback_cq_ = nullptr; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_SERVER_IMPL_H
|
@ -0,0 +1,42 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2016 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SERVER_POSIX_IMPL_H |
||||
#define GRPCPP_SERVER_POSIX_IMPL_H |
||||
|
||||
#include <memory> |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
#include <grpcpp/server.h> |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
#ifdef GPR_SUPPORT_CHANNELS_FROM_FD |
||||
|
||||
/// Add a new client to a \a Server communicating over the given
|
||||
/// file descriptor.
|
||||
///
|
||||
/// \param server The server to add the client to.
|
||||
/// \param fd The file descriptor representing a socket.
|
||||
void AddInsecureChannelFromFd(grpc::Server* server, int fd); |
||||
|
||||
#endif // GPR_SUPPORT_CHANNELS_FROM_FD
|
||||
|
||||
} // namespace grpc
|
||||
|
||||
#endif // GRPCPP_SERVER_POSIX_IMPL_H
|
@ -0,0 +1,48 @@ |
||||
/*
|
||||
* |
||||
* Copyright 2017 gRPC authors. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
* |
||||
*/ |
||||
|
||||
#ifndef GRPCPP_SUPPORT_ERROR_DETAILS_IMPL_H |
||||
#define GRPCPP_SUPPORT_ERROR_DETAILS_IMPL_H |
||||
|
||||
#include <grpcpp/support/status.h> |
||||
|
||||
namespace google { |
||||
namespace rpc { |
||||
class Status; |
||||
} // namespace rpc
|
||||
} // namespace google
|
||||
|
||||
namespace grpc_impl { |
||||
|
||||
/// Map a \a grpc::Status to a \a google::rpc::Status.
|
||||
/// The given \a to object will be cleared.
|
||||
/// On success, returns status with OK.
|
||||
/// Returns status with \a INVALID_ARGUMENT, if failed to deserialize.
|
||||
/// Returns status with \a FAILED_PRECONDITION, if \a to is nullptr.
|
||||
grpc::Status ExtractErrorDetails(const grpc::Status& from, |
||||
::google::rpc::Status* to); |
||||
|
||||
/// Map \a google::rpc::Status to a \a grpc::Status.
|
||||
/// Returns OK on success.
|
||||
/// Returns status with \a FAILED_PRECONDITION if \a to is nullptr.
|
||||
grpc::Status SetErrorDetails(const ::google::rpc::Status& from, |
||||
grpc::Status* to); |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_SUPPORT_ERROR_DETAILS_IMPL_H
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue