xref: /aosp_15_r20/external/grpc-grpc/test/cpp/util/channelz_sampler.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2015 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 <unistd.h>
19 
20 #include <cstdlib>
21 #include <fstream>
22 #include <iomanip>
23 #include <iostream>
24 #include <memory>
25 #include <ostream>
26 #include <queue>
27 #include <string>
28 
29 #include "absl/flags/flag.h"
30 #include "absl/strings/str_format.h"
31 #include "absl/strings/str_join.h"
32 #include "google/protobuf/text_format.h"
33 
34 #include <grpc/grpc.h>
35 #include <grpc/support/port_platform.h>
36 #include <grpcpp/channel.h>
37 #include <grpcpp/client_context.h>
38 #include <grpcpp/create_channel.h>
39 #include <grpcpp/ext/channelz_service_plugin.h>
40 #include <grpcpp/grpcpp.h>
41 #include <grpcpp/security/credentials.h>
42 #include <grpcpp/security/server_credentials.h>
43 #include <grpcpp/server.h>
44 #include <grpcpp/server_builder.h>
45 #include <grpcpp/server_context.h>
46 
47 #include "src/core/lib/json/json.h"
48 #include "src/core/lib/json/json_writer.h"
49 #include "src/cpp/server/channelz/channelz_service.h"
50 #include "src/proto/grpc/channelz/channelz.pb.h"
51 #include "test/core/util/test_config.h"
52 #include "test/cpp/util/test_config.h"
53 #include "test/cpp/util/test_credentials_provider.h"
54 
55 ABSL_FLAG(std::string, server_address, "", "channelz server address");
56 ABSL_FLAG(std::string, custom_credentials_type, "", "custom credentials type");
57 ABSL_FLAG(int64_t, sampling_times, 1, "number of sampling");
58 // TODO(Capstan): Consider using absl::Duration
59 ABSL_FLAG(int64_t, sampling_interval_seconds, 0,
60           "sampling interval in seconds");
61 ABSL_FLAG(std::string, output_json, "", "output filename in json format");
62 
63 namespace {
64 using grpc::ClientContext;
65 using grpc::Status;
66 using grpc::StatusCode;
67 using grpc::channelz::v1::GetChannelRequest;
68 using grpc::channelz::v1::GetChannelResponse;
69 using grpc::channelz::v1::GetServersRequest;
70 using grpc::channelz::v1::GetServersResponse;
71 using grpc::channelz::v1::GetSocketRequest;
72 using grpc::channelz::v1::GetSocketResponse;
73 using grpc::channelz::v1::GetSubchannelRequest;
74 using grpc::channelz::v1::GetSubchannelResponse;
75 using grpc::channelz::v1::GetTopChannelsRequest;
76 using grpc::channelz::v1::GetTopChannelsResponse;
77 }  // namespace
78 
79 class ChannelzSampler final {
80  public:
81   // Get server_id of a server
GetServerID(const grpc::channelz::v1::Server & server)82   int64_t GetServerID(const grpc::channelz::v1::Server& server) {
83     return server.ref().server_id();
84   }
85 
86   // Get channel_id of a channel
GetChannelID(const grpc::channelz::v1::Channel & channel)87   inline int64_t GetChannelID(const grpc::channelz::v1::Channel& channel) {
88     return channel.ref().channel_id();
89   }
90 
91   // Get subchannel_id of a subchannel
GetSubchannelID(const grpc::channelz::v1::Subchannel & subchannel)92   inline int64_t GetSubchannelID(
93       const grpc::channelz::v1::Subchannel& subchannel) {
94     return subchannel.ref().subchannel_id();
95   }
96 
97   // Get socket_id of a socket
GetSocketID(const grpc::channelz::v1::Socket & socket)98   inline int64_t GetSocketID(const grpc::channelz::v1::Socket& socket) {
99     return socket.ref().socket_id();
100   }
101 
102   // Get name of a server
GetServerName(const grpc::channelz::v1::Server & server)103   inline std::string GetServerName(const grpc::channelz::v1::Server& server) {
104     return server.ref().name();
105   }
106 
107   // Get name of a channel
GetChannelName(const grpc::channelz::v1::Channel & channel)108   inline std::string GetChannelName(
109       const grpc::channelz::v1::Channel& channel) {
110     return channel.ref().name();
111   }
112 
113   // Get name of a subchannel
GetSubchannelName(const grpc::channelz::v1::Subchannel & subchannel)114   inline std::string GetSubchannelName(
115       const grpc::channelz::v1::Subchannel& subchannel) {
116     return subchannel.ref().name();
117   }
118 
119   // Get name of a socket
GetSocketName(const grpc::channelz::v1::Socket & socket)120   inline std::string GetSocketName(const grpc::channelz::v1::Socket& socket) {
121     return socket.ref().name();
122   }
123 
124   // Get a channel based on channel_id
GetChannelRPC(int64_t channel_id)125   grpc::channelz::v1::Channel GetChannelRPC(int64_t channel_id) {
126     GetChannelRequest get_channel_request;
127     get_channel_request.set_channel_id(channel_id);
128     GetChannelResponse get_channel_response;
129     ClientContext get_channel_context;
130     get_channel_context.set_deadline(
131         grpc_timeout_seconds_to_deadline(rpc_timeout_seconds_));
132     Status status = channelz_stub_->GetChannel(
133         &get_channel_context, get_channel_request, &get_channel_response);
134     if (!status.ok()) {
135       gpr_log(GPR_ERROR, "GetChannelRPC failed: %s",
136               get_channel_context.debug_error_string().c_str());
137       GPR_ASSERT(0);
138     }
139     return get_channel_response.channel();
140   }
141 
142   // Get a subchannel based on subchannel_id
GetSubchannelRPC(int64_t subchannel_id)143   grpc::channelz::v1::Subchannel GetSubchannelRPC(int64_t subchannel_id) {
144     GetSubchannelRequest get_subchannel_request;
145     get_subchannel_request.set_subchannel_id(subchannel_id);
146     GetSubchannelResponse get_subchannel_response;
147     ClientContext get_subchannel_context;
148     get_subchannel_context.set_deadline(
149         grpc_timeout_seconds_to_deadline(rpc_timeout_seconds_));
150     Status status = channelz_stub_->GetSubchannel(&get_subchannel_context,
151                                                   get_subchannel_request,
152                                                   &get_subchannel_response);
153     if (!status.ok()) {
154       gpr_log(GPR_ERROR, "GetSubchannelRPC failed: %s",
155               get_subchannel_context.debug_error_string().c_str());
156       GPR_ASSERT(0);
157     }
158     return get_subchannel_response.subchannel();
159   }
160 
161   // get a socket based on socket_id
GetSocketRPC(int64_t socket_id)162   grpc::channelz::v1::Socket GetSocketRPC(int64_t socket_id) {
163     GetSocketRequest get_socket_request;
164     get_socket_request.set_socket_id(socket_id);
165     GetSocketResponse get_socket_response;
166     ClientContext get_socket_context;
167     get_socket_context.set_deadline(
168         grpc_timeout_seconds_to_deadline(rpc_timeout_seconds_));
169     Status status = channelz_stub_->GetSocket(
170         &get_socket_context, get_socket_request, &get_socket_response);
171     if (!status.ok()) {
172       gpr_log(GPR_ERROR, "GetSocketRPC failed: %s",
173               get_socket_context.debug_error_string().c_str());
174       GPR_ASSERT(0);
175     }
176     return get_socket_response.socket();
177   }
178 
179   // get the descedent channels/subchannels/sockets of a channel
180   // push descedent channels/subchannels to queue for layer traverse
181   // store descedent channels/subchannels/sockets for dumping data
GetChannelDescedence(const grpc::channelz::v1::Channel & channel,std::queue<grpc::channelz::v1::Channel> & channel_queue,std::queue<grpc::channelz::v1::Subchannel> & subchannel_queue)182   void GetChannelDescedence(
183       const grpc::channelz::v1::Channel& channel,
184       std::queue<grpc::channelz::v1::Channel>& channel_queue,
185       std::queue<grpc::channelz::v1::Subchannel>& subchannel_queue) {
186     std::cout << "    Channel ID" << GetChannelID(channel) << "_"
187               << GetChannelName(channel) << " descendence - ";
188     if (channel.channel_ref_size() > 0 || channel.subchannel_ref_size() > 0) {
189       if (channel.channel_ref_size() > 0) {
190         std::cout << "channel: ";
191         for (const auto& _channelref : channel.channel_ref()) {
192           int64_t ch_id = _channelref.channel_id();
193           std::cout << "ID" << ch_id << "_" << _channelref.name() << " ";
194           grpc::channelz::v1::Channel ch = GetChannelRPC(ch_id);
195           channel_queue.push(ch);
196           if (CheckID(ch_id)) {
197             all_channels_.push_back(ch);
198             StoreChannelInJson(ch);
199           }
200         }
201         if (channel.subchannel_ref_size() > 0) {
202           std::cout << ", ";
203         }
204       }
205       if (channel.subchannel_ref_size() > 0) {
206         std::cout << "subchannel: ";
207         for (const auto& _subchannelref : channel.subchannel_ref()) {
208           int64_t subch_id = _subchannelref.subchannel_id();
209           std::cout << "ID" << subch_id << "_" << _subchannelref.name() << " ";
210           grpc::channelz::v1::Subchannel subch = GetSubchannelRPC(subch_id);
211           subchannel_queue.push(subch);
212           if (CheckID(subch_id)) {
213             all_subchannels_.push_back(subch);
214             StoreSubchannelInJson(subch);
215           }
216         }
217       }
218     } else if (channel.socket_ref_size() > 0) {
219       std::cout << "socket: ";
220       for (const auto& _socketref : channel.socket_ref()) {
221         int64_t so_id = _socketref.socket_id();
222         std::cout << "ID" << so_id << "_" << _socketref.name() << " ";
223         grpc::channelz::v1::Socket so = GetSocketRPC(so_id);
224         if (CheckID(so_id)) {
225           all_sockets_.push_back(so);
226           StoreSocketInJson(so);
227         }
228       }
229     }
230     std::cout << std::endl;
231   }
232 
233   // get the descedent channels/subchannels/sockets of a subchannel
234   // push descedent channels/subchannels to queue for layer traverse
235   // store descedent channels/subchannels/sockets for dumping data
GetSubchannelDescedence(grpc::channelz::v1::Subchannel & subchannel,std::queue<grpc::channelz::v1::Channel> & channel_queue,std::queue<grpc::channelz::v1::Subchannel> & subchannel_queue)236   void GetSubchannelDescedence(
237       grpc::channelz::v1::Subchannel& subchannel,
238       std::queue<grpc::channelz::v1::Channel>& channel_queue,
239       std::queue<grpc::channelz::v1::Subchannel>& subchannel_queue) {
240     std::cout << "    Subchannel ID" << GetSubchannelID(subchannel) << "_"
241               << GetSubchannelName(subchannel) << " descendence - ";
242     if (subchannel.channel_ref_size() > 0 ||
243         subchannel.subchannel_ref_size() > 0) {
244       if (subchannel.channel_ref_size() > 0) {
245         std::cout << "channel: ";
246         for (const auto& _channelref : subchannel.channel_ref()) {
247           int64_t ch_id = _channelref.channel_id();
248           std::cout << "ID" << ch_id << "_" << _channelref.name() << " ";
249           grpc::channelz::v1::Channel ch = GetChannelRPC(ch_id);
250           channel_queue.push(ch);
251           if (CheckID(ch_id)) {
252             all_channels_.push_back(ch);
253             StoreChannelInJson(ch);
254           }
255         }
256         if (subchannel.subchannel_ref_size() > 0) {
257           std::cout << ", ";
258         }
259       }
260       if (subchannel.subchannel_ref_size() > 0) {
261         std::cout << "subchannel: ";
262         for (const auto& _subchannelref : subchannel.subchannel_ref()) {
263           int64_t subch_id = _subchannelref.subchannel_id();
264           std::cout << "ID" << subch_id << "_" << _subchannelref.name() << " ";
265           grpc::channelz::v1::Subchannel subch = GetSubchannelRPC(subch_id);
266           subchannel_queue.push(subch);
267           if (CheckID(subch_id)) {
268             all_subchannels_.push_back(subch);
269             StoreSubchannelInJson(subch);
270           }
271         }
272       }
273     } else if (subchannel.socket_ref_size() > 0) {
274       std::cout << "socket: ";
275       for (const auto& _socketref : subchannel.socket_ref()) {
276         int64_t so_id = _socketref.socket_id();
277         std::cout << "ID" << so_id << "_" << _socketref.name() << " ";
278         grpc::channelz::v1::Socket so = GetSocketRPC(so_id);
279         if (CheckID(so_id)) {
280           all_sockets_.push_back(so);
281           StoreSocketInJson(so);
282         }
283       }
284     }
285     std::cout << std::endl;
286   }
287 
288   // Set up the channelz sampler client
289   // Initialize json as an array
Setup(const std::string & custom_credentials_type,const std::string & server_address)290   void Setup(const std::string& custom_credentials_type,
291              const std::string& server_address) {
292     json_ = grpc_core::Json::Array();
293     rpc_timeout_seconds_ = 20;
294     grpc::ChannelArguments channel_args;
295     std::shared_ptr<grpc::ChannelCredentials> channel_creds =
296         grpc::testing::GetCredentialsProvider()->GetChannelCredentials(
297             custom_credentials_type, &channel_args);
298     if (!channel_creds) {
299       gpr_log(GPR_ERROR,
300               "Wrong user credential type: %s. Allowed credential types: "
301               "INSECURE_CREDENTIALS, ssl, alts, google_default_credentials.",
302               custom_credentials_type.c_str());
303       GPR_ASSERT(0);
304     }
305     std::shared_ptr<grpc::Channel> channel =
306         CreateChannel(server_address, channel_creds);
307     channelz_stub_ = grpc::channelz::v1::Channelz::NewStub(channel);
308   }
309 
310   // Get all servers, keep querying until getting all
311   // Store servers for dumping data
312   // Need to check id repeating for servers
GetServersRPC()313   void GetServersRPC() {
314     int64_t server_start_id = 0;
315     while (true) {
316       GetServersRequest get_servers_request;
317       GetServersResponse get_servers_response;
318       ClientContext get_servers_context;
319       get_servers_context.set_deadline(
320           grpc_timeout_seconds_to_deadline(rpc_timeout_seconds_));
321       get_servers_request.set_start_server_id(server_start_id);
322       Status status = channelz_stub_->GetServers(
323           &get_servers_context, get_servers_request, &get_servers_response);
324       if (!status.ok()) {
325         if (status.error_code() == StatusCode::UNIMPLEMENTED) {
326           gpr_log(GPR_ERROR,
327                   "Error status UNIMPLEMENTED. Please check and make sure "
328                   "channelz has been registered on the server being queried.");
329         } else {
330           gpr_log(GPR_ERROR,
331                   "GetServers RPC with GetServersRequest.server_start_id=%d, "
332                   "failed: %s",
333                   static_cast<int>(server_start_id),
334                   get_servers_context.debug_error_string().c_str());
335         }
336         GPR_ASSERT(0);
337       }
338       for (const auto& _server : get_servers_response.server()) {
339         all_servers_.push_back(_server);
340         StoreServerInJson(_server);
341       }
342       if (!get_servers_response.end()) {
343         server_start_id = GetServerID(all_servers_.back()) + 1;
344       } else {
345         break;
346       }
347     }
348     std::cout << "Number of servers = " << all_servers_.size() << std::endl;
349   }
350 
351   // Get sockets that belongs to servers
352   // Store sockets for dumping data
GetSocketsOfServers()353   void GetSocketsOfServers() {
354     for (const auto& _server : all_servers_) {
355       std::cout << "Server ID" << GetServerID(_server) << "_"
356                 << GetServerName(_server) << " listen_socket - ";
357       for (const auto& _socket : _server.listen_socket()) {
358         int64_t so_id = _socket.socket_id();
359         std::cout << "ID" << so_id << "_" << _socket.name() << " ";
360         if (CheckID(so_id)) {
361           grpc::channelz::v1::Socket so = GetSocketRPC(so_id);
362           all_sockets_.push_back(so);
363           StoreSocketInJson(so);
364         }
365       }
366       std::cout << std::endl;
367     }
368   }
369 
370   // Get all top channels, keep querying until getting all
371   // Store channels for dumping data
372   // No need to check id repeating for top channels
GetTopChannelsRPC()373   void GetTopChannelsRPC() {
374     int64_t channel_start_id = 0;
375     while (true) {
376       GetTopChannelsRequest get_top_channels_request;
377       GetTopChannelsResponse get_top_channels_response;
378       ClientContext get_top_channels_context;
379       get_top_channels_context.set_deadline(
380           grpc_timeout_seconds_to_deadline(rpc_timeout_seconds_));
381       get_top_channels_request.set_start_channel_id(channel_start_id);
382       Status status = channelz_stub_->GetTopChannels(
383           &get_top_channels_context, get_top_channels_request,
384           &get_top_channels_response);
385       if (!status.ok()) {
386         gpr_log(GPR_ERROR,
387                 "GetTopChannels RPC with "
388                 "GetTopChannelsRequest.channel_start_id=%d failed: %s",
389                 static_cast<int>(channel_start_id),
390                 get_top_channels_context.debug_error_string().c_str());
391         GPR_ASSERT(0);
392       }
393       for (const auto& _topchannel : get_top_channels_response.channel()) {
394         top_channels_.push_back(_topchannel);
395         all_channels_.push_back(_topchannel);
396         StoreChannelInJson(_topchannel);
397       }
398       if (!get_top_channels_response.end()) {
399         channel_start_id = GetChannelID(top_channels_.back()) + 1;
400       } else {
401         break;
402       }
403     }
404     std::cout << std::endl
405               << "Number of top channels = " << top_channels_.size()
406               << std::endl;
407   }
408 
409   // layer traverse for each top channel
TraverseTopChannels()410   void TraverseTopChannels() {
411     for (const auto& _topchannel : top_channels_) {
412       int tree_depth = 0;
413       std::queue<grpc::channelz::v1::Channel> channel_queue;
414       std::queue<grpc::channelz::v1::Subchannel> subchannel_queue;
415       std::cout << "Tree depth = " << tree_depth << std::endl;
416       GetChannelDescedence(_topchannel, channel_queue, subchannel_queue);
417       while (!channel_queue.empty() || !subchannel_queue.empty()) {
418         ++tree_depth;
419         std::cout << "Tree depth = " << tree_depth << std::endl;
420         int ch_q_size = channel_queue.size();
421         int subch_q_size = subchannel_queue.size();
422         for (int i = 0; i < ch_q_size; ++i) {
423           grpc::channelz::v1::Channel ch = channel_queue.front();
424           channel_queue.pop();
425           GetChannelDescedence(ch, channel_queue, subchannel_queue);
426         }
427         for (int i = 0; i < subch_q_size; ++i) {
428           grpc::channelz::v1::Subchannel subch = subchannel_queue.front();
429           subchannel_queue.pop();
430           GetSubchannelDescedence(subch, channel_queue, subchannel_queue);
431         }
432       }
433       std::cout << std::endl;
434     }
435   }
436 
437   // dump data of all entities to stdout
DumpStdout()438   void DumpStdout() {
439     std::string data_str;
440     for (const auto& _channel : all_channels_) {
441       std::cout << "channel ID" << GetChannelID(_channel) << "_"
442                 << GetChannelName(_channel) << " data:" << std::endl;
443       // TODO(mohanli): TextFormat::PrintToString records time as seconds and
444       // nanos. Need a more human readable way.
445       ::google::protobuf::TextFormat::PrintToString(_channel.data(), &data_str);
446       printf("%s\n", data_str.c_str());
447     }
448     for (const auto& _subchannel : all_subchannels_) {
449       std::cout << "subchannel ID" << GetSubchannelID(_subchannel) << "_"
450                 << GetSubchannelName(_subchannel) << " data:" << std::endl;
451       ::google::protobuf::TextFormat::PrintToString(_subchannel.data(),
452                                                     &data_str);
453       printf("%s\n", data_str.c_str());
454     }
455     for (const auto& _server : all_servers_) {
456       std::cout << "server ID" << GetServerID(_server) << "_"
457                 << GetServerName(_server) << " data:" << std::endl;
458       ::google::protobuf::TextFormat::PrintToString(_server.data(), &data_str);
459       printf("%s\n", data_str.c_str());
460     }
461     for (const auto& _socket : all_sockets_) {
462       std::cout << "socket ID" << GetSocketID(_socket) << "_"
463                 << GetSocketName(_socket) << " data:" << std::endl;
464       ::google::protobuf::TextFormat::PrintToString(_socket.data(), &data_str);
465       printf("%s\n", data_str.c_str());
466     }
467   }
468 
469   // Store a channel in Json
StoreChannelInJson(const grpc::channelz::v1::Channel & channel)470   void StoreChannelInJson(const grpc::channelz::v1::Channel& channel) {
471     std::string id = grpc::to_string(GetChannelID(channel));
472     std::string type = "Channel";
473     std::string description;
474     ::google::protobuf::TextFormat::PrintToString(channel.data(), &description);
475     grpc_core::Json description_json = grpc_core::Json::FromString(description);
476     StoreEntityInJson(id, type, description_json);
477   }
478 
479   // Store a subchannel in Json
StoreSubchannelInJson(const grpc::channelz::v1::Subchannel & subchannel)480   void StoreSubchannelInJson(const grpc::channelz::v1::Subchannel& subchannel) {
481     std::string id = grpc::to_string(GetSubchannelID(subchannel));
482     std::string type = "Subchannel";
483     std::string description;
484     ::google::protobuf::TextFormat::PrintToString(subchannel.data(),
485                                                   &description);
486     grpc_core::Json description_json = grpc_core::Json::FromString(description);
487     StoreEntityInJson(id, type, description_json);
488   }
489 
490   // Store a server in Json
StoreServerInJson(const grpc::channelz::v1::Server & server)491   void StoreServerInJson(const grpc::channelz::v1::Server& server) {
492     std::string id = grpc::to_string(GetServerID(server));
493     std::string type = "Server";
494     std::string description;
495     ::google::protobuf::TextFormat::PrintToString(server.data(), &description);
496     grpc_core::Json description_json = grpc_core::Json::FromString(description);
497     StoreEntityInJson(id, type, description_json);
498   }
499 
500   // Store a socket in Json
StoreSocketInJson(const grpc::channelz::v1::Socket & socket)501   void StoreSocketInJson(const grpc::channelz::v1::Socket& socket) {
502     std::string id = grpc::to_string(GetSocketID(socket));
503     std::string type = "Socket";
504     std::string description;
505     ::google::protobuf::TextFormat::PrintToString(socket.data(), &description);
506     grpc_core::Json description_json = grpc_core::Json::FromString(description);
507     StoreEntityInJson(id, type, description_json);
508   }
509 
510   // Store an entity in Json
StoreEntityInJson(std::string & id,std::string & type,const grpc_core::Json & description)511   void StoreEntityInJson(std::string& id, std::string& type,
512                          const grpc_core::Json& description) {
513     std::string start, finish;
514     gpr_timespec ago = gpr_time_sub(
515         now_,
516         gpr_time_from_seconds(absl::GetFlag(FLAGS_sampling_interval_seconds),
517                               GPR_TIMESPAN));
518     std::stringstream ss;
519     const time_t time_now = now_.tv_sec;
520     ss << std::put_time(std::localtime(&time_now), "%F %T");
521     finish = ss.str();  // example: "2019-02-01 12:12:18"
522     ss.str("");
523     const time_t time_ago = ago.tv_sec;
524     ss << std::put_time(std::localtime(&time_ago), "%F %T");
525     start = ss.str();
526     grpc_core::Json obj = grpc_core::Json::FromObject(
527         {{"Task",
528           grpc_core::Json::FromString(absl::StrFormat("%s_ID%s", type, id))},
529          {"Start", grpc_core::Json::FromString(start)},
530          {"Finish", grpc_core::Json::FromString(finish)},
531          {"ID", grpc_core::Json::FromString(id)},
532          {"Type", grpc_core::Json::FromString(type)},
533          {"Description", description}});
534     json_.push_back(obj);
535   }
536 
537   // Dump data in json
DumpJson()538   std::string DumpJson() {
539     return grpc_core::JsonDump(grpc_core::Json::FromArray(json_));
540   }
541 
542   // Check if one entity has been recorded
CheckID(int64_t id)543   bool CheckID(int64_t id) {
544     if (id_set_.count(id) == 0) {
545       id_set_.insert(id);
546       return true;
547     } else {
548       return false;
549     }
550   }
551 
552   // Record current time
RecordNow()553   void RecordNow() { now_ = gpr_now(GPR_CLOCK_REALTIME); }
554 
555  private:
556   std::unique_ptr<grpc::channelz::v1::Channelz::Stub> channelz_stub_;
557   std::vector<grpc::channelz::v1::Channel> top_channels_;
558   std::vector<grpc::channelz::v1::Server> all_servers_;
559   std::vector<grpc::channelz::v1::Channel> all_channels_;
560   std::vector<grpc::channelz::v1::Subchannel> all_subchannels_;
561   std::vector<grpc::channelz::v1::Socket> all_sockets_;
562   std::unordered_set<int64_t> id_set_;
563   grpc_core::Json::Array json_;
564   int64_t rpc_timeout_seconds_;
565   gpr_timespec now_;
566 };
567 
main(int argc,char ** argv)568 int main(int argc, char** argv) {
569   grpc::testing::TestEnvironment env(&argc, argv);
570   grpc::testing::InitTest(&argc, &argv, true);
571   std::ofstream output_file(absl::GetFlag(FLAGS_output_json));
572   for (int i = 0; i < absl::GetFlag(FLAGS_sampling_times); ++i) {
573     ChannelzSampler channelz_sampler;
574     channelz_sampler.Setup(absl::GetFlag(FLAGS_custom_credentials_type),
575                            absl::GetFlag(FLAGS_server_address));
576     std::cout << "Wait for sampling interval "
577               << absl::GetFlag(FLAGS_sampling_interval_seconds) << "s..."
578               << std::endl;
579     const gpr_timespec kDelay = gpr_time_add(
580         gpr_now(GPR_CLOCK_MONOTONIC),
581         gpr_time_from_seconds(absl::GetFlag(FLAGS_sampling_interval_seconds),
582                               GPR_TIMESPAN));
583     gpr_sleep_until(kDelay);
584     std::cout << "##### " << i << "th sampling #####" << std::endl;
585     channelz_sampler.RecordNow();
586     channelz_sampler.GetServersRPC();
587     channelz_sampler.GetSocketsOfServers();
588     channelz_sampler.GetTopChannelsRPC();
589     channelz_sampler.TraverseTopChannels();
590     channelz_sampler.DumpStdout();
591     if (!absl::GetFlag(FLAGS_output_json).empty()) {
592       output_file << channelz_sampler.DumpJson() << "\n" << std::flush;
593     }
594   }
595   output_file.close();
596   return 0;
597 }
598