Debian Codegraph @

src/core/lib/channel/channelz.cc

raw
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/support/port_platform.h>
20
21 #include "src/core/lib/channel/channelz.h"
22
23 #include <algorithm>
24 #include <atomic>
25
26 #include "absl/status/statusor.h"
27 #include "absl/strings/escaping.h"
28 #include "absl/strings/strip.h"
29
30 #include <grpc/impl/codegen/gpr_types.h>
31 #include <grpc/support/cpu.h>
32 #include <grpc/support/log.h>
33 #include <grpc/support/time.h>
34
35 #include "src/core/lib/address_utils/parse_address.h"
36 #include "src/core/lib/address_utils/sockaddr_utils.h"
37 #include "src/core/lib/channel/channel_args.h"
38 #include "src/core/lib/channel/channelz_registry.h"
39 #include "src/core/lib/gpr/string.h"
40 #include "src/core/lib/gpr/useful.h"
41 #include "src/core/lib/iomgr/exec_ctx.h"
42 #include "src/core/lib/iomgr/resolved_address.h"
43 #include "src/core/lib/transport/connectivity_state.h"
44 #include "src/core/lib/uri/uri_parser.h"
45
46 namespace grpc_core {
47 namespace channelz {
48
49 //
50 // BaseNode
51 //
52
53 BaseNode::BaseNode(EntityType type, std::string name)
54 : type_(type), uuid_(-1), name_(std::move(name)) {
55 // The registry will set uuid_ under its lock.
56 ChannelzRegistry::Register(this);
57 }
58
59 BaseNode::~BaseNode() { ChannelzRegistry::Unregister(uuid_); }
60
61 std::string BaseNode::RenderJsonString() {
62 Json json = RenderJson();
63 return json.Dump();
64 }
65
66 //
67 // CallCountingHelper
68 //
69
70 CallCountingHelper::CallCountingHelper() {
71 num_cores_ = std::max(1u, gpr_cpu_num_cores());
72 per_cpu_counter_data_storage_.reserve(num_cores_);
73 for (size_t i = 0; i < num_cores_; ++i) {
74 per_cpu_counter_data_storage_.emplace_back();
75 }
76 }
77
78 void CallCountingHelper::RecordCallStarted() {
79 AtomicCounterData& data =
80 per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()];
81 data.calls_started.fetch_add(1, std::memory_order_relaxed);
82 data.last_call_started_cycle.store(gpr_get_cycle_counter(),
83 std::memory_order_relaxed);
84 }
85
86 void CallCountingHelper::RecordCallFailed() {
87 per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
88 .calls_failed.fetch_add(1, std::memory_order_relaxed);
89 }
90
91 void CallCountingHelper::RecordCallSucceeded() {
92 per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
93 .calls_succeeded.fetch_add(1, std::memory_order_relaxed);
94 }
95
96 void CallCountingHelper::CollectData(CounterData* out) {
97 for (size_t core = 0; core < num_cores_; ++core) {
98 AtomicCounterData& data = per_cpu_counter_data_storage_[core];
99
100 out->calls_started += data.calls_started.load(std::memory_order_relaxed);
101 out->calls_succeeded +=
102 per_cpu_counter_data_storage_[core].calls_succeeded.load(
103 std::memory_order_relaxed);
104 out->calls_failed += per_cpu_counter_data_storage_[core].calls_failed.load(
105 std::memory_order_relaxed);
106 const gpr_cycle_counter last_call =
107 per_cpu_counter_data_storage_[core].last_call_started_cycle.load(
108 std::memory_order_relaxed);
109 if (last_call > out->last_call_started_cycle) {
110 out->last_call_started_cycle = last_call;
111 }
112 }
113 }
114
115 void CallCountingHelper::PopulateCallCounts(Json::Object* json) {
116 CounterData data;
117 CollectData(&data);
118 if (data.calls_started != 0) {
119 (*json)["callsStarted"] = std::to_string(data.calls_started);
120 gpr_timespec ts = gpr_convert_clock_type(
121 gpr_cycle_counter_to_time(data.last_call_started_cycle),
122 GPR_CLOCK_REALTIME);
123 (*json)["lastCallStartedTimestamp"] = gpr_format_timespec(ts);
124 }
125 if (data.calls_succeeded != 0) {
126 (*json)["callsSucceeded"] = std::to_string(data.calls_succeeded);
127 }
128 if (data.calls_failed) {
129 (*json)["callsFailed"] = std::to_string(data.calls_failed);
130 }
131 }
132
133 //
134 // ChannelNode
135 //
136
137 ChannelNode::ChannelNode(std::string target, size_t channel_tracer_max_nodes,
138 bool is_internal_channel)
139 : BaseNode(is_internal_channel ? EntityType::kInternalChannel
140 : EntityType::kTopLevelChannel,
141 target),
142 target_(std::move(target)),
143 trace_(channel_tracer_max_nodes) {}
144
145 const char* ChannelNode::GetChannelConnectivityStateChangeString(
146 grpc_connectivity_state state) {
147 switch (state) {
148 case GRPC_CHANNEL_IDLE:
149 return "Channel state change to IDLE";
150 case GRPC_CHANNEL_CONNECTING:
151 return "Channel state change to CONNECTING";
152 case GRPC_CHANNEL_READY:
153 return "Channel state change to READY";
154 case GRPC_CHANNEL_TRANSIENT_FAILURE:
155 return "Channel state change to TRANSIENT_FAILURE";
156 case GRPC_CHANNEL_SHUTDOWN:
157 return "Channel state change to SHUTDOWN";
158 }
159 GPR_UNREACHABLE_CODE(return "UNKNOWN");
160 }
161
162 Json ChannelNode::RenderJson() {
163 Json::Object data = {
164 {"target", target_},
165 };
166 // Connectivity state.
167 // If low-order bit is on, then the field is set.
168 int state_field = connectivity_state_.load(std::memory_order_relaxed);
169 if ((state_field & 1) != 0) {
170 grpc_connectivity_state state =
171 static_cast<grpc_connectivity_state>(state_field >> 1);
172 data["state"] = Json::Object{
173 {"state", ConnectivityStateName(state)},
174 };
175 }
176 // Fill in the channel trace if applicable.
177 Json trace_json = trace_.RenderJson();
178 if (trace_json.type() != Json::Type::JSON_NULL) {
179 data["trace"] = std::move(trace_json);
180 }
181 // Ask CallCountingHelper to populate call count data.
182 call_counter_.PopulateCallCounts(&data);
183 // Construct outer object.
184 Json::Object json = {
185 {"ref",
186 Json::Object{
187 {"channelId", std::to_string(uuid())},
188 }},
189 {"data", std::move(data)},
190 };
191 // Template method. Child classes may override this to add their specific
192 // functionality.
193 PopulateChildRefs(&json);
194 return json;
195 }
196
197 void ChannelNode::PopulateChildRefs(Json::Object* json) {
198 MutexLock lock(&child_mu_);
199 if (!child_subchannels_.empty()) {
200 Json::Array array;
201 for (intptr_t subchannel_uuid : child_subchannels_) {
202 array.emplace_back(Json::Object{
203 {"subchannelId", std::to_string(subchannel_uuid)},
204 });
205 }
206 (*json)["subchannelRef"] = std::move(array);
207 }
208 if (!child_channels_.empty()) {
209 Json::Array array;
210 for (intptr_t channel_uuid : child_channels_) {
211 array.emplace_back(Json::Object{
212 {"channelId", std::to_string(channel_uuid)},
213 });
214 }
215 (*json)["channelRef"] = std::move(array);
216 }
217 }
218
219 void ChannelNode::SetConnectivityState(grpc_connectivity_state state) {
220 // Store with low-order bit set to indicate that the field is set.
221 int state_field = (state << 1) + 1;
222 connectivity_state_.store(state_field, std::memory_order_relaxed);
223 }
224
225 void ChannelNode::AddChildChannel(intptr_t child_uuid) {
226 MutexLock lock(&child_mu_);
227 child_channels_.insert(child_uuid);
228 }
229
230 void ChannelNode::RemoveChildChannel(intptr_t child_uuid) {
231 MutexLock lock(&child_mu_);
232 child_channels_.erase(child_uuid);
233 }
234
235 void ChannelNode::AddChildSubchannel(intptr_t child_uuid) {
236 MutexLock lock(&child_mu_);
237 child_subchannels_.insert(child_uuid);
238 }
239
240 void ChannelNode::RemoveChildSubchannel(intptr_t child_uuid) {
241 MutexLock lock(&child_mu_);
242 child_subchannels_.erase(child_uuid);
243 }
244
245 //
246 // ServerNode
247 //
248
249 ServerNode::ServerNode(size_t channel_tracer_max_nodes)
250 : BaseNode(EntityType::kServer, ""), trace_(channel_tracer_max_nodes) {}
251
252 ServerNode::~ServerNode() {}
253
254 void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) {
255 MutexLock lock(&child_mu_);
256 child_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
257 }
258
259 void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
260 MutexLock lock(&child_mu_);
261 child_sockets_.erase(child_uuid);
262 }
263
264 void ServerNode::AddChildListenSocket(RefCountedPtr<ListenSocketNode> node) {
265 MutexLock lock(&child_mu_);
266 child_listen_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
267 }
268
269 void ServerNode::RemoveChildListenSocket(intptr_t child_uuid) {
270 MutexLock lock(&child_mu_);
271 child_listen_sockets_.erase(child_uuid);
272 }
273
274 std::string ServerNode::RenderServerSockets(intptr_t start_socket_id,
275 intptr_t max_results) {
276 GPR_ASSERT(start_socket_id >= 0);
277 GPR_ASSERT(max_results >= 0);
278 // If user does not set max_results, we choose 500.
279 size_t pagination_limit = max_results == 0 ? 500 : max_results;
280 Json::Object object;
281 {
282 MutexLock lock(&child_mu_);
283 size_t sockets_rendered = 0;
284 // Create list of socket refs.
285 Json::Array array;
286 auto it = child_sockets_.lower_bound(start_socket_id);
287 for (; it != child_sockets_.end() && sockets_rendered < pagination_limit;
288 ++it, ++sockets_rendered) {
289 array.emplace_back(Json::Object{
290 {"socketId", std::to_string(it->first)},
291 {"name", it->second->name()},
292 });
293 }
294 object["socketRef"] = std::move(array);
295 if (it == child_sockets_.end()) object["end"] = true;
296 }
297 Json json = std::move(object);
298 return json.Dump();
299 }
300
301 Json ServerNode::RenderJson() {
302 Json::Object data;
303 // Fill in the channel trace if applicable.
304 Json trace_json = trace_.RenderJson();
305 if (trace_json.type() != Json::Type::JSON_NULL) {
306 data["trace"] = std::move(trace_json);
307 }
308 // Ask CallCountingHelper to populate call count data.
309 call_counter_.PopulateCallCounts(&data);
310 // Construct top-level object.
311 Json::Object object = {
312 {"ref",
313 Json::Object{
314 {"serverId", std::to_string(uuid())},
315 }},
316 {"data", std::move(data)},
317 };
318 // Render listen sockets.
319 {
320 MutexLock lock(&child_mu_);
321 if (!child_listen_sockets_.empty()) {
322 Json::Array array;
323 for (const auto& it : child_listen_sockets_) {
324 array.emplace_back(Json::Object{
325 {"socketId", std::to_string(it.first)},
326 {"name", it.second->name()},
327 });
328 }
329 object["listenSocket"] = std::move(array);
330 }
331 }
332 return object;
333 }
334
335 //
336 // SocketNode::Security::Tls
337 //
338
339 Json SocketNode::Security::Tls::RenderJson() {
340 Json::Object data;
341 if (type == NameType::kStandardName) {
342 data["standard_name"] = name;
343 } else if (type == NameType::kOtherName) {
344 data["other_name"] = name;
345 }
346 if (!local_certificate.empty()) {
347 data["local_certificate"] = absl::Base64Escape(local_certificate);
348 }
349 if (!remote_certificate.empty()) {
350 data["remote_certificate"] = absl::Base64Escape(remote_certificate);
351 }
352 return data;
353 }
354
355 //
356 // SocketNode::Security
357 //
358
359 Json SocketNode::Security::RenderJson() {
360 Json::Object data;
361 switch (type) {
362 case ModelType::kUnset:
363 break;
364 case ModelType::kTls:
365 if (tls) {
366 data["tls"] = tls->RenderJson();
367 }
368 break;
369 case ModelType::kOther:
370 if (other) {
371 data["other"] = *other;
372 }
373 break;
374 }
375 return data;
376 }
377
378 namespace {
379
380 void* SecurityArgCopy(void* p) {
381 SocketNode::Security* xds_certificate_provider =
382 static_cast<SocketNode::Security*>(p);
383 return xds_certificate_provider->Ref().release();
384 }
385
386 void SecurityArgDestroy(void* p) {
387 SocketNode::Security* xds_certificate_provider =
388 static_cast<SocketNode::Security*>(p);
389 xds_certificate_provider->Unref();
390 }
391
392 int SecurityArgCmp(void* p, void* q) { return QsortCompare(p, q); }
393
394 const grpc_arg_pointer_vtable kChannelArgVtable = {
395 SecurityArgCopy, SecurityArgDestroy, SecurityArgCmp};
396
397 } // namespace
398
399 grpc_arg SocketNode::Security::MakeChannelArg() const {
400 return grpc_channel_arg_pointer_create(
401 const_cast<char*>(GRPC_ARG_CHANNELZ_SECURITY),
402 const_cast<SocketNode::Security*>(this), &kChannelArgVtable);
403 }
404
405 RefCountedPtr<SocketNode::Security> SocketNode::Security::GetFromChannelArgs(
406 const grpc_channel_args* args) {
407 Security* security = grpc_channel_args_find_pointer<Security>(
408 args, GRPC_ARG_CHANNELZ_SECURITY);
409 return security != nullptr ? security->Ref() : nullptr;
410 }
411
412 //
413 // SocketNode
414 //
415
416 namespace {
417
418 void PopulateSocketAddressJson(Json::Object* json, const char* name,
419 const char* addr_str) {
420 if (addr_str == nullptr) return;
421 absl::StatusOr<URI> uri = URI::Parse(addr_str);
422 if (uri.ok()) {
423 if (uri->scheme() == "ipv4" || uri->scheme() == "ipv6") {
424 auto address = StringToSockaddr(absl::StripPrefix(uri->path(), "/"));
425 if (address.ok()) {
426 std::string packed_host = grpc_sockaddr_get_packed_host(&*address);
427 (*json)[name] = Json::Object{
428 {"tcpip_address",
429 Json::Object{
430 {"port", grpc_sockaddr_get_port(&*address)},
431 {"ip_address", absl::Base64Escape(packed_host)},
432 }},
433 };
434 return;
435 }
436 } else if (uri->scheme() == "unix") {
437 (*json)[name] = Json::Object{
438 {"uds_address",
439 Json::Object{
440 {"filename", uri->path()},
441 }},
442 };
443 return;
444 }
445 }
446 // Unknown address type.
447 (*json)[name] = Json::Object{
448 {"other_address",
449 Json::Object{
450 {"name", addr_str},
451 }},
452 };
453 }
454
455 } // namespace
456
457 SocketNode::SocketNode(std::string local, std::string remote, std::string name,
458 RefCountedPtr<Security> security)
459 : BaseNode(EntityType::kSocket, std::move(name)),
460 local_(std::move(local)),
461 remote_(std::move(remote)),
462 security_(std::move(security)) {}
463
464 void SocketNode::RecordStreamStartedFromLocal() {
465 streams_started_.fetch_add(1, std::memory_order_relaxed);
466 last_local_stream_created_cycle_.store(gpr_get_cycle_counter(),
467 std::memory_order_relaxed);
468 }
469
470 void SocketNode::RecordStreamStartedFromRemote() {
471 streams_started_.fetch_add(1, std::memory_order_relaxed);
472 last_remote_stream_created_cycle_.store(gpr_get_cycle_counter(),
473 std::memory_order_relaxed);
474 }
475
476 void SocketNode::RecordMessagesSent(uint32_t num_sent) {
477 messages_sent_.fetch_add(num_sent, std::memory_order_relaxed);
478 last_message_sent_cycle_.store(gpr_get_cycle_counter(),
479 std::memory_order_relaxed);
480 }
481
482 void SocketNode::RecordMessageReceived() {
483 messages_received_.fetch_add(1, std::memory_order_relaxed);
484 last_message_received_cycle_.store(gpr_get_cycle_counter(),
485 std::memory_order_relaxed);
486 }
487
488 Json SocketNode::RenderJson() {
489 // Create and fill the data child.
490 Json::Object data;
491 gpr_timespec ts;
492 int64_t streams_started = streams_started_.load(std::memory_order_relaxed);
493 if (streams_started != 0) {
494 data["streamsStarted"] = std::to_string(streams_started);
495 gpr_cycle_counter last_local_stream_created_cycle =
496 last_local_stream_created_cycle_.load(std::memory_order_relaxed);
497 if (last_local_stream_created_cycle != 0) {
498 ts = gpr_convert_clock_type(
499 gpr_cycle_counter_to_time(last_local_stream_created_cycle),
500 GPR_CLOCK_REALTIME);
501 data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
502 }
503 gpr_cycle_counter last_remote_stream_created_cycle =
504 last_remote_stream_created_cycle_.load(std::memory_order_relaxed);
505 if (last_remote_stream_created_cycle != 0) {
506 ts = gpr_convert_clock_type(
507 gpr_cycle_counter_to_time(last_remote_stream_created_cycle),
508 GPR_CLOCK_REALTIME);
509 data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
510 }
511 }
512 int64_t streams_succeeded =
513 streams_succeeded_.load(std::memory_order_relaxed);
514 if (streams_succeeded != 0) {
515 data["streamsSucceeded"] = std::to_string(streams_succeeded);
516 }
517 int64_t streams_failed = streams_failed_.load(std::memory_order_relaxed);
518 if (streams_failed != 0) {
519 data["streamsFailed"] = std::to_string(streams_failed);
520 }
521 int64_t messages_sent = messages_sent_.load(std::memory_order_relaxed);
522 if (messages_sent != 0) {
523 data["messagesSent"] = std::to_string(messages_sent);
524 ts = gpr_convert_clock_type(
525 gpr_cycle_counter_to_time(
526 last_message_sent_cycle_.load(std::memory_order_relaxed)),
527 GPR_CLOCK_REALTIME);
528 data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
529 }
530 int64_t messages_received =
531 messages_received_.load(std::memory_order_relaxed);
532 if (messages_received != 0) {
533 data["messagesReceived"] = std::to_string(messages_received);
534 ts = gpr_convert_clock_type(
535 gpr_cycle_counter_to_time(
536 last_message_received_cycle_.load(std::memory_order_relaxed)),
537 GPR_CLOCK_REALTIME);
538 data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
539 }
540 int64_t keepalives_sent = keepalives_sent_.load(std::memory_order_relaxed);
541 if (keepalives_sent != 0) {
542 data["keepAlivesSent"] = std::to_string(keepalives_sent);
543 }
544 // Create and fill the parent object.
545 Json::Object object = {
546 {"ref",
547 Json::Object{
548 {"socketId", std::to_string(uuid())},
549 {"name", name()},
550 }},
551 {"data", std::move(data)},
552 };
553 if (security_ != nullptr &&
554 security_->type != SocketNode::Security::ModelType::kUnset) {
555 object["security"] = security_->RenderJson();
556 }
557 PopulateSocketAddressJson(&object, "remote", remote_.c_str());
558 PopulateSocketAddressJson(&object, "local", local_.c_str());
559 return object;
560 }
561
562 //
563 // ListenSocketNode
564 //
565
566 ListenSocketNode::ListenSocketNode(std::string local_addr, std::string name)
567 : BaseNode(EntityType::kSocket, std::move(name)),
568 local_addr_(std::move(local_addr)) {}
569
570 Json ListenSocketNode::RenderJson() {
571 Json::Object object = {
572 {"ref",
573 Json::Object{
574 {"socketId", std::to_string(uuid())},
575 {"name", name()},
576 }},
577 };
578 PopulateSocketAddressJson(&object, "local", local_addr_.c_str());
579 return object;
580 }
581
582 } // namespace channelz
583 } // namespace grpc_core