xref: /aosp_15_r20/external/grpc-grpc/test/cpp/util/channelz_sampler_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2016 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 #include <stdlib.h>
19 #include <unistd.h>
20 
21 #include <cstdlib>
22 #include <iostream>
23 #include <memory>
24 #include <string>
25 #include <thread>
26 
27 #include "absl/strings/str_cat.h"
28 #include "gtest/gtest.h"
29 
30 #include <grpc/grpc.h>
31 #include <grpc/support/alloc.h>
32 #include <grpc/support/port_platform.h>
33 #include <grpcpp/channel.h>
34 #include <grpcpp/client_context.h>
35 #include <grpcpp/create_channel.h>
36 #include <grpcpp/ext/channelz_service_plugin.h>
37 #include <grpcpp/grpcpp.h>
38 #include <grpcpp/security/credentials.h>
39 #include <grpcpp/security/server_credentials.h>
40 #include <grpcpp/server.h>
41 #include <grpcpp/server_builder.h>
42 #include <grpcpp/server_context.h>
43 
44 #include "src/core/lib/gprpp/env.h"
45 #include "src/cpp/server/channelz/channelz_service.h"
46 #include "src/proto/grpc/testing/test.grpc.pb.h"
47 #include "test/core/util/port.h"
48 #include "test/core/util/test_config.h"
49 #include "test/cpp/util/subprocess.h"
50 #include "test/cpp/util/test_credentials_provider.h"
51 
52 static std::string g_root;
53 
54 namespace {
55 using grpc::ClientContext;
56 using grpc::Server;
57 using grpc::ServerBuilder;
58 using grpc::ServerContext;
59 using grpc::Status;
60 }  // namespace
61 
62 // Test variables
63 std::string server_address("0.0.0.0:10000");
64 std::string custom_credentials_type("INSECURE_CREDENTIALS");
65 std::string sampling_times = "2";
66 std::string sampling_interval_seconds = "3";
67 std::string output_json("output.json");
68 
69 // Creata an echo server
70 class EchoServerImpl final : public grpc::testing::TestService::Service {
EmptyCall(ServerContext *,const grpc::testing::Empty *,grpc::testing::Empty *)71   Status EmptyCall(ServerContext* /*context*/,
72                    const grpc::testing::Empty* /*request*/,
73                    grpc::testing::Empty* /*response*/) override {
74     return Status::OK;
75   }
76 };
77 
78 // Run client in a thread
RunClient(const std::string & client_id,gpr_event * done_ev)79 void RunClient(const std::string& client_id, gpr_event* done_ev) {
80   grpc::ChannelArguments channel_args;
81   std::shared_ptr<grpc::ChannelCredentials> channel_creds =
82       grpc::testing::GetCredentialsProvider()->GetChannelCredentials(
83           custom_credentials_type, &channel_args);
84   std::unique_ptr<grpc::testing::TestService::Stub> stub =
85       grpc::testing::TestService::NewStub(
86           grpc::CreateChannel(server_address, channel_creds));
87   gpr_log(GPR_INFO, "Client %s is echoing!", client_id.c_str());
88   while (true) {
89     if (gpr_event_wait(done_ev, grpc_timeout_seconds_to_deadline(1)) !=
90         nullptr) {
91       return;
92     }
93     grpc::testing::Empty request;
94     grpc::testing::Empty response;
95     ClientContext context;
96     Status status = stub->EmptyCall(&context, request, &response);
97     if (!status.ok()) {
98       gpr_log(GPR_ERROR, "Client echo failed.");
99       GPR_ASSERT(0);
100     }
101   }
102 }
103 
104 // Create the channelz to test the connection to the server
WaitForConnection(int wait_server_seconds)105 bool WaitForConnection(int wait_server_seconds) {
106   grpc::ChannelArguments channel_args;
107   std::shared_ptr<grpc::ChannelCredentials> channel_creds =
108       grpc::testing::GetCredentialsProvider()->GetChannelCredentials(
109           custom_credentials_type, &channel_args);
110   auto channel = grpc::CreateChannel(server_address, channel_creds);
111   return channel->WaitForConnected(
112       grpc_timeout_seconds_to_deadline(wait_server_seconds));
113 }
114 
115 // Test the channelz sampler
TEST(ChannelzSamplerTest,SimpleTest)116 TEST(ChannelzSamplerTest, SimpleTest) {
117   // start server
118   grpc::channelz::experimental::InitChannelzService();
119   EchoServerImpl service;
120   ServerBuilder builder;
121   auto server_creds =
122       grpc::testing::GetCredentialsProvider()->GetServerCredentials(
123           custom_credentials_type);
124   builder.AddListeningPort(server_address, server_creds);
125   builder.RegisterService(&service);
126   std::unique_ptr<Server> server(builder.BuildAndStart());
127   gpr_log(GPR_INFO, "Server listening on %s", server_address.c_str());
128   const int kWaitForServerSeconds = 10;
129   ASSERT_TRUE(WaitForConnection(kWaitForServerSeconds));
130   // client threads
131   gpr_event done_ev1, done_ev2;
132   gpr_event_init(&done_ev1);
133   gpr_event_init(&done_ev2);
134   std::thread client_thread_1(RunClient, "1", &done_ev1);
135   std::thread client_thread_2(RunClient, "2", &done_ev2);
136   // Run the channelz sampler
137   grpc::SubProcess* test_driver = new grpc::SubProcess(
138       {g_root + "/channelz_sampler", "--server_address=" + server_address,
139        "--custom_credentials_type=" + custom_credentials_type,
140        "--sampling_times=" + sampling_times,
141        "--sampling_interval_seconds=" + sampling_interval_seconds,
142        "--output_json=" + output_json});
143   int status = test_driver->Join();
144   if (WIFEXITED(status)) {
145     if (WEXITSTATUS(status)) {
146       gpr_log(GPR_ERROR,
147               "Channelz sampler test test-runner exited with code %d",
148               WEXITSTATUS(status));
149       GPR_ASSERT(0);  // log the line number of the assertion failure
150     }
151   } else if (WIFSIGNALED(status)) {
152     gpr_log(GPR_ERROR, "Channelz sampler test test-runner ended from signal %d",
153             WTERMSIG(status));
154     GPR_ASSERT(0);
155   } else {
156     gpr_log(GPR_ERROR,
157             "Channelz sampler test test-runner ended with unknown status %d",
158             status);
159     GPR_ASSERT(0);
160   }
161   delete test_driver;
162   gpr_event_set(&done_ev1, reinterpret_cast<void*>(1));
163   gpr_event_set(&done_ev2, reinterpret_cast<void*>(1));
164   client_thread_1.join();
165   client_thread_2.join();
166 }
167 
main(int argc,char ** argv)168 int main(int argc, char** argv) {
169   grpc::testing::TestEnvironment env(&argc, argv);
170   ::testing::InitGoogleTest(&argc, argv);
171   std::string me = argv[0];
172   auto lslash = me.rfind('/');
173   if (lslash != std::string::npos) {
174     g_root = me.substr(0, lslash);
175   } else {
176     g_root = ".";
177   }
178 
179   /// ensures the target address is unique even if this test is run in parallel
180   server_address = absl::StrCat("0.0.0.0:", grpc_pick_unused_port_or_die());
181   int ret = RUN_ALL_TESTS();
182   return ret;
183 }
184