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(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 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;
319 MutexLock lock(&child_mu_);
320 size_t sockets_rendered = 0;
321 // Create list of socket refs.
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()},
331 object["socketRef"] = std::move(array);
332 if (it == child_sockets_.end()) object["end"] = true;
334 Json json = std::move(object);
338 Json ServerNode::RenderJson() {
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);
345 // Ask CallCountingHelper to populate call count data.
346 call_counter_.PopulateCallCounts(&data);
347 // Construct top-level object.
348 Json::Object object = {
351 {"serverId", std::to_string(uuid())},
353 {"data", std::move(data)},
355 // Render listen sockets.
357 MutexLock lock(&child_mu_);
358 if (!child_listen_sockets_.empty()) {
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()},
366 object["listenSocket"] = std::move(array);
378 void PopulateSocketAddressJson(Json::Object* json, const char* name,
379 const char* addr_str) {
380 if (addr_str == nullptr) return;
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;
389 GPR_ASSERT(SplitHostPort(host_port, &host, &port));
392 port_num = atoi(port.data());
394 char* b64_host = grpc_base64_encode(host.data(), host.size(), false, false);
395 data["tcpip_address"] = Json::Object{
397 {"ip_address", b64_host},
400 } else if (uri != nullptr && strcmp(uri->scheme, "unix") == 0) {
401 data["uds_address"] = Json::Object{
402 {"filename", uri->path},
405 data["other_address"] = Json::Object{
409 grpc_uri_destroy(uri);
410 (*json)[name] = std::move(data);
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)) {}
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);
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);
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);
437 void SocketNode::RecordMessageReceived() {
438 messages_received_.FetchAdd(1, MemoryOrder::RELAXED);
439 last_message_received_cycle_.Store(gpr_get_cycle_counter(),
440 MemoryOrder::RELAXED);
443 Json SocketNode::RenderJson() {
444 // Create and fill the data child.
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),
456 data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
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),
464 data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
467 int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED);
468 if (streams_succeeded != 0) {
469 data["streamsSucceeded"] = std::to_string(streams_succeeded);
471 int64_t streams_failed = streams_failed_.Load(MemoryOrder::RELAXED);
472 if (streams_failed != 0) {
473 data["streamsFailed"] = std::to_string(streams_failed);
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)),
482 data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
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)),
491 data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
493 int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED);
494 if (keepalives_sent != 0) {
495 data["keepAlivesSent"] = std::to_string(keepalives_sent);
497 // Create and fill the parent object.
498 Json::Object object = {
501 {"socketId", std::to_string(uuid())},
504 {"data", std::move(data)},
506 PopulateSocketAddressJson(&object, "remote", remote_.c_str());
507 PopulateSocketAddressJson(&object, "local", local_.c_str());
515 ListenSocketNode::ListenSocketNode(std::string local_addr, std::string name)
516 : BaseNode(EntityType::kSocket, std::move(name)),
517 local_addr_(std::move(local_addr)) {}
519 Json ListenSocketNode::RenderJson() {
520 Json::Object object = {
523 {"socketId", std::to_string(uuid())},
527 PopulateSocketAddressJson(&object, "local", local_addr_.c_str());
531 } // namespace channelz
532 } // namespace grpc_core