istio_echo_server.cc
Go to the documentation of this file.
1 //
2 // Copyright 2022 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include <algorithm>
18 #include <atomic>
19 #include <chrono>
20 #include <condition_variable>
21 #include <deque>
22 #include <map>
23 #include <memory>
24 #include <mutex>
25 #include <set>
26 #include <sstream>
27 #include <string>
28 #include <thread>
29 #include <vector>
30 
31 #include "absl/algorithm/container.h"
32 #include "absl/flags/flag.h"
33 #include "absl/strings/str_format.h"
34 #include "absl/strings/str_join.h"
35 #include "absl/strings/str_split.h"
36 
39 #include <grpcpp/grpcpp.h>
40 #include <grpcpp/server.h>
41 #include <grpcpp/server_builder.h>
42 #include <grpcpp/server_context.h>
45 
47 #include "src/core/lib/gpr/env.h"
50 #include "src/proto/grpc/testing/istio_echo.pb.h"
54 
55 // A list of ports to listen on, for gRPC traffic.
56 ABSL_FLAG(std::vector<std::string>, grpc, std::vector<std::string>({"7070"}),
57  "GRPC ports");
58 ABSL_FLAG(std::vector<std::string>, tls, std::vector<std::string>({}),
59  "Ports that are using TLS. These must be defined as http/grpc/tcp.");
60 ABSL_FLAG(std::vector<std::string>, xds_grpc_server,
61  std::vector<std::string>({}),
62  "Ports that should rely on XDS configuration to serve");
63 ABSL_FLAG(std::string, crt, "", "gRPC TLS server-side certificate");
64 ABSL_FLAG(std::string, key, "", "gRPC TLS server-side key");
65 ABSL_FLAG(std::string, forwarding_address, "0.0.0.0:7072",
66  "Forwarding address for unhandled protocols");
67 
68 // The following flags must be defined, but are not used for now. Some may be
69 // necessary for certain tests.
70 ABSL_FLAG(std::vector<std::string>, port, std::vector<std::string>({"8080"}),
71  "HTTP/1.1 ports");
72 ABSL_FLAG(std::vector<std::string>, tcp, std::vector<std::string>({"9090"}),
73  "TCP ports");
74 ABSL_FLAG(std::vector<std::string>, bind_ip, std::vector<std::string>({}),
75  "Ports that are bound to INSTANCE_IP rather than wildcard IP.");
76 ABSL_FLAG(std::vector<std::string>, bind_localhost,
77  std::vector<std::string>({}),
78  "Ports that are bound to localhost rather than wildcard IP.");
79 ABSL_FLAG(std::vector<std::string>, server_first, std::vector<std::string>({}),
80  "Ports that are server first. These must be defined as tcp.");
81 ABSL_FLAG(std::string, metrics, "", "Metrics port");
82 ABSL_FLAG(std::string, uds, "", "HTTP server on unix domain socket");
83 ABSL_FLAG(std::string, cluster, "", "Cluster where this server is deployed");
84 ABSL_FLAG(std::string, istio_version, "", "Istio sidecar version");
85 ABSL_FLAG(std::string, disable_alpn, "", "disable ALPN negotiation");
86 
87 namespace grpc {
88 namespace testing {
89 namespace {
90 
91 void RunServer(const std::set<int>& grpc_ports, const std::set<int>& xds_ports,
92  const std::set<int>& tls_ports) {
93  // Get hostname
94  std::string hostname;
95  char* hostname_p = grpc_gethostname();
96  if (hostname_p == nullptr) {
97  hostname = absl::StrFormat("generated-%d", rand() % 1000);
98  } else {
99  hostname = hostname_p;
100  free(hostname_p);
101  }
102  EchoTestServiceImpl echo_test_service(
103  std::move(hostname), absl::GetFlag(FLAGS_forwarding_address));
104  ServerBuilder builder;
105  XdsServerBuilder xds_builder;
106  bool has_xds_listeners = false;
107  builder.RegisterService(&echo_test_service);
108  for (int port : grpc_ports) {
109  auto server_address = grpc_core::JoinHostPort("0.0.0.0", port);
110  if (xds_ports.find(port) != xds_ports.end()) {
111  xds_builder.AddListeningPort(
113  gpr_log(GPR_INFO, "Server listening on %s over xds",
114  server_address.c_str());
115  has_xds_listeners = true;
116  } else if (tls_ports.find(port) != tls_ports.end()) {
117  // Create Credentials for Tls Servers -
118  // 1. Uses FileWatcherCertificateProvider with a refresh interval of 600
119  // seconds. (Number decided based on gRPC defaults.
120  // 2. Do not ask for client certificates. (Not yet sure what is needed
121  // right now.) Add ports to the builders
122  experimental::TlsServerCredentialsOptions options(
123  std::make_shared<experimental::FileWatcherCertificateProvider>(
124  absl::GetFlag(FLAGS_key), absl::GetFlag(FLAGS_crt), 600));
125  options.set_cert_request_type(GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE);
126  options.watch_identity_key_cert_pairs();
127  options.set_check_call_host(false);
129  gpr_log(GPR_INFO, "Server listening on %s over tls",
130  server_address.c_str());
131  } else {
132  builder.AddListeningPort(server_address, InsecureServerCredentials());
133  gpr_log(GPR_INFO, "Server listening on %s over insecure",
134  server_address.c_str());
135  }
136  }
137  // Enable the default health check service, probably not needed though.
139  std::unique_ptr<Server> xds_server;
140  if (has_xds_listeners) {
141  xds_server = xds_builder.BuildAndStart();
142  }
143  std::unique_ptr<Server> server(builder.BuildAndStart());
144  server->Wait();
145 }
146 
147 } // namespace
148 } // namespace testing
149 } // namespace grpc
150 
151 int main(int argc, char** argv) {
152  // Preprocess argv, for two things:
153  // 1. merge duplciate flags. So "--grpc=8080 --grpc=9090" becomes
154  // "--grpc=8080,9090".
155  // 2. replace '-' to '_'. So "--istio-version=123" becomes
156  // "--istio_version=123".
157  // 3. remove --version since that is specially interpretted by absl
158  std::map<std::string, std::vector<std::string>> argv_dict;
159  for (int i = 0; i < argc; i++) {
160  std::string arg(argv[i]);
161  size_t equal = arg.find_first_of('=');
162  if (equal != std::string::npos) {
163  std::string f = arg.substr(0, equal);
164  if (f == "--version") {
165  continue;
166  }
167  std::string v = arg.substr(equal + 1, std::string::npos);
168  argv_dict[f].push_back(v);
169  }
170  }
171  std::vector<char*> new_argv_strs;
172  // Keep the command itself.
173  new_argv_strs.push_back(argv[0]);
174  for (const auto& kv : argv_dict) {
176  for (const auto& s : kv.second) {
177  if (!values.empty()) values += ",";
178  values += s;
179  }
180  // replace '-' to '_', excluding the leading "--".
181  std::string f = kv.first;
182  std::replace(f.begin() + 2, f.end(), '-', '_');
183  std::string k_vs = absl::StrCat(f, "=", values);
184  char* writable = new char[k_vs.size() + 1];
185  std::copy(k_vs.begin(), k_vs.end(), writable);
186  writable[k_vs.size()] = '\0';
187  new_argv_strs.push_back(writable);
188  }
189  int new_argc = new_argv_strs.size();
190  char** new_argv = new_argv_strs.data();
191  grpc::testing::TestEnvironment env(&new_argc, new_argv);
192  grpc::testing::InitTest(&new_argc, &new_argv, true);
193  // Turn gRPC ports from a string vector to an int vector.
194  std::set<int> grpc_ports;
195  for (const auto& p : absl::GetFlag(FLAGS_grpc)) {
196  int grpc_port = std::stoi(p);
197  grpc_ports.insert(grpc_port);
198  }
199  // Create a map of which ports are supposed to use xds
200  std::set<int> xds_ports;
201  for (const auto& p : absl::GetFlag(FLAGS_xds_grpc_server)) {
202  int port = 0;
203  if (!absl::SimpleAtoi(p, &port)) {
204  gpr_log(GPR_ERROR, "SimpleAtoi Failure: %s", p.c_str());
205  return 1;
206  }
207  xds_ports.insert(port);
208  // If the port does not exist in gRPC ports set, add it.
209  if (grpc_ports.find(port) == grpc_ports.end()) {
210  grpc_ports.insert(port);
211  }
212  }
213  // Create a map of which ports are supposed to use tls
214  std::set<int> tls_ports;
215  for (const auto& p : absl::GetFlag(FLAGS_tls)) {
216  int port = 0;
217  if (!absl::SimpleAtoi(p, &port)) {
218  gpr_log(GPR_ERROR, "SimpleAtoi Failure: %s", p.c_str());
219  return 1;
220  }
221  tls_ports.insert(port);
222  }
223  // Start the servers
224  grpc::testing::RunServer(grpc_ports, xds_ports, tls_ports);
225  return 0;
226 }
grpc::testing::InitTest
void InitTest(int *argc, char ***argv, bool remove_flags)
Definition: test_config_cc.cc:28
xds_server_builder.h
GPR_INFO
#define GPR_INFO
Definition: include/grpc/impl/codegen/log.h:56
testing
Definition: aws_request_signer_test.cc:25
generate.env
env
Definition: generate.py:37
absl::StrCat
std::string StrCat(const AlphaNum &a, const AlphaNum &b)
Definition: abseil-cpp/absl/strings/str_cat.cc:98
absl::StrFormat
ABSL_MUST_USE_RESULT std::string StrFormat(const FormatSpec< Args... > &format, const Args &... args)
Definition: abseil-cpp/absl/strings/str_format.h:338
grpc
Definition: grpcpp/alarm.h:33
grpc::EnableDefaultHealthCheckService
void EnableDefaultHealthCheckService(bool enable)
Definition: health_check_service.cc:30
proto_server_reflection_plugin.h
status_util.h
copy
static int copy(grpc_slice_buffer *input, grpc_slice_buffer *output)
Definition: message_compress.cc:145
options
double_dict options[]
Definition: capstone_test.c:55
equal
static uint8_t equal(signed char b, signed char c)
Definition: curve25519.c:708
testing::internal::string
::std::string string
Definition: bloaty/third_party/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:881
tcp
static uv_tcp_t tcp
Definition: test-connection-fail.c:29
env.h
grpc::XdsServerCredentials
std::shared_ptr< ServerCredentials > XdsServerCredentials(const std::shared_ptr< ServerCredentials > &fallback_credentials)
Builds Xds ServerCredentials given fallback credentials.
Definition: xds_server_credentials.cc:30
xds_manager.p
p
Definition: xds_manager.py:60
grpc::testing::RunServer
void RunServer()
Definition: client_crash_test_server.cc:56
main
int main(int argc, char **argv)
Definition: istio_echo_server.cc:151
server_address
std::string server_address("0.0.0.0:10000")
gethostname.h
absl::SimpleAtoi
ABSL_NAMESPACE_BEGIN ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str, int_type *out)
Definition: abseil-cpp/absl/strings/numbers.h:271
profile_analyzer.builder
builder
Definition: profile_analyzer.py:159
autogen_x86imm.f
f
Definition: autogen_x86imm.py:9
absl::move
constexpr absl::remove_reference_t< T > && move(T &&t) noexcept
Definition: abseil-cpp/absl/utility/utility.h:221
grpc_gethostname
char * grpc_gethostname()
cluster
absl::string_view cluster
Definition: xds_resolver.cc:331
gpr_log
GPRAPI void gpr_log(const char *file, int line, gpr_log_severity severity, const char *format,...) GPR_PRINT_FORMAT_CHECK(4
setup.v
v
Definition: third_party/bloaty/third_party/capstone/bindings/python/setup.py:42
grpc::experimental::TlsServerCredentials
std::shared_ptr< ServerCredentials > TlsServerCredentials(const experimental::TlsServerCredentialsOptions &options)
Builds TLS ServerCredentials given TLS options.
Definition: secure_server_credentials.cc:153
grpc_core::JoinHostPort
std::string JoinHostPort(absl::string_view host, int port)
Definition: host_port.cc:32
grpcpp.h
arg
Definition: cmdline.cc:40
grpc.server
def server(thread_pool, handlers=None, interceptors=None, options=None, maximum_concurrent_rpcs=None, compression=None, xds=False)
Definition: src/python/grpcio/grpc/__init__.py:2034
absl::GetFlag
ABSL_MUST_USE_RESULT T GetFlag(const absl::Flag< T > &flag)
Definition: abseil-cpp/absl/flags/flag.h:98
host_port.h
admin_services.h
GPR_ERROR
#define GPR_ERROR
Definition: include/grpc/impl/codegen/log.h:57
tests.unit._exit_scenarios.port
port
Definition: _exit_scenarios.py:179
test_config.h
istio_echo_server_lib.h
key
const char * key
Definition: hpack_parser_table.cc:164
server
Definition: examples/python/async_streaming/server.py:1
GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE
@ GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE
Definition: grpc_security_constants.h:84
server_context.h
grpc::testing::TestEnvironment
Definition: test/core/util/test_config.h:54
values
std::array< int64_t, Size > values
Definition: abseil-cpp/absl/container/btree_benchmark.cc:608
arg
struct arg arg
test_config.h
ABSL_FLAG
ABSL_FLAG(std::vector< std::string >, grpc, std::vector< std::string >({"7070"}), "GRPC ports")
grpc::InsecureServerCredentials
std::shared_ptr< ServerCredentials > InsecureServerCredentials()
Definition: insecure_server_credentials.cc:52
server.h
server_builder.h
string_ref.h
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230


grpc
Author(s):
autogenerated on Thu Mar 13 2025 03:00:22