3 * Copyright 2017 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <grpc/impl/codegen/port_platform.h>
21 #include "src/core/lib/channel/channelz.h"
23 #include <grpc/grpc.h>
24 #include <grpc/support/alloc.h>
25 #include <grpc/support/log.h>
26 #include <grpc/support/string_util.h>
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"
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};
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);
78 intptr_t GetParentUuidFromArgs(const grpc_channel_args& args) {
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);
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);
95 BaseNode::~BaseNode() { ChannelzRegistry::Unregister(uuid_); }
97 std::string BaseNode::RenderJsonString() {
98 Json json = RenderJson();
103 // CallCountingHelper
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();
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);
122 void CallCountingHelper::RecordCallFailed() {
123 per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
124 .calls_failed.FetchAdd(1, MemoryOrder::RELAXED);
127 void CallCountingHelper::RecordCallSucceeded() {
128 per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]
129 .calls_succeeded.FetchAdd(1, MemoryOrder::RELAXED);
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];
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;
151 void CallCountingHelper::PopulateCallCounts(Json::Object* object) {
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),
159 (*object)["lastCallStartedTimestamp"] = gpr_format_timespec(ts);
161 if (data.calls_succeeded != 0) {
162 (*object)["callsSucceeded"] = std::to_string(data.calls_succeeded);
164 if (data.calls_failed) {
165 (*object)["callsFailed"] = std::to_string(data.calls_failed);
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,
178 target_(std::move(target)),
179 trace_(channel_tracer_max_nodes),
180 parent_uuid_(parent_uuid) {}
182 const char* ChannelNode::GetChannelConnectivityStateChangeString(
183 grpc_connectivity_state 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";
196 GPR_UNREACHABLE_CODE(return "UNKNOWN");
199 Json ChannelNode::RenderJson() {
200 Json::Object data = {
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)},
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);
218 // Ask CallCountingHelper to populate call count data.
219 call_counter_.PopulateCallCounts(&data);
220 // Construct outer object.
221 Json::Object json = {
224 {"channelId", std::to_string(uuid())},
226 {"data", std::move(data)},
228 // Template method. Child classes may override this to add their specific
230 PopulateChildRefs(&json);
234 void ChannelNode::PopulateChildRefs(Json::Object* json) {
235 MutexLock lock(&child_mu_);
236 if (!child_subchannels_.empty()) {
238 for (const auto& p : child_subchannels_) {
239 array.emplace_back(Json::Object{
240 {"subchannelId", std::to_string(p.first)},
243 (*json)["subchannelRef"] = std::move(array);
245 if (!child_channels_.empty()) {
247 for (const auto& p : child_channels_) {
248 array.emplace_back(Json::Object{
249 {"channelId", std::to_string(p.first)},
252 (*json)["channelRef"] = std::move(array);
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);
262 void ChannelNode::AddChildChannel(intptr_t child_uuid) {
263 MutexLock lock(&child_mu_);
264 child_channels_.insert(std::make_pair(child_uuid, true));
267 void ChannelNode::RemoveChildChannel(intptr_t child_uuid) {
268 MutexLock lock(&child_mu_);
269 child_channels_.erase(child_uuid);
272 void ChannelNode::AddChildSubchannel(intptr_t child_uuid) {
273 MutexLock lock(&child_mu_);
274 child_subchannels_.insert(std::make_pair(child_uuid, true));
277 void ChannelNode::RemoveChildSubchannel(intptr_t child_uuid) {
278 MutexLock lock(&child_mu_);
279 child_subchannels_.erase(child_uuid);
286 ServerNode::ServerNode(grpc_server* /*server*/, size_t channel_tracer_max_nodes)
287 : BaseNode(EntityType::kServer, ""), trace_(channel_tracer_max_nodes) {}
289 ServerNode::~ServerNode() {}
291 void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) {
292 MutexLock lock(&child_mu_);
293 child_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
296 void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
297 MutexLock lock(&child_mu_);
298 child_sockets_.erase(child_uuid);
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)));
306 void ServerNode::RemoveChildListenSocket(intptr_t child_uuid) {
307 MutexLock lock(&child_mu_);
308 child_listen_sockets_.erase(child_uuid);
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;
317 MutexLock lock(&child_mu_);
318 size_t sockets_rendered = 0;
319 if (!child_sockets_.empty()) {
320 // Create list of socket refs.
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()},
331 object["socketRef"] = std::move(array);
333 if (sockets_rendered == child_sockets_.size()) object["end"] = true;
335 Json json = std::move(object);
339 Json ServerNode::RenderJson() {
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);
346 // Ask CallCountingHelper to populate call count data.
347 call_counter_.PopulateCallCounts(&data);
348 // Construct top-level object.
349 Json::Object object = {
352 {"serverId", std::to_string(uuid())},
354 {"data", std::move(data)},
356 // Render listen sockets.
358 MutexLock lock(&child_mu_);
359 if (!child_listen_sockets_.empty()) {
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()},
367 object["listenSocket"] = std::move(array);
379 void PopulateSocketAddressJson(Json::Object* json, const char* name,
380 const char* addr_str) {
381 if (addr_str == nullptr) return;
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;
390 GPR_ASSERT(SplitHostPort(host_port, &host, &port));
393 port_num = atoi(port.data());
395 char* b64_host = grpc_base64_encode(host.data(), host.size(), false, false);
396 data["tcpip_address"] = Json::Object{
398 {"ip_address", b64_host},
401 } else if (uri != nullptr && strcmp(uri->scheme, "unix") == 0) {
402 data["uds_address"] = Json::Object{
403 {"filename", uri->path},
406 data["other_address"] = Json::Object{
410 grpc_uri_destroy(uri);
411 (*json)[name] = std::move(data);
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)) {}
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);
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);
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);
438 void SocketNode::RecordMessageReceived() {
439 messages_received_.FetchAdd(1, MemoryOrder::RELAXED);
440 last_message_received_cycle_.Store(gpr_get_cycle_counter(),
441 MemoryOrder::RELAXED);
444 Json SocketNode::RenderJson() {
445 // Create and fill the data child.
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),
457 data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
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),
465 data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
468 int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED);
469 if (streams_succeeded != 0) {
470 data["streamsSucceeded"] = std::to_string(streams_succeeded);
472 int64_t streams_failed = streams_failed_.Load(MemoryOrder::RELAXED);
473 if (streams_failed != 0) {
474 data["streamsFailed"] = std::to_string(streams_failed);
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)),
483 data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
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)),
492 data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
494 int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED);
495 if (keepalives_sent != 0) {
496 data["keepAlivesSent"] = std::to_string(keepalives_sent);
498 // Create and fill the parent object.
499 Json::Object object = {
502 {"socketId", std::to_string(uuid())},
505 {"data", std::move(data)},
507 PopulateSocketAddressJson(&object, "remote", remote_.c_str());
508 PopulateSocketAddressJson(&object, "local", local_.c_str());
516 ListenSocketNode::ListenSocketNode(std::string local_addr, std::string name)
517 : BaseNode(EntityType::kSocket, std::move(name)),
518 local_addr_(std::move(local_addr)) {}
520 Json ListenSocketNode::RenderJson() {
521 Json::Object object = {
524 {"socketId", std::to_string(uuid())},
528 PopulateSocketAddressJson(&object, "local", local_addr_.c_str());
532 } // namespace channelz
533 } // namespace grpc_core