Imported Upstream version 1.32.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(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   GPR_ASSERT(start_socket_id >= 0);
314   GPR_ASSERT(max_results >= 0);
315   // If user does not set max_results, we choose 500.
316   size_t pagination_limit = max_results == 0 ? 500 : max_results;
317   Json::Object object;
318   {
319     MutexLock lock(&child_mu_);
320     size_t sockets_rendered = 0;
321     // Create list of socket refs.
322     Json::Array array;
323     auto it = child_sockets_.lower_bound(start_socket_id);
324     for (; it != child_sockets_.end() && sockets_rendered < pagination_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     if (it == child_sockets_.end()) object["end"] = true;
333   }
334   Json json = std::move(object);
335   return json.Dump();
336 }
337
338 Json ServerNode::RenderJson() {
339   Json::Object data;
340   // Fill in the channel trace if applicable.
341   Json trace_json = trace_.RenderJson();
342   if (trace_json.type() != Json::Type::JSON_NULL) {
343     data["trace"] = std::move(trace_json);
344   }
345   // Ask CallCountingHelper to populate call count data.
346   call_counter_.PopulateCallCounts(&data);
347   // Construct top-level object.
348   Json::Object object = {
349       {"ref",
350        Json::Object{
351            {"serverId", std::to_string(uuid())},
352        }},
353       {"data", std::move(data)},
354   };
355   // Render listen sockets.
356   {
357     MutexLock lock(&child_mu_);
358     if (!child_listen_sockets_.empty()) {
359       Json::Array array;
360       for (const auto& it : child_listen_sockets_) {
361         array.emplace_back(Json::Object{
362             {"socketId", std::to_string(it.first)},
363             {"name", it.second->name()},
364         });
365       }
366       object["listenSocket"] = std::move(array);
367     }
368   }
369   return object;
370 }
371
372 //
373 // SocketNode
374 //
375
376 namespace {
377
378 void PopulateSocketAddressJson(Json::Object* json, const char* name,
379                                const char* addr_str) {
380   if (addr_str == nullptr) return;
381   Json::Object data;
382   grpc_uri* uri = grpc_uri_parse(addr_str, true);
383   if ((uri != nullptr) && ((strcmp(uri->scheme, "ipv4") == 0) ||
384                            (strcmp(uri->scheme, "ipv6") == 0))) {
385     const char* host_port = uri->path;
386     if (*host_port == '/') ++host_port;
387     std::string host;
388     std::string port;
389     GPR_ASSERT(SplitHostPort(host_port, &host, &port));
390     int port_num = -1;
391     if (!port.empty()) {
392       port_num = atoi(port.data());
393     }
394     char* b64_host = grpc_base64_encode(host.data(), host.size(), false, false);
395     data["tcpip_address"] = Json::Object{
396         {"port", port_num},
397         {"ip_address", b64_host},
398     };
399     gpr_free(b64_host);
400   } else if (uri != nullptr && strcmp(uri->scheme, "unix") == 0) {
401     data["uds_address"] = Json::Object{
402         {"filename", uri->path},
403     };
404   } else {
405     data["other_address"] = Json::Object{
406         {"name", addr_str},
407     };
408   }
409   grpc_uri_destroy(uri);
410   (*json)[name] = std::move(data);
411 }
412
413 }  // namespace
414
415 SocketNode::SocketNode(std::string local, std::string remote, std::string name)
416     : BaseNode(EntityType::kSocket, std::move(name)),
417       local_(std::move(local)),
418       remote_(std::move(remote)) {}
419
420 void SocketNode::RecordStreamStartedFromLocal() {
421   streams_started_.FetchAdd(1, MemoryOrder::RELAXED);
422   last_local_stream_created_cycle_.Store(gpr_get_cycle_counter(),
423                                          MemoryOrder::RELAXED);
424 }
425
426 void SocketNode::RecordStreamStartedFromRemote() {
427   streams_started_.FetchAdd(1, MemoryOrder::RELAXED);
428   last_remote_stream_created_cycle_.Store(gpr_get_cycle_counter(),
429                                           MemoryOrder::RELAXED);
430 }
431
432 void SocketNode::RecordMessagesSent(uint32_t num_sent) {
433   messages_sent_.FetchAdd(num_sent, MemoryOrder::RELAXED);
434   last_message_sent_cycle_.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED);
435 }
436
437 void SocketNode::RecordMessageReceived() {
438   messages_received_.FetchAdd(1, MemoryOrder::RELAXED);
439   last_message_received_cycle_.Store(gpr_get_cycle_counter(),
440                                      MemoryOrder::RELAXED);
441 }
442
443 Json SocketNode::RenderJson() {
444   // Create and fill the data child.
445   Json::Object data;
446   gpr_timespec ts;
447   int64_t streams_started = streams_started_.Load(MemoryOrder::RELAXED);
448   if (streams_started != 0) {
449     data["streamsStarted"] = std::to_string(streams_started);
450     gpr_cycle_counter last_local_stream_created_cycle =
451         last_local_stream_created_cycle_.Load(MemoryOrder::RELAXED);
452     if (last_local_stream_created_cycle != 0) {
453       ts = gpr_convert_clock_type(
454           gpr_cycle_counter_to_time(last_local_stream_created_cycle),
455           GPR_CLOCK_REALTIME);
456       data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
457     }
458     gpr_cycle_counter last_remote_stream_created_cycle =
459         last_remote_stream_created_cycle_.Load(MemoryOrder::RELAXED);
460     if (last_remote_stream_created_cycle != 0) {
461       ts = gpr_convert_clock_type(
462           gpr_cycle_counter_to_time(last_remote_stream_created_cycle),
463           GPR_CLOCK_REALTIME);
464       data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
465     }
466   }
467   int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED);
468   if (streams_succeeded != 0) {
469     data["streamsSucceeded"] = std::to_string(streams_succeeded);
470   }
471   int64_t streams_failed = streams_failed_.Load(MemoryOrder::RELAXED);
472   if (streams_failed != 0) {
473     data["streamsFailed"] = std::to_string(streams_failed);
474   }
475   int64_t messages_sent = messages_sent_.Load(MemoryOrder::RELAXED);
476   if (messages_sent != 0) {
477     data["messagesSent"] = std::to_string(messages_sent);
478     ts = gpr_convert_clock_type(
479         gpr_cycle_counter_to_time(
480             last_message_sent_cycle_.Load(MemoryOrder::RELAXED)),
481         GPR_CLOCK_REALTIME);
482     data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
483   }
484   int64_t messages_received = messages_received_.Load(MemoryOrder::RELAXED);
485   if (messages_received != 0) {
486     data["messagesReceived"] = std::to_string(messages_received);
487     ts = gpr_convert_clock_type(
488         gpr_cycle_counter_to_time(
489             last_message_received_cycle_.Load(MemoryOrder::RELAXED)),
490         GPR_CLOCK_REALTIME);
491     data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
492   }
493   int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED);
494   if (keepalives_sent != 0) {
495     data["keepAlivesSent"] = std::to_string(keepalives_sent);
496   }
497   // Create and fill the parent object.
498   Json::Object object = {
499       {"ref",
500        Json::Object{
501            {"socketId", std::to_string(uuid())},
502            {"name", name()},
503        }},
504       {"data", std::move(data)},
505   };
506   PopulateSocketAddressJson(&object, "remote", remote_.c_str());
507   PopulateSocketAddressJson(&object, "local", local_.c_str());
508   return object;
509 }
510
511 //
512 // ListenSocketNode
513 //
514
515 ListenSocketNode::ListenSocketNode(std::string local_addr, std::string name)
516     : BaseNode(EntityType::kSocket, std::move(name)),
517       local_addr_(std::move(local_addr)) {}
518
519 Json ListenSocketNode::RenderJson() {
520   Json::Object object = {
521       {"ref",
522        Json::Object{
523            {"socketId", std::to_string(uuid())},
524            {"name", name()},
525        }},
526   };
527   PopulateSocketAddressJson(&object, "local", local_addr_.c_str());
528   return object;
529 }
530
531 }  // namespace channelz
532 }  // namespace grpc_core