mirror of https://github.com/grpc/grpc.git
commit
4198c4fcc6
245 changed files with 6688 additions and 2986 deletions
@ -1,16 +1,8 @@ |
||||
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.") |
||||
|
||||
python_configure(name = "local_config_python") |
||||
pip_repositories() |
||||
pip_install() |
||||
|
@ -0,0 +1,84 @@ |
||||
"""Utility functions for generating protobuf code.""" |
||||
|
||||
_PROTO_EXTENSION = ".proto" |
||||
|
||||
def get_proto_root(workspace_root): |
||||
"""Gets the root protobuf directory. |
||||
|
||||
Args: |
||||
workspace_root: context.label.workspace_root |
||||
|
||||
Returns: |
||||
The directory relative to which generated include paths should be. |
||||
""" |
||||
if workspace_root: |
||||
return "/{}".format(workspace_root) |
||||
else: |
||||
return "" |
||||
|
||||
def _strip_proto_extension(proto_filename): |
||||
if not proto_filename.endswith(_PROTO_EXTENSION): |
||||
fail('"{}" does not end with "{}"'.format( |
||||
proto_filename, |
||||
_PROTO_EXTENSION, |
||||
)) |
||||
return proto_filename[:-len(_PROTO_EXTENSION)] |
||||
|
||||
def proto_path_to_generated_filename(proto_path, fmt_str): |
||||
"""Calculates the name of a generated file for a protobuf path. |
||||
|
||||
For example, "examples/protos/helloworld.proto" might map to |
||||
"helloworld.pb.h". |
||||
|
||||
Args: |
||||
proto_path: The path to the .proto file. |
||||
fmt_str: A format string used to calculate the generated filename. For |
||||
example, "{}.pb.h" might be used to calculate a C++ header filename. |
||||
|
||||
Returns: |
||||
The generated filename. |
||||
""" |
||||
return fmt_str.format(_strip_proto_extension(proto_path)) |
||||
|
||||
def _get_include_directory(include): |
||||
directory = include.path |
||||
if directory.startswith("external"): |
||||
external_separator = directory.find("/") |
||||
repository_separator = directory.find("/", external_separator + 1) |
||||
return directory[:repository_separator] |
||||
else: |
||||
return "." |
||||
|
||||
def get_include_protoc_args(includes): |
||||
"""Returns protoc args that imports protos relative to their import root. |
||||
|
||||
Args: |
||||
includes: A list of included proto files. |
||||
|
||||
Returns: |
||||
A list of arguments to be passed to protoc. For example, ["--proto_path=."]. |
||||
""" |
||||
return [ |
||||
"--proto_path={}".format(_get_include_directory(include)) |
||||
for include in includes |
||||
] |
||||
|
||||
def get_plugin_args(plugin, flags, dir_out, generate_mocks): |
||||
"""Returns arguments configuring protoc to use a plugin for a language. |
||||
|
||||
Args: |
||||
plugin: An executable file to run as the protoc plugin. |
||||
flags: The plugin flags to be passed to protoc. |
||||
dir_out: The output directory for the plugin. |
||||
generate_mocks: A bool indicating whether to generate mocks. |
||||
|
||||
Returns: |
||||
A list of protoc arguments configuring the plugin. |
||||
""" |
||||
augmented_flags = list(flags) |
||||
if generate_mocks: |
||||
augmented_flags.append("generate_mock_code=true") |
||||
return [ |
||||
"--plugin=protoc-gen-PLUGIN=" + plugin.path, |
||||
"--PLUGIN_out=" + ",".join(augmented_flags) + ":" + dir_out, |
||||
] |
@ -0,0 +1,203 @@ |
||||
"""Generates and compiles Python gRPC stubs from proto_library rules.""" |
||||
|
||||
load("@grpc_python_dependencies//:requirements.bzl", "requirement") |
||||
load( |
||||
"//bazel:protobuf.bzl", |
||||
"get_include_protoc_args", |
||||
"get_plugin_args", |
||||
"get_proto_root", |
||||
"proto_path_to_generated_filename", |
||||
) |
||||
|
||||
_GENERATED_PROTO_FORMAT = "{}_pb2.py" |
||||
_GENERATED_GRPC_PROTO_FORMAT = "{}_pb2_grpc.py" |
||||
|
||||
def _get_staged_proto_file(context, source_file): |
||||
if source_file.dirname == context.label.package: |
||||
return source_file |
||||
else: |
||||
copied_proto = context.actions.declare_file(source_file.basename) |
||||
context.actions.run_shell( |
||||
inputs = [source_file], |
||||
outputs = [copied_proto], |
||||
command = "cp {} {}".format(source_file.path, copied_proto.path), |
||||
mnemonic = "CopySourceProto", |
||||
) |
||||
return copied_proto |
||||
|
||||
def _generate_py_impl(context): |
||||
protos = [] |
||||
for src in context.attr.deps: |
||||
for file in src.proto.direct_sources: |
||||
protos.append(_get_staged_proto_file(context, file)) |
||||
includes = [ |
||||
file |
||||
for src in context.attr.deps |
||||
for file in src.proto.transitive_imports |
||||
] |
||||
proto_root = get_proto_root(context.label.workspace_root) |
||||
format_str = (_GENERATED_GRPC_PROTO_FORMAT if context.executable.plugin else _GENERATED_PROTO_FORMAT) |
||||
out_files = [ |
||||
context.actions.declare_file( |
||||
proto_path_to_generated_filename( |
||||
proto.basename, |
||||
format_str, |
||||
), |
||||
) |
||||
for proto in protos |
||||
] |
||||
|
||||
arguments = [] |
||||
tools = [context.executable._protoc] |
||||
if context.executable.plugin: |
||||
arguments += get_plugin_args( |
||||
context.executable.plugin, |
||||
context.attr.flags, |
||||
context.genfiles_dir.path, |
||||
False, |
||||
) |
||||
tools += [context.executable.plugin] |
||||
else: |
||||
arguments += [ |
||||
"--python_out={}:{}".format( |
||||
",".join(context.attr.flags), |
||||
context.genfiles_dir.path, |
||||
), |
||||
] |
||||
|
||||
arguments += get_include_protoc_args(includes) |
||||
arguments += [ |
||||
"--proto_path={}".format(context.genfiles_dir.path) |
||||
for proto in protos |
||||
] |
||||
for proto in protos: |
||||
massaged_path = proto.path |
||||
if massaged_path.startswith(context.genfiles_dir.path): |
||||
massaged_path = proto.path[len(context.genfiles_dir.path) + 1:] |
||||
arguments.append(massaged_path) |
||||
|
||||
well_known_proto_files = [] |
||||
if context.attr.well_known_protos: |
||||
well_known_proto_directory = context.attr.well_known_protos.files.to_list( |
||||
)[0].dirname |
||||
|
||||
arguments += ["-I{}".format(well_known_proto_directory + "/../..")] |
||||
well_known_proto_files = context.attr.well_known_protos.files.to_list() |
||||
|
||||
context.actions.run( |
||||
inputs = protos + includes + well_known_proto_files, |
||||
tools = tools, |
||||
outputs = out_files, |
||||
executable = context.executable._protoc, |
||||
arguments = arguments, |
||||
mnemonic = "ProtocInvocation", |
||||
) |
||||
return struct(files = depset(out_files)) |
||||
|
||||
__generate_py = rule( |
||||
attrs = { |
||||
"deps": attr.label_list( |
||||
mandatory = True, |
||||
allow_empty = False, |
||||
providers = ["proto"], |
||||
), |
||||
"plugin": attr.label( |
||||
executable = True, |
||||
providers = ["files_to_run"], |
||||
cfg = "host", |
||||
), |
||||
"flags": attr.string_list( |
||||
mandatory = False, |
||||
allow_empty = True, |
||||
), |
||||
"well_known_protos": attr.label(mandatory = False), |
||||
"_protoc": attr.label( |
||||
default = Label("//external:protocol_compiler"), |
||||
executable = True, |
||||
cfg = "host", |
||||
), |
||||
}, |
||||
output_to_genfiles = True, |
||||
implementation = _generate_py_impl, |
||||
) |
||||
|
||||
def _generate_py(well_known_protos, **kwargs): |
||||
if well_known_protos: |
||||
__generate_py( |
||||
well_known_protos = "@com_google_protobuf//:well_known_protos", |
||||
**kwargs |
||||
) |
||||
else: |
||||
__generate_py(**kwargs) |
||||
|
||||
_WELL_KNOWN_PROTO_LIBS = [ |
||||
"@com_google_protobuf//:any_proto", |
||||
"@com_google_protobuf//:api_proto", |
||||
"@com_google_protobuf//:compiler_plugin_proto", |
||||
"@com_google_protobuf//:descriptor_proto", |
||||
"@com_google_protobuf//:duration_proto", |
||||
"@com_google_protobuf//:empty_proto", |
||||
"@com_google_protobuf//:field_mask_proto", |
||||
"@com_google_protobuf//:source_context_proto", |
||||
"@com_google_protobuf//:struct_proto", |
||||
"@com_google_protobuf//:timestamp_proto", |
||||
"@com_google_protobuf//:type_proto", |
||||
"@com_google_protobuf//:wrappers_proto", |
||||
] |
||||
|
||||
def py_proto_library( |
||||
name, |
||||
deps, |
||||
well_known_protos = True, |
||||
proto_only = False, |
||||
**kwargs): |
||||
"""Generate python code for a protobuf. |
||||
|
||||
Args: |
||||
name: The name of the target. |
||||
deps: A list of dependencies. Must contain a single element. |
||||
well_known_protos: A bool indicating whether or not to include well-known |
||||
protos. |
||||
proto_only: A bool indicating whether to generate vanilla protobuf code |
||||
or to also generate gRPC code. |
||||
""" |
||||
if len(deps) > 1: |
||||
fail("The supported length of 'deps' is 1.") |
||||
|
||||
codegen_target = "_{}_codegen".format(name) |
||||
codegen_grpc_target = "_{}_grpc_codegen".format(name) |
||||
|
||||
well_known_proto_rules = _WELL_KNOWN_PROTO_LIBS if well_known_protos else [] |
||||
|
||||
_generate_py( |
||||
name = codegen_target, |
||||
deps = deps, |
||||
well_known_protos = well_known_protos, |
||||
**kwargs |
||||
) |
||||
|
||||
if not proto_only: |
||||
_generate_py( |
||||
name = codegen_grpc_target, |
||||
deps = deps, |
||||
plugin = "//:grpc_python_plugin", |
||||
well_known_protos = well_known_protos, |
||||
**kwargs |
||||
) |
||||
|
||||
native.py_library( |
||||
name = name, |
||||
srcs = [ |
||||
":{}".format(codegen_grpc_target), |
||||
":{}".format(codegen_target), |
||||
], |
||||
deps = [requirement("protobuf")], |
||||
**kwargs |
||||
) |
||||
else: |
||||
native.py_library( |
||||
name = name, |
||||
srcs = [":{}".format(codegen_target), ":{}".format(codegen_target)], |
||||
deps = [requirement("protobuf")], |
||||
**kwargs |
||||
) |
@ -0,0 +1,281 @@ |
||||
/*
|
||||
* |
||||
* 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_CREDENTIALS_IMPL_H |
||||
#define GRPCPP_SECURITY_CREDENTIALS_IMPL_H |
||||
|
||||
#include <map> |
||||
#include <memory> |
||||
#include <vector> |
||||
|
||||
#include <grpc/grpc_security_constants.h> |
||||
#include <grpcpp/impl/codegen/client_interceptor.h> |
||||
#include <grpcpp/impl/codegen/grpc_library.h> |
||||
#include <grpcpp/security/auth_context.h> |
||||
#include <grpcpp/support/channel_arguments.h> |
||||
#include <grpcpp/support/status.h> |
||||
#include <grpcpp/support/string_ref.h> |
||||
|
||||
struct grpc_call; |
||||
|
||||
namespace grpc_impl { |
||||
|
||||
class Channel; |
||||
class ChannelCredentials; |
||||
class CallCredentials; |
||||
class SecureCallCredentials; |
||||
class SecureChannelCredentials; |
||||
|
||||
std::shared_ptr<::grpc::Channel> CreateCustomChannelImpl( |
||||
const grpc::string& target, |
||||
const std::shared_ptr<ChannelCredentials>& creds, |
||||
const grpc::ChannelArguments& args); |
||||
|
||||
namespace experimental { |
||||
std::shared_ptr<::grpc::Channel> CreateCustomChannelWithInterceptors( |
||||
const grpc::string& target, |
||||
const std::shared_ptr<ChannelCredentials>& creds, |
||||
const grpc::ChannelArguments& args, |
||||
std::vector< |
||||
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> |
||||
interceptor_creators); |
||||
} |
||||
|
||||
/// A channel credentials object encapsulates all the state needed by a client
|
||||
/// to authenticate with a server for a given channel.
|
||||
/// It can make various assertions, e.g., about the client’s identity, role
|
||||
/// for all the calls on that channel.
|
||||
///
|
||||
/// \see https://grpc.io/docs/guides/auth.html
|
||||
class ChannelCredentials : private grpc::GrpcLibraryCodegen { |
||||
public: |
||||
ChannelCredentials(); |
||||
~ChannelCredentials(); |
||||
|
||||
protected: |
||||
friend std::shared_ptr<ChannelCredentials> CompositeChannelCredentials( |
||||
const std::shared_ptr<ChannelCredentials>& channel_creds, |
||||
const std::shared_ptr<CallCredentials>& call_creds); |
||||
|
||||
virtual SecureChannelCredentials* AsSecureCredentials() = 0; |
||||
|
||||
private: |
||||
friend std::shared_ptr<::grpc::Channel> CreateCustomChannelImpl( |
||||
const grpc::string& target, |
||||
const std::shared_ptr<ChannelCredentials>& creds, |
||||
const grpc::ChannelArguments& args); |
||||
|
||||
friend std::shared_ptr<::grpc::Channel> |
||||
grpc_impl::experimental::CreateCustomChannelWithInterceptors( |
||||
const grpc::string& target, |
||||
const std::shared_ptr<ChannelCredentials>& creds, |
||||
const grpc::ChannelArguments& args, |
||||
std::vector<std::unique_ptr< |
||||
grpc::experimental::ClientInterceptorFactoryInterface>> |
||||
interceptor_creators); |
||||
|
||||
virtual std::shared_ptr<::grpc::Channel> CreateChannelImpl( |
||||
const grpc::string& target, const grpc::ChannelArguments& args) = 0; |
||||
|
||||
// This function should have been a pure virtual function, but it is
|
||||
// implemented as a virtual function so that it does not break API.
|
||||
virtual std::shared_ptr<::grpc::Channel> CreateChannelWithInterceptors( |
||||
const grpc::string& target, const grpc::ChannelArguments& args, |
||||
std::vector<std::unique_ptr< |
||||
grpc::experimental::ClientInterceptorFactoryInterface>> |
||||
interceptor_creators) { |
||||
return nullptr; |
||||
} |
||||
}; |
||||
|
||||
/// A call credentials object encapsulates the state needed by a client to
|
||||
/// authenticate with a server for a given call on a channel.
|
||||
///
|
||||
/// \see https://grpc.io/docs/guides/auth.html
|
||||
class CallCredentials : private grpc::GrpcLibraryCodegen { |
||||
public: |
||||
CallCredentials(); |
||||
~CallCredentials(); |
||||
|
||||
/// Apply this instance's credentials to \a call.
|
||||
virtual bool ApplyToCall(grpc_call* call) = 0; |
||||
|
||||
protected: |
||||
friend std::shared_ptr<ChannelCredentials> CompositeChannelCredentials( |
||||
const std::shared_ptr<ChannelCredentials>& channel_creds, |
||||
const std::shared_ptr<CallCredentials>& call_creds); |
||||
|
||||
friend std::shared_ptr<CallCredentials> CompositeCallCredentials( |
||||
const std::shared_ptr<CallCredentials>& creds1, |
||||
const std::shared_ptr<CallCredentials>& creds2); |
||||
|
||||
virtual SecureCallCredentials* AsSecureCredentials() = 0; |
||||
}; |
||||
|
||||
/// Options used to build SslCredentials.
|
||||
struct SslCredentialsOptions { |
||||
/// The buffer containing the PEM encoding of the server root certificates. If
|
||||
/// this parameter is empty, the default roots will be used. The default
|
||||
/// roots can be overridden using the \a GRPC_DEFAULT_SSL_ROOTS_FILE_PATH
|
||||
/// environment variable pointing to a file on the file system containing the
|
||||
/// roots.
|
||||
grpc::string pem_root_certs; |
||||
|
||||
/// The buffer containing the PEM encoding of the client's private key. This
|
||||
/// parameter can be empty if the client does not have a private key.
|
||||
grpc::string pem_private_key; |
||||
|
||||
/// The buffer containing the PEM encoding of the client's certificate chain.
|
||||
/// This parameter can be empty if the client does not have a certificate
|
||||
/// chain.
|
||||
grpc::string pem_cert_chain; |
||||
}; |
||||
|
||||
// Factories for building different types of Credentials The functions may
|
||||
// return empty shared_ptr when credentials cannot be created. If a
|
||||
// Credentials pointer is returned, it can still be invalid when used to create
|
||||
// a channel. A lame channel will be created then and all rpcs will fail on it.
|
||||
|
||||
/// Builds credentials with reasonable defaults.
|
||||
///
|
||||
/// \warning Only use these credentials when connecting to a Google endpoint.
|
||||
/// Using these credentials to connect to any other service may result in this
|
||||
/// service being able to impersonate your client for requests to Google
|
||||
/// services.
|
||||
std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials(); |
||||
|
||||
/// Builds SSL Credentials given SSL specific options
|
||||
std::shared_ptr<ChannelCredentials> SslCredentials( |
||||
const SslCredentialsOptions& options); |
||||
|
||||
/// Builds credentials for use when running in GCE
|
||||
///
|
||||
/// \warning Only use these credentials when connecting to a Google endpoint.
|
||||
/// Using these credentials to connect to any other service may result in this
|
||||
/// service being able to impersonate your client for requests to Google
|
||||
/// services.
|
||||
std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials(); |
||||
|
||||
constexpr long kMaxAuthTokenLifetimeSecs = 3600; |
||||
|
||||
/// Builds Service Account JWT Access credentials.
|
||||
/// json_key is the JSON key string containing the client's private key.
|
||||
/// token_lifetime_seconds is the lifetime in seconds of each Json Web Token
|
||||
/// (JWT) created with this credentials. It should not exceed
|
||||
/// \a kMaxAuthTokenLifetimeSecs or will be cropped to this value.
|
||||
std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials( |
||||
const grpc::string& json_key, |
||||
long token_lifetime_seconds = grpc_impl::kMaxAuthTokenLifetimeSecs); |
||||
|
||||
/// Builds refresh token credentials.
|
||||
/// json_refresh_token is the JSON string containing the refresh token along
|
||||
/// with a client_id and client_secret.
|
||||
///
|
||||
/// \warning Only use these credentials when connecting to a Google endpoint.
|
||||
/// Using these credentials to connect to any other service may result in this
|
||||
/// service being able to impersonate your client for requests to Google
|
||||
/// services.
|
||||
std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials( |
||||
const grpc::string& json_refresh_token); |
||||
|
||||
/// Builds access token credentials.
|
||||
/// access_token is an oauth2 access token that was fetched using an out of band
|
||||
/// mechanism.
|
||||
///
|
||||
/// \warning Only use these credentials when connecting to a Google endpoint.
|
||||
/// Using these credentials to connect to any other service may result in this
|
||||
/// service being able to impersonate your client for requests to Google
|
||||
/// services.
|
||||
std::shared_ptr<CallCredentials> AccessTokenCredentials( |
||||
const grpc::string& access_token); |
||||
|
||||
/// Builds IAM credentials.
|
||||
///
|
||||
/// \warning Only use these credentials when connecting to a Google endpoint.
|
||||
/// Using these credentials to connect to any other service may result in this
|
||||
/// service being able to impersonate your client for requests to Google
|
||||
/// services.
|
||||
std::shared_ptr<CallCredentials> GoogleIAMCredentials( |
||||
const grpc::string& authorization_token, |
||||
const grpc::string& authority_selector); |
||||
|
||||
/// Combines a channel credentials and a call credentials into a composite
|
||||
/// channel credentials.
|
||||
std::shared_ptr<ChannelCredentials> CompositeChannelCredentials( |
||||
const std::shared_ptr<ChannelCredentials>& channel_creds, |
||||
const std::shared_ptr<CallCredentials>& call_creds); |
||||
|
||||
/// Combines two call credentials objects into a composite call credentials.
|
||||
std::shared_ptr<CallCredentials> CompositeCallCredentials( |
||||
const std::shared_ptr<CallCredentials>& creds1, |
||||
const std::shared_ptr<CallCredentials>& creds2); |
||||
|
||||
/// Credentials for an unencrypted, unauthenticated channel
|
||||
std::shared_ptr<ChannelCredentials> InsecureChannelCredentials(); |
||||
|
||||
/// Credentials for a channel using Cronet.
|
||||
std::shared_ptr<ChannelCredentials> CronetChannelCredentials(void* engine); |
||||
|
||||
/// User defined metadata credentials.
|
||||
class MetadataCredentialsPlugin { |
||||
public: |
||||
virtual ~MetadataCredentialsPlugin() {} |
||||
|
||||
/// If this method returns true, the Process function will be scheduled in
|
||||
/// a different thread from the one processing the call.
|
||||
virtual bool IsBlocking() const { return true; } |
||||
|
||||
/// Type of credentials this plugin is implementing.
|
||||
virtual const char* GetType() const { return ""; } |
||||
|
||||
/// Gets the auth metatada produced by this plugin.
|
||||
/// The fully qualified method name is:
|
||||
/// service_url + "/" + method_name.
|
||||
/// The channel_auth_context contains (among other things), the identity of
|
||||
/// the server.
|
||||
virtual grpc::Status GetMetadata( |
||||
grpc::string_ref service_url, grpc::string_ref method_name, |
||||
const grpc::AuthContext& channel_auth_context, |
||||
std::multimap<grpc::string, grpc::string>* metadata) = 0; |
||||
}; |
||||
|
||||
std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin( |
||||
std::unique_ptr<MetadataCredentialsPlugin> plugin); |
||||
|
||||
namespace experimental { |
||||
|
||||
/// Options used to build AltsCredentials.
|
||||
struct AltsCredentialsOptions { |
||||
/// service accounts of target endpoint that will be acceptable
|
||||
/// by the client. If service accounts are provided and none of them matches
|
||||
/// that of the server, authentication will fail.
|
||||
std::vector<grpc::string> target_service_accounts; |
||||
}; |
||||
|
||||
/// Builds ALTS Credentials given ALTS specific options
|
||||
std::shared_ptr<ChannelCredentials> AltsCredentials( |
||||
const AltsCredentialsOptions& options); |
||||
|
||||
/// Builds Local Credentials.
|
||||
std::shared_ptr<ChannelCredentials> LocalCredentials( |
||||
grpc_local_connect_type type); |
||||
|
||||
} // namespace experimental
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_SECURITY_CREDENTIALS_IMPL_H
|
@ -0,0 +1,152 @@ |
||||
/*
|
||||
* |
||||
* 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_SUPPORT_CHANNEL_ARGUMENTS_IMPL_H |
||||
#define GRPCPP_SUPPORT_CHANNEL_ARGUMENTS_IMPL_H |
||||
|
||||
#include <list> |
||||
#include <vector> |
||||
|
||||
#include <grpc/compression.h> |
||||
#include <grpc/grpc.h> |
||||
#include <grpcpp/resource_quota.h> |
||||
#include <grpcpp/support/config.h> |
||||
|
||||
namespace grpc { |
||||
namespace testing { |
||||
class ChannelArgumentsTest; |
||||
} // namespace testing
|
||||
} // namespace grpc
|
||||
|
||||
namespace grpc_impl { |
||||
|
||||
class SecureChannelCredentials; |
||||
|
||||
/// Options for channel creation. The user can use generic setters to pass
|
||||
/// key value pairs down to C channel creation code. For gRPC related options,
|
||||
/// concrete setters are provided.
|
||||
class ChannelArguments { |
||||
public: |
||||
ChannelArguments(); |
||||
~ChannelArguments(); |
||||
|
||||
ChannelArguments(const ChannelArguments& other); |
||||
ChannelArguments& operator=(ChannelArguments other) { |
||||
Swap(other); |
||||
return *this; |
||||
} |
||||
|
||||
void Swap(ChannelArguments& other); |
||||
|
||||
/// Dump arguments in this instance to \a channel_args. Does not take
|
||||
/// ownership of \a channel_args.
|
||||
///
|
||||
/// Note that the underlying arguments are shared. Changes made to either \a
|
||||
/// channel_args or this instance would be reflected on both.
|
||||
void SetChannelArgs(grpc_channel_args* channel_args) const; |
||||
|
||||
// gRPC specific channel argument setters
|
||||
/// Set target name override for SSL host name checking. This option is for
|
||||
/// testing only and should never be used in production.
|
||||
void SetSslTargetNameOverride(const grpc::string& name); |
||||
// TODO(yangg) add flow control options
|
||||
/// Set the compression algorithm for the channel.
|
||||
void SetCompressionAlgorithm(grpc_compression_algorithm algorithm); |
||||
|
||||
/// Set the grpclb fallback timeout (in ms) for the channel. If this amount
|
||||
/// of time has passed but we have not gotten any non-empty \a serverlist from
|
||||
/// the balancer, we will fall back to use the backend address(es) returned by
|
||||
/// the resolver.
|
||||
void SetGrpclbFallbackTimeout(int fallback_timeout); |
||||
|
||||
/// For client channel's, the socket mutator operates on
|
||||
/// "channel" sockets. For server's, the socket mutator operates
|
||||
/// only on "listen" sockets.
|
||||
/// TODO(apolcyn): allow socket mutators to also operate
|
||||
/// on server "channel" sockets, and adjust the socket mutator
|
||||
/// object to be more speficic about which type of socket
|
||||
/// it should operate on.
|
||||
void SetSocketMutator(grpc_socket_mutator* mutator); |
||||
|
||||
/// Set the string to prepend to the user agent.
|
||||
void SetUserAgentPrefix(const grpc::string& user_agent_prefix); |
||||
|
||||
/// Set the buffer pool to be attached to the constructed channel.
|
||||
void SetResourceQuota(const grpc::ResourceQuota& resource_quota); |
||||
|
||||
/// Set the max receive and send message sizes.
|
||||
void SetMaxReceiveMessageSize(int size); |
||||
void SetMaxSendMessageSize(int size); |
||||
|
||||
/// Set LB policy name.
|
||||
/// Note that if the name resolver returns only balancer addresses, the
|
||||
/// grpclb LB policy will be used, regardless of what is specified here.
|
||||
void SetLoadBalancingPolicyName(const grpc::string& lb_policy_name); |
||||
|
||||
/// Set service config in JSON form.
|
||||
/// Primarily meant for use in unit tests.
|
||||
void SetServiceConfigJSON(const grpc::string& service_config_json); |
||||
|
||||
// Generic channel argument setters. Only for advanced use cases.
|
||||
/// Set an integer argument \a value under \a key.
|
||||
void SetInt(const grpc::string& key, int value); |
||||
|
||||
// Generic channel argument setter. Only for advanced use cases.
|
||||
/// Set a pointer argument \a value under \a key. Owership is not transferred.
|
||||
void SetPointer(const grpc::string& key, void* value); |
||||
|
||||
void SetPointerWithVtable(const grpc::string& key, void* value, |
||||
const grpc_arg_pointer_vtable* vtable); |
||||
|
||||
/// Set a textual argument \a value under \a key.
|
||||
void SetString(const grpc::string& key, const grpc::string& value); |
||||
|
||||
/// Return (by value) a C \a grpc_channel_args structure which points to
|
||||
/// arguments owned by this \a ChannelArguments instance
|
||||
grpc_channel_args c_channel_args() const { |
||||
grpc_channel_args out; |
||||
out.num_args = args_.size(); |
||||
out.args = args_.empty() ? NULL : const_cast<grpc_arg*>(&args_[0]); |
||||
return out; |
||||
} |
||||
|
||||
private: |
||||
friend class grpc_impl::SecureChannelCredentials; |
||||
friend class grpc::testing::ChannelArgumentsTest; |
||||
|
||||
/// Default pointer argument operations.
|
||||
struct PointerVtableMembers { |
||||
static void* Copy(void* in) { return in; } |
||||
static void Destroy(void* in) {} |
||||
static int Compare(void* a, void* b) { |
||||
if (a < b) return -1; |
||||
if (a > b) return 1; |
||||
return 0; |
||||
} |
||||
}; |
||||
|
||||
// Returns empty string when it is not set.
|
||||
grpc::string GetSslTargetNameOverride() const; |
||||
|
||||
std::vector<grpc_arg> args_; |
||||
std::list<grpc::string> strings_; |
||||
}; |
||||
|
||||
} // namespace grpc_impl
|
||||
|
||||
#endif // GRPCPP_SUPPORT_CHANNEL_ARGUMENTS_IMPL_H
|
@ -0,0 +1,179 @@ |
||||
/*
|
||||
* |
||||
* 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. |
||||
* |
||||
*/ |
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include "src/core/lib/iomgr/port.h" |
||||
#if GRPC_ARES == 1 && defined(GRPC_UV) |
||||
|
||||
#include <ares.h> |
||||
#include <uv.h> |
||||
|
||||
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h" |
||||
|
||||
#include <grpc/support/alloc.h> |
||||
#include <grpc/support/log.h> |
||||
#include <grpc/support/string_util.h> |
||||
#include <grpc/support/time.h> |
||||
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" |
||||
#include "src/core/lib/gpr/string.h" |
||||
#include "src/core/lib/iomgr/combiner.h" |
||||
|
||||
namespace grpc_core { |
||||
|
||||
void ares_uv_poll_cb(uv_poll_t* handle, int status, int events); |
||||
|
||||
void ares_uv_poll_close_cb(uv_handle_t* handle) { Delete(handle); } |
||||
|
||||
class GrpcPolledFdLibuv : public GrpcPolledFd { |
||||
public: |
||||
GrpcPolledFdLibuv(ares_socket_t as, grpc_combiner* combiner) |
||||
: as_(as), combiner_(combiner) { |
||||
gpr_asprintf(&name_, "c-ares socket: %" PRIdPTR, (intptr_t)as); |
||||
handle_ = New<uv_poll_t>(); |
||||
uv_poll_init_socket(uv_default_loop(), handle_, as); |
||||
handle_->data = this; |
||||
GRPC_COMBINER_REF(combiner_, "libuv ares event driver"); |
||||
} |
||||
|
||||
~GrpcPolledFdLibuv() { |
||||
gpr_free(name_); |
||||
GRPC_COMBINER_UNREF(combiner_, "libuv ares event driver"); |
||||
} |
||||
|
||||
void RegisterForOnReadableLocked(grpc_closure* read_closure) override { |
||||
GPR_ASSERT(read_closure_ == nullptr); |
||||
GPR_ASSERT((poll_events_ & UV_READABLE) == 0); |
||||
read_closure_ = read_closure; |
||||
poll_events_ |= UV_READABLE; |
||||
uv_poll_start(handle_, poll_events_, ares_uv_poll_cb); |
||||
} |
||||
|
||||
void RegisterForOnWriteableLocked(grpc_closure* write_closure) override { |
||||
GPR_ASSERT(write_closure_ == nullptr); |
||||
GPR_ASSERT((poll_events_ & UV_WRITABLE) == 0); |
||||
write_closure_ = write_closure; |
||||
poll_events_ |= UV_WRITABLE; |
||||
uv_poll_start(handle_, poll_events_, ares_uv_poll_cb); |
||||
} |
||||
|
||||
bool IsFdStillReadableLocked() override { |
||||
/* uv_poll_t is based on poll, which is level triggered. So, if cares
|
||||
* leaves some data unread, the event will trigger again. */ |
||||
return false; |
||||
} |
||||
|
||||
void ShutdownInternalLocked(grpc_error* error) { |
||||
uv_poll_stop(handle_); |
||||
uv_close(reinterpret_cast<uv_handle_t*>(handle_), ares_uv_poll_close_cb); |
||||
if (read_closure_ != nullptr) { |
||||
GRPC_CLOSURE_SCHED(read_closure_, GRPC_ERROR_CANCELLED); |
||||
} |
||||
if (write_closure_ != nullptr) { |
||||
GRPC_CLOSURE_SCHED(write_closure_, GRPC_ERROR_CANCELLED); |
||||
} |
||||
} |
||||
|
||||
void ShutdownLocked(grpc_error* error) override { |
||||
if (grpc_core::ExecCtx::Get() == nullptr) { |
||||
grpc_core::ExecCtx exec_ctx; |
||||
ShutdownInternalLocked(error); |
||||
} else { |
||||
ShutdownInternalLocked(error); |
||||
} |
||||
} |
||||
|
||||
ares_socket_t GetWrappedAresSocketLocked() override { return as_; } |
||||
|
||||
const char* GetName() override { return name_; } |
||||
|
||||
char* name_; |
||||
ares_socket_t as_; |
||||
uv_poll_t* handle_; |
||||
grpc_closure* read_closure_ = nullptr; |
||||
grpc_closure* write_closure_ = nullptr; |
||||
int poll_events_ = 0; |
||||
grpc_combiner* combiner_; |
||||
}; |
||||
|
||||
struct AresUvPollCbArg { |
||||
AresUvPollCbArg(uv_poll_t* handle, int status, int events) |
||||
: handle(handle), status(status), events(events) {} |
||||
|
||||
uv_poll_t* handle; |
||||
int status; |
||||
int events; |
||||
}; |
||||
|
||||
static void ares_uv_poll_cb_locked(void* arg, grpc_error* error) { |
||||
grpc_core::UniquePtr<AresUvPollCbArg> arg_struct( |
||||
reinterpret_cast<AresUvPollCbArg*>(arg)); |
||||
uv_poll_t* handle = arg_struct->handle; |
||||
int status = arg_struct->status; |
||||
int events = arg_struct->events; |
||||
GrpcPolledFdLibuv* polled_fd = |
||||
reinterpret_cast<GrpcPolledFdLibuv*>(handle->data); |
||||
if (status < 0) { |
||||
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("cares polling error"); |
||||
error = |
||||
grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR, |
||||
grpc_slice_from_static_string(uv_strerror(status))); |
||||
} |
||||
if (events & UV_READABLE) { |
||||
GPR_ASSERT(polled_fd->read_closure_ != nullptr); |
||||
GRPC_CLOSURE_SCHED(polled_fd->read_closure_, error); |
||||
polled_fd->read_closure_ = nullptr; |
||||
polled_fd->poll_events_ &= ~UV_READABLE; |
||||
} |
||||
if (events & UV_WRITABLE) { |
||||
GPR_ASSERT(polled_fd->write_closure_ != nullptr); |
||||
GRPC_CLOSURE_SCHED(polled_fd->write_closure_, error); |
||||
polled_fd->write_closure_ = nullptr; |
||||
polled_fd->poll_events_ &= ~UV_WRITABLE; |
||||
} |
||||
uv_poll_start(handle, polled_fd->poll_events_, ares_uv_poll_cb); |
||||
} |
||||
|
||||
void ares_uv_poll_cb(uv_poll_t* handle, int status, int events) { |
||||
grpc_core::ExecCtx exec_ctx; |
||||
GrpcPolledFdLibuv* polled_fd = |
||||
reinterpret_cast<GrpcPolledFdLibuv*>(handle->data); |
||||
AresUvPollCbArg* arg = New<AresUvPollCbArg>(handle, status, events); |
||||
GRPC_CLOSURE_SCHED( |
||||
GRPC_CLOSURE_CREATE(ares_uv_poll_cb_locked, arg, |
||||
grpc_combiner_scheduler(polled_fd->combiner_)), |
||||
GRPC_ERROR_NONE); |
||||
} |
||||
|
||||
class GrpcPolledFdFactoryLibuv : public GrpcPolledFdFactory { |
||||
public: |
||||
GrpcPolledFd* NewGrpcPolledFdLocked(ares_socket_t as, |
||||
grpc_pollset_set* driver_pollset_set, |
||||
grpc_combiner* combiner) override { |
||||
return New<GrpcPolledFdLibuv>(as, combiner); |
||||
} |
||||
|
||||
void ConfigureAresChannelLocked(ares_channel channel) override {} |
||||
}; |
||||
|
||||
UniquePtr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(grpc_combiner* combiner) { |
||||
return UniquePtr<GrpcPolledFdFactory>(New<GrpcPolledFdFactoryLibuv>()); |
||||
} |
||||
|
||||
} // namespace grpc_core
|
||||
|
||||
#endif /* GRPC_ARES == 1 && defined(GRPC_UV) */ |
@ -0,0 +1,52 @@ |
||||
/*
|
||||
* |
||||
* 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. |
||||
* |
||||
*/ |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include "src/core/lib/iomgr/port.h" |
||||
#if GRPC_ARES == 1 && defined(GRPC_UV) |
||||
|
||||
#include <grpc/support/string_util.h> |
||||
|
||||
#include "src/core/ext/filters/client_channel/parse_address.h" |
||||
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" |
||||
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h" |
||||
#include "src/core/ext/filters/client_channel/server_address.h" |
||||
#include "src/core/lib/gpr/host_port.h" |
||||
#include "src/core/lib/gpr/string.h" |
||||
|
||||
bool grpc_ares_query_ipv6() { |
||||
/* The libuv grpc code currently does not have the code to probe for this,
|
||||
* so we assume for now that IPv6 is always available in contexts where this |
||||
* code will be used. */ |
||||
return true; |
||||
} |
||||
|
||||
bool grpc_ares_maybe_resolve_localhost_manually_locked( |
||||
const char* name, const char* default_port, |
||||
grpc_core::UniquePtr<grpc_core::ServerAddressList>* addrs) { |
||||
char* host = nullptr; |
||||
char* port = nullptr; |
||||
bool out = inner_maybe_resolve_localhost_manually_locked(name, default_port, |
||||
addrs, &host, &port); |
||||
gpr_free(host); |
||||
gpr_free(port); |
||||
return out; |
||||
} |
||||
|
||||
#endif /* GRPC_ARES == 1 && defined(GRPC_UV) */ |
@ -0,0 +1,83 @@ |
||||
/*
|
||||
* |
||||
* 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. |
||||
* |
||||
*/ |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include "src/core/lib/iomgr/port.h" |
||||
#if GRPC_ARES == 1 && (defined(GRPC_UV) || defined(GPR_WINDOWS)) |
||||
|
||||
#include <grpc/support/string_util.h> |
||||
|
||||
#include "src/core/ext/filters/client_channel/parse_address.h" |
||||
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" |
||||
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h" |
||||
#include "src/core/ext/filters/client_channel/server_address.h" |
||||
#include "src/core/lib/gpr/host_port.h" |
||||
#include "src/core/lib/gpr/string.h" |
||||
|
||||
bool inner_maybe_resolve_localhost_manually_locked( |
||||
const char* name, const char* default_port, |
||||
grpc_core::UniquePtr<grpc_core::ServerAddressList>* addrs, char** host, |
||||
char** port) { |
||||
gpr_split_host_port(name, host, port); |
||||
if (*host == nullptr) { |
||||
gpr_log(GPR_ERROR, |
||||
"Failed to parse %s into host:port during manual localhost " |
||||
"resolution check.", |
||||
name); |
||||
return false; |
||||
} |
||||
if (*port == nullptr) { |
||||
if (default_port == nullptr) { |
||||
gpr_log(GPR_ERROR, |
||||
"No port or default port for %s during manual localhost " |
||||
"resolution check.", |
||||
name); |
||||
return false; |
||||
} |
||||
*port = gpr_strdup(default_port); |
||||
} |
||||
if (gpr_stricmp(*host, "localhost") == 0) { |
||||
GPR_ASSERT(*addrs == nullptr); |
||||
*addrs = grpc_core::MakeUnique<grpc_core::ServerAddressList>(); |
||||
uint16_t numeric_port = grpc_strhtons(*port); |
||||
// Append the ipv6 loopback address.
|
||||
struct sockaddr_in6 ipv6_loopback_addr; |
||||
memset(&ipv6_loopback_addr, 0, sizeof(ipv6_loopback_addr)); |
||||
((char*)&ipv6_loopback_addr.sin6_addr)[15] = 1; |
||||
ipv6_loopback_addr.sin6_family = AF_INET6; |
||||
ipv6_loopback_addr.sin6_port = numeric_port; |
||||
(*addrs)->emplace_back(&ipv6_loopback_addr, sizeof(ipv6_loopback_addr), |
||||
nullptr /* args */); |
||||
// Append the ipv4 loopback address.
|
||||
struct sockaddr_in ipv4_loopback_addr; |
||||
memset(&ipv4_loopback_addr, 0, sizeof(ipv4_loopback_addr)); |
||||
((char*)&ipv4_loopback_addr.sin_addr)[0] = 0x7f; |
||||
((char*)&ipv4_loopback_addr.sin_addr)[3] = 0x01; |
||||
ipv4_loopback_addr.sin_family = AF_INET; |
||||
ipv4_loopback_addr.sin_port = numeric_port; |
||||
(*addrs)->emplace_back(&ipv4_loopback_addr, sizeof(ipv4_loopback_addr), |
||||
nullptr /* args */); |
||||
// Let the address sorter figure out which one should be tried first.
|
||||
grpc_cares_wrapper_address_sorting_sort(addrs->get()); |
||||
return true; |
||||
} |
||||
return false; |
||||
} |
||||
|
||||
#endif /* GRPC_ARES == 1 && (defined(GRPC_UV) || defined(GPR_WINDOWS)) */ |
@ -0,0 +1,34 @@ |
||||
/*
|
||||
* |
||||
* 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 GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_LIBUV_WINDOWS_H |
||||
#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_LIBUV_WINDOWS_H |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include <grpc/support/string_util.h> |
||||
|
||||
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" |
||||
|
||||
bool inner_maybe_resolve_localhost_manually_locked( |
||||
const char* name, const char* default_port, |
||||
grpc_core::UniquePtr<grpc_core::ServerAddressList>* addrs, char** host, |
||||
char** port); |
||||
|
||||
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_LIBUV_WINDOWS_H \ |
||||
*/ |
@ -0,0 +1,87 @@ |
||||
/*
|
||||
* |
||||
* 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 GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H |
||||
#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include <stdint.h> |
||||
|
||||
// --------------------------------------------------------------------
|
||||
// How to use global configuration variables:
|
||||
//
|
||||
// Defining config variables of a specified type:
|
||||
// GPR_GLOBAL_CONFIG_DEFINE_*TYPE*(name, default_value, help);
|
||||
//
|
||||
// Supported TYPEs: BOOL, INT32, STRING
|
||||
//
|
||||
// It's recommended to use lowercase letters for 'name' like
|
||||
// regular variables. The builtin configuration system uses
|
||||
// environment variable and the name is converted to uppercase
|
||||
// when looking up the value. For example,
|
||||
// GPR_GLOBAL_CONFIG_DEFINE(grpc_latency) looks up the value with the
|
||||
// name, "GRPC_LATENCY".
|
||||
//
|
||||
// The variable initially has the specified 'default_value'
|
||||
// which must be an expression convertible to 'Type'.
|
||||
// 'default_value' may be evaluated 0 or more times,
|
||||
// and at an unspecified time; keep it
|
||||
// simple and usually free of side-effects.
|
||||
//
|
||||
// GPR_GLOBAL_CONFIG_DEFINE_*TYPE* should not be called in a C++ header.
|
||||
// It should be called at the top-level (outside any namespaces)
|
||||
// in a .cc file.
|
||||
//
|
||||
// Getting the variables:
|
||||
// GPR_GLOBAL_CONFIG_GET(name)
|
||||
//
|
||||
// If error happens during getting variables, error messages will
|
||||
// be logged and default value will be returned.
|
||||
//
|
||||
// Setting the variables with new value:
|
||||
// GPR_GLOBAL_CONFIG_SET(name, new_value)
|
||||
//
|
||||
// Declaring config variables for other modules to access:
|
||||
// GPR_GLOBAL_CONFIG_DECLARE_*TYPE*(name)
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// How to customize the global configuration system:
|
||||
//
|
||||
// How to read and write configuration value can be customized.
|
||||
// Builtin system uses environment variables but it can be extended to
|
||||
// support command-line flag, file, etc.
|
||||
//
|
||||
// To customize it, following macros should be redefined.
|
||||
//
|
||||
// GPR_GLOBAL_CONFIG_DEFINE_BOOL
|
||||
// GPR_GLOBAL_CONFIG_DEFINE_INT32
|
||||
// GPR_GLOBAL_CONFIG_DEFINE_STRING
|
||||
//
|
||||
// These macros should define functions for getting and setting variable.
|
||||
// For example, GPR_GLOBAL_CONFIG_DEFINE_BOOL(test, ...) would define two
|
||||
// functions.
|
||||
//
|
||||
// bool gpr_global_config_get_test();
|
||||
// void gpr_global_config_set_test(bool value);
|
||||
|
||||
#include "src/core/lib/gprpp/global_config_env.h" |
||||
|
||||
#include "src/core/lib/gprpp/global_config_custom.h" |
||||
|
||||
#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H */ |
@ -0,0 +1,29 @@ |
||||
/*
|
||||
* |
||||
* 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 GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H |
||||
#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H |
||||
|
||||
// This is a placeholder for custom global configuration implementaion.
|
||||
// To use the custom one, please define following macros here.
|
||||
//
|
||||
// GPR_GLOBAL_CONFIG_DEFINE_BOOL
|
||||
// GPR_GLOBAL_CONFIG_DEFINE_INT32
|
||||
// GPR_GLOBAL_CONFIG_DEFINE_STRING
|
||||
|
||||
#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H */ |
@ -0,0 +1,135 @@ |
||||
/*
|
||||
* |
||||
* 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. |
||||
* |
||||
*/ |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include "src/core/lib/gprpp/global_config_env.h" |
||||
|
||||
#include <grpc/support/alloc.h> |
||||
#include <grpc/support/log.h> |
||||
#include <grpc/support/string_util.h> |
||||
|
||||
#include "src/core/lib/gpr/env.h" |
||||
#include "src/core/lib/gpr/string.h" |
||||
|
||||
#include <ctype.h> |
||||
#include <string.h> |
||||
|
||||
namespace grpc_core { |
||||
|
||||
namespace { |
||||
|
||||
void DefaultGlobalConfigEnvErrorFunction(const char* error_message) { |
||||
gpr_log(GPR_ERROR, "%s", error_message); |
||||
} |
||||
|
||||
GlobalConfigEnvErrorFunctionType g_global_config_env_error_func = |
||||
DefaultGlobalConfigEnvErrorFunction; |
||||
|
||||
void LogParsingError(const char* name, const char* value) { |
||||
char* error_message; |
||||
gpr_asprintf(&error_message, |
||||
"Illegal value '%s' specified for environment variable '%s'", |
||||
value, name); |
||||
(*g_global_config_env_error_func)(error_message); |
||||
gpr_free(error_message); |
||||
} |
||||
|
||||
} // namespace
|
||||
|
||||
void SetGlobalConfigEnvErrorFunction(GlobalConfigEnvErrorFunctionType func) { |
||||
g_global_config_env_error_func = func; |
||||
} |
||||
|
||||
UniquePtr<char> GlobalConfigEnv::GetValue() { |
||||
return UniquePtr<char>(gpr_getenv(GetName())); |
||||
} |
||||
|
||||
void GlobalConfigEnv::SetValue(const char* value) { |
||||
gpr_setenv(GetName(), value); |
||||
} |
||||
|
||||
void GlobalConfigEnv::Unset() { gpr_unsetenv(GetName()); } |
||||
|
||||
char* GlobalConfigEnv::GetName() { |
||||
// This makes sure that name_ is in a canonical form having uppercase
|
||||
// letters. This is okay to be called serveral times.
|
||||
for (char* c = name_; *c != 0; ++c) { |
||||
*c = toupper(*c); |
||||
} |
||||
return name_; |
||||
} |
||||
static_assert(std::is_trivially_destructible<GlobalConfigEnvBool>::value, |
||||
"GlobalConfigEnvBool needs to be trivially destructible."); |
||||
|
||||
bool GlobalConfigEnvBool::Get() { |
||||
UniquePtr<char> str = GetValue(); |
||||
if (str == nullptr) { |
||||
return default_value_; |
||||
} |
||||
// parsing given value string.
|
||||
bool result = false; |
||||
if (!gpr_parse_bool_value(str.get(), &result)) { |
||||
LogParsingError(GetName(), str.get()); |
||||
result = default_value_; |
||||
} |
||||
return result; |
||||
} |
||||
|
||||
void GlobalConfigEnvBool::Set(bool value) { |
||||
SetValue(value ? "true" : "false"); |
||||
} |
||||
|
||||
static_assert(std::is_trivially_destructible<GlobalConfigEnvInt32>::value, |
||||
"GlobalConfigEnvInt32 needs to be trivially destructible."); |
||||
|
||||
int32_t GlobalConfigEnvInt32::Get() { |
||||
UniquePtr<char> str = GetValue(); |
||||
if (str == nullptr) { |
||||
return default_value_; |
||||
} |
||||
// parsing given value string.
|
||||
char* end = str.get(); |
||||
long result = strtol(str.get(), &end, 10); |
||||
if (*end != 0) { |
||||
LogParsingError(GetName(), str.get()); |
||||
result = default_value_; |
||||
} |
||||
return static_cast<int32_t>(result); |
||||
} |
||||
|
||||
void GlobalConfigEnvInt32::Set(int32_t value) { |
||||
char buffer[GPR_LTOA_MIN_BUFSIZE]; |
||||
gpr_ltoa(value, buffer); |
||||
SetValue(buffer); |
||||
} |
||||
|
||||
static_assert(std::is_trivially_destructible<GlobalConfigEnvString>::value, |
||||
"GlobalConfigEnvString needs to be trivially destructible."); |
||||
|
||||
UniquePtr<char> GlobalConfigEnvString::Get() { |
||||
UniquePtr<char> str = GetValue(); |
||||
if (str == nullptr) { |
||||
return UniquePtr<char>(gpr_strdup(default_value_)); |
||||
} |
||||
return str; |
||||
} |
||||
|
||||
void GlobalConfigEnvString::Set(const char* value) { SetValue(value); } |
||||
|
||||
} // namespace grpc_core
|
@ -0,0 +1,131 @@ |
||||
/*
|
||||
* |
||||
* 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 GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H |
||||
#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include "src/core/lib/gprpp/global_config_generic.h" |
||||
#include "src/core/lib/gprpp/memory.h" |
||||
|
||||
namespace grpc_core { |
||||
|
||||
typedef void (*GlobalConfigEnvErrorFunctionType)(const char* error_message); |
||||
|
||||
/*
|
||||
* Set global_config_env_error_function which is called when config system |
||||
* encounters errors such as parsing error. What the default function does |
||||
* is logging error message. |
||||
*/ |
||||
void SetGlobalConfigEnvErrorFunction(GlobalConfigEnvErrorFunctionType func); |
||||
|
||||
// Base class for all classes to access environment variables.
|
||||
class GlobalConfigEnv { |
||||
protected: |
||||
// `name` should be writable and alive after constructor is called.
|
||||
constexpr explicit GlobalConfigEnv(char* name) : name_(name) {} |
||||
|
||||
public: |
||||
// Returns the value of `name` variable.
|
||||
UniquePtr<char> GetValue(); |
||||
|
||||
// Sets the value of `name` variable.
|
||||
void SetValue(const char* value); |
||||
|
||||
// Unsets `name` variable.
|
||||
void Unset(); |
||||
|
||||
protected: |
||||
char* GetName(); |
||||
|
||||
private: |
||||
char* name_; |
||||
}; |
||||
|
||||
class GlobalConfigEnvBool : public GlobalConfigEnv { |
||||
public: |
||||
constexpr GlobalConfigEnvBool(char* name, bool default_value) |
||||
: GlobalConfigEnv(name), default_value_(default_value) {} |
||||
|
||||
bool Get(); |
||||
void Set(bool value); |
||||
|
||||
private: |
||||
bool default_value_; |
||||
}; |
||||
|
||||
class GlobalConfigEnvInt32 : public GlobalConfigEnv { |
||||
public: |
||||
constexpr GlobalConfigEnvInt32(char* name, int32_t default_value) |
||||
: GlobalConfigEnv(name), default_value_(default_value) {} |
||||
|
||||
int32_t Get(); |
||||
void Set(int32_t value); |
||||
|
||||
private: |
||||
int32_t default_value_; |
||||
}; |
||||
|
||||
class GlobalConfigEnvString : public GlobalConfigEnv { |
||||
public: |
||||
constexpr GlobalConfigEnvString(char* name, const char* default_value) |
||||
: GlobalConfigEnv(name), default_value_(default_value) {} |
||||
|
||||
UniquePtr<char> Get(); |
||||
void Set(const char* value); |
||||
|
||||
private: |
||||
const char* default_value_; |
||||
}; |
||||
|
||||
} // namespace grpc_core
|
||||
|
||||
// Macros for defining global config instances using environment variables.
|
||||
// This defines a GlobalConfig*Type* instance with arguments for
|
||||
// mutable variable name and default value.
|
||||
// Mutable name (g_env_str_##name) is here for having an array
|
||||
// for the canonical name without dynamic allocation.
|
||||
// `help` argument is ignored for this implementation.
|
||||
|
||||
#define GPR_GLOBAL_CONFIG_DEFINE_BOOL(name, default_value, help) \ |
||||
static char g_env_str_##name[] = #name; \
|
||||
static ::grpc_core::GlobalConfigEnvBool g_env_##name(g_env_str_##name, \
|
||||
default_value); \
|
||||
bool gpr_global_config_get_##name() { return g_env_##name.Get(); } \
|
||||
void gpr_global_config_set_##name(bool value) { g_env_##name.Set(value); } |
||||
|
||||
#define GPR_GLOBAL_CONFIG_DEFINE_INT32(name, default_value, help) \ |
||||
static char g_env_str_##name[] = #name; \
|
||||
static ::grpc_core::GlobalConfigEnvInt32 g_env_##name(g_env_str_##name, \
|
||||
default_value); \
|
||||
int32_t gpr_global_config_get_##name() { return g_env_##name.Get(); } \
|
||||
void gpr_global_config_set_##name(int32_t value) { g_env_##name.Set(value); } |
||||
|
||||
#define GPR_GLOBAL_CONFIG_DEFINE_STRING(name, default_value, help) \ |
||||
static char g_env_str_##name[] = #name; \
|
||||
static ::grpc_core::GlobalConfigEnvString g_env_##name(g_env_str_##name, \
|
||||
default_value); \
|
||||
::grpc_core::UniquePtr<char> gpr_global_config_get_##name() { \
|
||||
return g_env_##name.Get(); \
|
||||
} \
|
||||
void gpr_global_config_set_##name(const char* value) { \
|
||||
g_env_##name.Set(value); \
|
||||
} |
||||
|
||||
#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H */ |
@ -0,0 +1,44 @@ |
||||
/*
|
||||
* |
||||
* 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 GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H |
||||
#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H |
||||
|
||||
#include <grpc/support/port_platform.h> |
||||
|
||||
#include "src/core/lib/gprpp/memory.h" |
||||
|
||||
#include <stdint.h> |
||||
|
||||
#define GPR_GLOBAL_CONFIG_GET(name) gpr_global_config_get_##name() |
||||
|
||||
#define GPR_GLOBAL_CONFIG_SET(name, value) gpr_global_config_set_##name(value) |
||||
|
||||
#define GPR_GLOBAL_CONFIG_DECLARE_BOOL(name) \ |
||||
extern bool gpr_global_config_get_##name(); \
|
||||
extern void gpr_global_config_set_##name(bool value) |
||||
|
||||
#define GPR_GLOBAL_CONFIG_DECLARE_INT32(name) \ |
||||
extern int32_t gpr_global_config_get_##name(); \
|
||||
extern void gpr_global_config_set_##name(int32_t value) |
||||
|
||||
#define GPR_GLOBAL_CONFIG_DECLARE_STRING(name) \ |
||||
extern grpc_core::UniquePtr<char> gpr_global_config_get_##name(); \
|
||||
extern void gpr_global_config_set_##name(const char* value) |
||||
|
||||
#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H */ |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue