Imported Upstream version 1.31.0
[platform/upstream/grpc.git] / src / core / lib / channel / channelz.cc
1 /*
2  *
3  * Copyright 2017 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
19 #include <grpc/impl/codegen/port_platform.h>
20
21 #include "src/core/lib/channel/channelz.h"
22
23 #include <grpc/grpc.h>
24 #include <grpc/support/alloc.h>
25 #include <grpc/support/log.h>
26 #include <grpc/support/string_util.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include "src/core/lib/channel/channelz_registry.h"
32 #include "src/core/lib/channel/status_util.h"
33 #include "src/core/lib/gpr/string.h"
34 #include "src/core/lib/gpr/useful.h"
35 #include "src/core/lib/gprpp/atomic.h"
36 #include "src/core/lib/gprpp/host_port.h"
37 #include "src/core/lib/gprpp/memory.h"
38 #include "src/core/lib/iomgr/error.h"
39 #include "src/core/lib/iomgr/exec_ctx.h"
40 #include "src/core/lib/slice/b64.h"
41 #include "src/core/lib/slice/slice_internal.h"
42 #include "src/core/lib/surface/channel.h"
43 #include "src/core/lib/surface/server.h"
44 #include "src/core/lib/transport/connectivity_state.h"
45 #include "src/core/lib/transport/error_utils.h"
46 #include "src/core/lib/uri/uri_parser.h"
47
48 namespace grpc_core {
49 namespace channelz {
50
51 //
52 // channel arg code
53 //
54
55 namespace {
56
57 void* parent_uuid_copy(void* p) { return p; }
58 void parent_uuid_destroy(void* /*p*/) {}
59 int parent_uuid_cmp(void* p1, void* p2) { return GPR_ICMP(p1, p2); }
60 const grpc_arg_pointer_vtable parent_uuid_vtable = {
61     parent_uuid_copy, parent_uuid_destroy, parent_uuid_cmp};
62
63 }  // namespace
64
65 grpc_arg MakeParentUuidArg(intptr_t parent_uuid) {
66   // We would ideally like to store the uuid in an integer argument.
67   // Unfortunately, that won't work, because intptr_t (the type used for
68   // uuids) doesn't fit in an int (the type used for integer args).
69   // So instead, we use a hack to store it as a pointer, because
70   // intptr_t should be the same size as void*.
71   static_assert(sizeof(intptr_t) <= sizeof(void*),
72                 "can't fit intptr_t inside of void*");
73   return grpc_channel_arg_pointer_create(
74       const_cast<char*>(GRPC_ARG_CHANNELZ_PARENT_UUID),
75       reinterpret_cast<void*>(parent_uuid), &parent_uuid_vtable);
76 }
77
78 intptr_t GetParentUuidFromArgs(const grpc_channel_args& args) {
79   const grpc_arg* arg =
80       grpc_channel_args_find(&args, GRPC_ARG_CHANNELZ_PARENT_UUID);
81   if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return 0;
82   return reinterpret_cast<intptr_t>(arg->value.pointer.p);
83 }
84
85 //
86 // BaseNode
87 //
88
89 BaseNode::BaseNode(EntityType type, std::string name)
90     : type_(type), uuid_(-1), name_(std::move(name)) {
91   // The registry will set uuid_ under its lock.
92   ChannelzRegistry::Register(this);
93 }
94
95 BaseNode::~BaseNode() { ChannelzRegistry::Unregister(uuid_); }
96
97 std::string BaseNode::RenderJsonString() {
98   Json json = RenderJson();
99   return json.Dump();
100 }
101
102 //
103 // CallCountingHelper
104 //
105
106 CallCountingHelper::CallCountingHelper() {
107   num_cores_ = GPR_MAX(1, gpr_cpu_num_cores());
108   per_cpu_counter_data_storage_.reserve(num_cores_);
109   for (size_t i = 0; i < num_cores_; ++i) {
110     per_cpu_counter_data_storage_.emplace_back();
111   }
112 }
113
114 void CallCountingHelper::RecordCallStarted() {
115   AtomicCounterData& data =
116       per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()];
117   data.calls_started.FetchAdd(1, MemoryOrder::RELAXED);
118   data.last_call_started_cycle.Store(gpr_get_cycle_counter(),
119                                      MemoryOrder::RELAXED);
120 }
121
122 void CallCountingHelper::RecordCallFailed() {
123   per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
124       .calls_failed.FetchAdd(1, MemoryOrder::RELAXED);
125 }
126
127 void CallCountingHelper::RecordCallSucceeded() {
128   per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
129       .calls_succeeded.FetchAdd(1, MemoryOrder::RELAXED);
130 }
131
132 void CallCountingHelper::CollectData(CounterData* out) {
133   for (size_t core = 0; core < num_cores_; ++core) {
134     AtomicCounterData& data = per_cpu_counter_data_storage_[core];
135
136     out->calls_started += data.calls_started.Load(MemoryOrder::RELAXED);
137     out->calls_succeeded +=
138         per_cpu_counter_data_storage_[core].calls_succeeded.Load(
139             MemoryOrder::RELAXED);
140     out->calls_failed += per_cpu_counter_data_storage_[core].calls_failed.Load(
141         MemoryOrder::RELAXED);
142     const gpr_cycle_counter last_call =
143         per_cpu_counter_data_storage_[core].last_call_started_cycle.Load(
144             MemoryOrder::RELAXED);
145     if (last_call > out->last_call_started_cycle) {
146       out->last_call_started_cycle = last_call;
147     }
148   }
149 }
150
151 void CallCountingHelper::PopulateCallCounts(Json::Object* object) {
152   CounterData data;
153   CollectData(&data);
154   if (data.calls_started != 0) {
155     (*object)["callsStarted"] = std::to_string(data.calls_started);
156     gpr_timespec ts = gpr_convert_clock_type(
157         gpr_cycle_counter_to_time(data.last_call_started_cycle),
158         GPR_CLOCK_REALTIME);
159     (*object)["lastCallStartedTimestamp"] = gpr_format_timespec(ts);
160   }
161   if (data.calls_succeeded != 0) {
162     (*object)["callsSucceeded"] = std::to_string(data.calls_succeeded);
163   }
164   if (data.calls_failed) {
165     (*object)["callsFailed"] = std::to_string(data.calls_failed);
166   }
167 }
168
169 //
170 // ChannelNode
171 //
172
173 ChannelNode::ChannelNode(std::string target, size_t channel_tracer_max_nodes,
174                          intptr_t parent_uuid)
175     : BaseNode(parent_uuid == 0 ? EntityType::kTopLevelChannel
176                                 : EntityType::kInternalChannel,
177                target),
178       target_(std::move(target)),
179       trace_(channel_tracer_max_nodes),
180       parent_uuid_(parent_uuid) {}
181
182 const char* ChannelNode::GetChannelConnectivityStateChangeString(
183     grpc_connectivity_state state) {
184   switch (state) {
185     case GRPC_CHANNEL_IDLE:
186       return "Channel state change to IDLE";
187     case GRPC_CHANNEL_CONNECTING:
188       return "Channel state change to CONNECTING";
189     case GRPC_CHANNEL_READY:
190       return "Channel state change to READY";
191     case GRPC_CHANNEL_TRANSIENT_FAILURE:
192       return "Channel state change to TRANSIENT_FAILURE";
193     case GRPC_CHANNEL_SHUTDOWN:
194       return "Channel state change to SHUTDOWN";
195   }
196   GPR_UNREACHABLE_CODE(return "UNKNOWN");
197 }
198
199 Json ChannelNode::RenderJson() {
200   Json::Object data = {
201       {"target", target_},
202   };
203   // Connectivity state.
204   // If low-order bit is on, then the field is set.
205   int state_field = connectivity_state_.Load(MemoryOrder::RELAXED);
206   if ((state_field & 1) != 0) {
207     grpc_connectivity_state state =
208         static_cast<grpc_connectivity_state>(state_field >> 1);
209     data["state"] = Json::Object{
210         {"state", ConnectivityStateName(state)},
211     };
212   }
213   // Fill in the channel trace if applicable.
214   Json trace_json = trace_.RenderJson();
215   if (trace_json.type() != Json::Type::JSON_NULL) {
216     data["trace"] = std::move(trace_json);
217   }
218   // Ask CallCountingHelper to populate call count data.
219   call_counter_.PopulateCallCounts(&data);
220   // Construct outer object.
221   Json::Object json = {
222       {"ref",
223        Json::Object{
224            {"channelId", std::to_string(uuid())},
225        }},
226       {"data", std::move(data)},
227   };
228   // Template method. Child classes may override this to add their specific
229   // functionality.
230   PopulateChildRefs(&json);
231   return json;
232 }
233
234 void ChannelNode::PopulateChildRefs(Json::Object* json) {
235   MutexLock lock(&child_mu_);
236   if (!child_subchannels_.empty()) {
237     Json::Array array;
238     for (const auto& p : child_subchannels_) {
239       array.emplace_back(Json::Object{
240           {"subchannelId", std::to_string(p.first)},
241       });
242     }
243     (*json)["subchannelRef"] = std::move(array);
244   }
245   if (!child_channels_.empty()) {
246     Json::Array array;
247     for (const auto& p : child_channels_) {
248       array.emplace_back(Json::Object{
249           {"channelId", std::to_string(p.first)},
250       });
251     }
252     (*json)["channelRef"] = std::move(array);
253   }
254 }
255
256 void ChannelNode::SetConnectivityState(grpc_connectivity_state state) {
257   // Store with low-order bit set to indicate that the field is set.
258   int state_field = (state << 1) + 1;
259   connectivity_state_.Store(state_field, MemoryOrder::RELAXED);
260 }
261
262 void ChannelNode::AddChildChannel(intptr_t child_uuid) {
263   MutexLock lock(&child_mu_);
264   child_channels_.insert(std::make_pair(child_uuid, true));
265 }
266
267 void ChannelNode::RemoveChildChannel(intptr_t child_uuid) {
268   MutexLock lock(&child_mu_);
269   child_channels_.erase(child_uuid);
270 }
271
272 void ChannelNode::AddChildSubchannel(intptr_t child_uuid) {
273   MutexLock lock(&child_mu_);
274   child_subchannels_.insert(std::make_pair(child_uuid, true));
275 }
276
277 void ChannelNode::RemoveChildSubchannel(intptr_t child_uuid) {
278   MutexLock lock(&child_mu_);
279   child_subchannels_.erase(child_uuid);
280 }
281
282 //
283 // ServerNode
284 //
285
286 ServerNode::ServerNode(grpc_server* /*server*/, size_t channel_tracer_max_nodes)
287     : BaseNode(EntityType::kServer, ""), trace_(channel_tracer_max_nodes) {}
288
289 ServerNode::~ServerNode() {}
290
291 void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) {
292   MutexLock lock(&child_mu_);
293   child_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
294 }
295
296 void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
297   MutexLock lock(&child_mu_);
298   child_sockets_.erase(child_uuid);
299 }
300
301 void ServerNode::AddChildListenSocket(RefCountedPtr<ListenSocketNode> node) {
302   MutexLock lock(&child_mu_);
303   child_listen_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
304 }
305
306 void ServerNode::RemoveChildListenSocket(intptr_t child_uuid) {
307   MutexLock lock(&child_mu_);
308   child_listen_sockets_.erase(child_uuid);
309 }
310
311 std::string ServerNode::RenderServerSockets(intptr_t start_socket_id,
312                                             intptr_t max_results) {
313   // If user does not set max_results, we choose 500.
314   size_t pagination_limit = max_results == 0 ? 500 : max_results;
315   Json::Object object;
316   {
317     MutexLock lock(&child_mu_);
318     size_t sockets_rendered = 0;
319     if (!child_sockets_.empty()) {
320       // Create list of socket refs.
321       Json::Array array;
322       const size_t limit = GPR_MIN(child_sockets_.size(), pagination_limit);
323       for (auto it = child_sockets_.lower_bound(start_socket_id);
324            it != child_sockets_.end() && sockets_rendered < limit;
325            ++it, ++sockets_rendered) {
326         array.emplace_back(Json::Object{
327             {"socketId", std::to_string(it->first)},
328             {"name", it->second->name()},
329         });
330       }
331       object["socketRef"] = std::move(array);
332     }
333     if (sockets_rendered == child_sockets_.size()) object["end"] = true;
334   }
335   Json json = std::move(object);
336   return json.Dump();
337 }
338
339 Json ServerNode::RenderJson() {
340   Json::Object data;
341   // Fill in the channel trace if applicable.
342   Json trace_json = trace_.RenderJson();
343   if (trace_json.type() != Json::Type::JSON_NULL) {
344     data["trace"] = std::move(trace_json);
345   }
346   // Ask CallCountingHelper to populate call count data.
347   call_counter_.PopulateCallCounts(&data);
348   // Construct top-level object.
349   Json::Object object = {
350       {"ref",
351        Json::Object{
352            {"serverId", std::to_string(uuid())},
353        }},
354       {"data", std::move(data)},
355   };
356   // Render listen sockets.
357   {
358     MutexLock lock(&child_mu_);
359     if (!child_listen_sockets_.empty()) {
360       Json::Array array;
361       for (const auto& it : child_listen_sockets_) {
362         array.emplace_back(Json::Object{
363             {"socketId", std::to_string(it.first)},
364             {"name", it.second->name()},
365         });
366       }
367       object["listenSocket"] = std::move(array);
368     }
369   }
370   return object;
371 }
372
373 //
374 // SocketNode
375 //
376
377 namespace {
378
379 void PopulateSocketAddressJson(Json::Object* json, const char* name,
380                                const char* addr_str) {
381   if (addr_str == nullptr) return;
382   Json::Object data;
383   grpc_uri* uri = grpc_uri_parse(addr_str, true);
384   if ((uri != nullptr) && ((strcmp(uri->scheme, "ipv4") == 0) ||
385                            (strcmp(uri->scheme, "ipv6") == 0))) {
386     const char* host_port = uri->path;
387     if (*host_port == '/') ++host_port;
388     std::string host;
389     std::string port;
390     GPR_ASSERT(SplitHostPort(host_port, &host, &port));
391     int port_num = -1;
392     if (!port.empty()) {
393       port_num = atoi(port.data());
394     }
395     char* b64_host = grpc_base64_encode(host.data(), host.size(), false, false);
396     data["tcpip_address"] = Json::Object{
397         {"port", port_num},
398         {"ip_address", b64_host},
399     };
400     gpr_free(b64_host);
401   } else if (uri != nullptr && strcmp(uri->scheme, "unix") == 0) {
402     data["uds_address"] = Json::Object{
403         {"filename", uri->path},
404     };
405   } else {
406     data["other_address"] = Json::Object{
407         {"name", addr_str},
408     };
409   }
410   grpc_uri_destroy(uri);
411   (*json)[name] = std::move(data);
412 }
413
414 }  // namespace
415
416 SocketNode::SocketNode(std::string local, std::string remote, std::string name)
417     : BaseNode(EntityType::kSocket, std::move(name)),
418       local_(std::move(local)),
419       remote_(std::move(remote)) {}
420
421 void SocketNode::RecordStreamStartedFromLocal() {
422   streams_started_.FetchAdd(1, MemoryOrder::RELAXED);
423   last_local_stream_created_cycle_.Store(gpr_get_cycle_counter(),
424                                          MemoryOrder::RELAXED);
425 }
426
427 void SocketNode::RecordStreamStartedFromRemote() {
428   streams_started_.FetchAdd(1, MemoryOrder::RELAXED);
429   last_remote_stream_created_cycle_.Store(gpr_get_cycle_counter(),
430                                           MemoryOrder::RELAXED);
431 }
432
433 void SocketNode::RecordMessagesSent(uint32_t num_sent) {
434   messages_sent_.FetchAdd(num_sent, MemoryOrder::RELAXED);
435   last_message_sent_cycle_.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED);
436 }
437
438 void SocketNode::RecordMessageReceived() {
439   messages_received_.FetchAdd(1, MemoryOrder::RELAXED);
440   last_message_received_cycle_.Store(gpr_get_cycle_counter(),
441                                      MemoryOrder::RELAXED);
442 }
443
444 Json SocketNode::RenderJson() {
445   // Create and fill the data child.
446   Json::Object data;
447   gpr_timespec ts;
448   int64_t streams_started = streams_started_.Load(MemoryOrder::RELAXED);
449   if (streams_started != 0) {
450     data["streamsStarted"] = std::to_string(streams_started);
451     gpr_cycle_counter last_local_stream_created_cycle =
452         last_local_stream_created_cycle_.Load(MemoryOrder::RELAXED);
453     if (last_local_stream_created_cycle != 0) {
454       ts = gpr_convert_clock_type(
455           gpr_cycle_counter_to_time(last_local_stream_created_cycle),
456           GPR_CLOCK_REALTIME);
457       data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
458     }
459     gpr_cycle_counter last_remote_stream_created_cycle =
460         last_remote_stream_created_cycle_.Load(MemoryOrder::RELAXED);
461     if (last_remote_stream_created_cycle != 0) {
462       ts = gpr_convert_clock_type(
463           gpr_cycle_counter_to_time(last_remote_stream_created_cycle),
464           GPR_CLOCK_REALTIME);
465       data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
466     }
467   }
468   int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED);
469   if (streams_succeeded != 0) {
470     data["streamsSucceeded"] = std::to_string(streams_succeeded);
471   }
472   int64_t streams_failed = streams_failed_.Load(MemoryOrder::RELAXED);
473   if (streams_failed != 0) {
474     data["streamsFailed"] = std::to_string(streams_failed);
475   }
476   int64_t messages_sent = messages_sent_.Load(MemoryOrder::RELAXED);
477   if (messages_sent != 0) {
478     data["messagesSent"] = std::to_string(messages_sent);
479     ts = gpr_convert_clock_type(
480         gpr_cycle_counter_to_time(
481             last_message_sent_cycle_.Load(MemoryOrder::RELAXED)),
482         GPR_CLOCK_REALTIME);
483     data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
484   }
485   int64_t messages_received = messages_received_.Load(MemoryOrder::RELAXED);
486   if (messages_received != 0) {
487     data["messagesReceived"] = std::to_string(messages_received);
488     ts = gpr_convert_clock_type(
489         gpr_cycle_counter_to_time(
490             last_message_received_cycle_.Load(MemoryOrder::RELAXED)),
491         GPR_CLOCK_REALTIME);
492     data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
493   }
494   int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED);
495   if (keepalives_sent != 0) {
496     data["keepAlivesSent"] = std::to_string(keepalives_sent);
497   }
498   // Create and fill the parent object.
499   Json::Object object = {
500       {"ref",
501        Json::Object{
502            {"socketId", std::to_string(uuid())},
503            {"name", name()},
504        }},
505       {"data", std::move(data)},
506   };
507   PopulateSocketAddressJson(&object, "remote", remote_.c_str());
508   PopulateSocketAddressJson(&object, "local", local_.c_str());
509   return object;
510 }
511
512 //
513 // ListenSocketNode
514 //
515
516 ListenSocketNode::ListenSocketNode(std::string local_addr, std::string name)
517     : BaseNode(EntityType::kSocket, std::move(name)),
518       local_addr_(std::move(local_addr)) {}
519
520 Json ListenSocketNode::RenderJson() {
521   Json::Object object = {
522       {"ref",
523        Json::Object{
524            {"socketId", std::to_string(uuid())},
525            {"name", name()},
526        }},
527   };
528   PopulateSocketAddressJson(&object, "local", local_addr_.c_str());
529   return object;
530 }
531
532 }  // namespace channelz
533 }  // namespace grpc_core