Debian Codegraph @

src/core/lib/gprpp/status_helper.cc

raw
1 //
2 //
3 // Copyright 2021 the 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/gprpp/status_helper.h"
22
23 #include <string.h>
24
25 #include <algorithm>
26 #include <utility>
27
28 #include "absl/strings/cord.h"
29 #include "absl/strings/escaping.h"
30 #include "absl/strings/match.h"
31 #include "absl/strings/numbers.h"
32 #include "absl/strings/str_cat.h"
33 #include "absl/strings/str_join.h"
34 #include "absl/time/clock.h"
35 #include "google/protobuf/any.upb.h"
36 #include "google/rpc/status.upb.h"
37 #include "upb/arena.h"
38 #include "upb/upb.h"
39 #include "upb/upb.hpp"
40
41 #include <grpc/support/log.h>
42
43 #include "src/core/lib/slice/percent_encoding.h"
44 #include "src/core/lib/slice/slice.h"
45
46 namespace grpc_core {
47
48 namespace {
49
50 #define TYPE_URL_PREFIX "type.googleapis.com/grpc.status."
51 #define TYPE_INT_TAG "int."
52 #define TYPE_STR_TAG "str."
53 #define TYPE_TIME_TAG "time."
54 #define TYPE_CHILDREN_TAG "children"
55 #define TYPE_URL(name) (TYPE_URL_PREFIX name)
56 const absl::string_view kTypeUrlPrefix = TYPE_URL_PREFIX;
57 const absl::string_view kTypeIntTag = TYPE_INT_TAG;
58 const absl::string_view kTypeStrTag = TYPE_STR_TAG;
59 const absl::string_view kTypeTimeTag = TYPE_TIME_TAG;
60 const absl::string_view kTypeChildrenTag = TYPE_CHILDREN_TAG;
61 const absl::string_view kChildrenPropertyUrl = TYPE_URL(TYPE_CHILDREN_TAG);
62
63 const char* GetStatusIntPropertyUrl(StatusIntProperty key) {
64 switch (key) {
65 case StatusIntProperty::kErrorNo:
66 return TYPE_URL(TYPE_INT_TAG "errno");
67 case StatusIntProperty::kFileLine:
68 return TYPE_URL(TYPE_INT_TAG "file_line");
69 case StatusIntProperty::kStreamId:
70 return TYPE_URL(TYPE_INT_TAG "stream_id");
71 case StatusIntProperty::kRpcStatus:
72 return TYPE_URL(TYPE_INT_TAG "grpc_status");
73 case StatusIntProperty::kOffset:
74 return TYPE_URL(TYPE_INT_TAG "offset");
75 case StatusIntProperty::kIndex:
76 return TYPE_URL(TYPE_INT_TAG "index");
77 case StatusIntProperty::kSize:
78 return TYPE_URL(TYPE_INT_TAG "size");
79 case StatusIntProperty::kHttp2Error:
80 return TYPE_URL(TYPE_INT_TAG "http2_error");
81 case StatusIntProperty::kTsiCode:
82 return TYPE_URL(TYPE_INT_TAG "tsi_code");
83 case StatusIntProperty::kWsaError:
84 return TYPE_URL(TYPE_INT_TAG "wsa_error");
85 case StatusIntProperty::kFd:
86 return TYPE_URL(TYPE_INT_TAG "fd");
87 case StatusIntProperty::kHttpStatus:
88 return TYPE_URL(TYPE_INT_TAG "http_status");
89 case StatusIntProperty::kOccurredDuringWrite:
90 return TYPE_URL(TYPE_INT_TAG "occurred_during_write");
91 case StatusIntProperty::ChannelConnectivityState:
92 return TYPE_URL(TYPE_INT_TAG "channel_connectivity_state");
93 case StatusIntProperty::kLbPolicyDrop:
94 return TYPE_URL(TYPE_INT_TAG "lb_policy_drop");
95 }
96 GPR_UNREACHABLE_CODE(return "unknown");
97 }
98
99 const char* GetStatusStrPropertyUrl(StatusStrProperty key) {
100 switch (key) {
101 case StatusStrProperty::kDescription:
102 return TYPE_URL(TYPE_STR_TAG "description");
103 case StatusStrProperty::kFile:
104 return TYPE_URL(TYPE_STR_TAG "file");
105 case StatusStrProperty::kOsError:
106 return TYPE_URL(TYPE_STR_TAG "os_error");
107 case StatusStrProperty::kSyscall:
108 return TYPE_URL(TYPE_STR_TAG "syscall");
109 case StatusStrProperty::kTargetAddress:
110 return TYPE_URL(TYPE_STR_TAG "target_address");
111 case StatusStrProperty::kGrpcMessage:
112 return TYPE_URL(TYPE_STR_TAG "grpc_message");
113 case StatusStrProperty::kRawBytes:
114 return TYPE_URL(TYPE_STR_TAG "raw_bytes");
115 case StatusStrProperty::kTsiError:
116 return TYPE_URL(TYPE_STR_TAG "tsi_error");
117 case StatusStrProperty::kFilename:
118 return TYPE_URL(TYPE_STR_TAG "filename");
119 case StatusStrProperty::kKey:
120 return TYPE_URL(TYPE_STR_TAG "key");
121 case StatusStrProperty::kValue:
122 return TYPE_URL(TYPE_STR_TAG "value");
123 }
124 GPR_UNREACHABLE_CODE(return "unknown");
125 }
126
127 const char* GetStatusTimePropertyUrl(StatusTimeProperty key) {
128 switch (key) {
129 case StatusTimeProperty::kCreated:
130 return TYPE_URL(TYPE_TIME_TAG "created_time");
131 }
132 GPR_UNREACHABLE_CODE(return "unknown");
133 }
134
135 void EncodeUInt32ToBytes(uint32_t v, char* buf) {
136 buf[0] = v & 0xFF;
137 buf[1] = (v >> 8) & 0xFF;
138 buf[2] = (v >> 16) & 0xFF;
139 buf[3] = (v >> 24) & 0xFF;
140 }
141
142 uint32_t DecodeUInt32FromBytes(const char* buf) {
143 const unsigned char* ubuf = reinterpret_cast<const unsigned char*>(buf);
144 return ubuf[0] | (uint32_t(ubuf[1]) << 8) | (uint32_t(ubuf[2]) << 16) |
145 (uint32_t(ubuf[3]) << 24);
146 }
147
148 std::vector<absl::Status> ParseChildren(absl::Cord children) {
149 std::vector<absl::Status> result;
150 upb::Arena arena;
151 // Cord is flattened to iterate the buffer easily at the cost of memory copy.
152 // TODO(veblush): Optimize this once CordReader is introduced.
153 absl::string_view buf = children.Flatten();
154 size_t cur = 0;
155 while (buf.size() - cur >= sizeof(uint32_t)) {
156 size_t msg_size = DecodeUInt32FromBytes(buf.data() + cur);
157 cur += sizeof(uint32_t);
158 GPR_ASSERT(buf.size() - cur >= msg_size);
159 google_rpc_Status* msg =
160 google_rpc_Status_parse(buf.data() + cur, msg_size, arena.ptr());
161 cur += msg_size;
162 result.push_back(internal::StatusFromProto(msg));
163 }
164 return result;
165 }
166
167 } // namespace
168
169 absl::Status StatusCreate(absl::StatusCode code, absl::string_view msg,
170 const DebugLocation& location,
171 std::vector<absl::Status> children) {
172 absl::Status s(code, msg);
173 if (location.file() != nullptr) {
174 StatusSetStr(&s, StatusStrProperty::kFile, location.file());
175 }
176 if (location.line() != -1) {
177 StatusSetInt(&s, StatusIntProperty::kFileLine, location.line());
178 }
179 StatusSetTime(&s, StatusTimeProperty::kCreated, absl::Now());
180 for (const absl::Status& child : children) {
181 if (!child.ok()) {
182 StatusAddChild(&s, child);
183 }
184 }
185 return s;
186 }
187
188 void StatusSetInt(absl::Status* status, StatusIntProperty key, intptr_t value) {
189 status->SetPayload(GetStatusIntPropertyUrl(key),
190 absl::Cord(std::to_string(value)));
191 }
192
193 absl::optional<intptr_t> StatusGetInt(const absl::Status& status,
194 StatusIntProperty key) {
195 absl::optional<absl::Cord> p =
196 status.GetPayload(GetStatusIntPropertyUrl(key));
197 if (p.has_value()) {
198 absl::optional<absl::string_view> sv = p->TryFlat();
199 intptr_t value;
200 if (sv.has_value()) {
201 if (absl::SimpleAtoi(*sv, &value)) {
202 return value;
203 }
204 } else {
205 if (absl::SimpleAtoi(std::string(*p), &value)) {
206 return value;
207 }
208 }
209 }
210 return {};
211 }
212
213 void StatusSetStr(absl::Status* status, StatusStrProperty key,
214 absl::string_view value) {
215 status->SetPayload(GetStatusStrPropertyUrl(key), absl::Cord(value));
216 }
217
218 absl::optional<std::string> StatusGetStr(const absl::Status& status,
219 StatusStrProperty key) {
220 absl::optional<absl::Cord> p =
221 status.GetPayload(GetStatusStrPropertyUrl(key));
222 if (p.has_value()) {
223 return std::string(*p);
224 }
225 return {};
226 }
227
228 void StatusSetTime(absl::Status* status, StatusTimeProperty key,
229 absl::Time time) {
230 std::string time_str =
231 absl::FormatTime(absl::RFC3339_full, time, absl::UTCTimeZone());
232 status->SetPayload(GetStatusTimePropertyUrl(key),
233 absl::Cord(std::move(time_str)));
234 }
235
236 absl::optional<absl::Time> StatusGetTime(const absl::Status& status,
237 StatusTimeProperty key) {
238 absl::optional<absl::Cord> p =
239 status.GetPayload(GetStatusTimePropertyUrl(key));
240 if (p.has_value()) {
241 absl::optional<absl::string_view> sv = p->TryFlat();
242 absl::Time time;
243 if (sv.has_value()) {
244 if (absl::ParseTime(absl::RFC3339_full, sv.value(), &time, nullptr)) {
245 return time;
246 }
247 } else {
248 std::string s = std::string(*p);
249 if (absl::ParseTime(absl::RFC3339_full, s, &time, nullptr)) {
250 return time;
251 }
252 }
253 }
254 return {};
255 }
256
257 void StatusAddChild(absl::Status* status, absl::Status child) {
258 upb::Arena arena;
259 // Serialize msg to buf
260 google_rpc_Status* msg = internal::StatusToProto(child, arena.ptr());
261 size_t buf_len = 0;
262 char* buf = google_rpc_Status_serialize(msg, arena.ptr(), &buf_len);
263 // Append (msg-length and msg) to children payload
264 absl::optional<absl::Cord> old_children =
265 status->GetPayload(kChildrenPropertyUrl);
266 absl::Cord children;
267 if (old_children.has_value()) {
268 children = *old_children;
269 }
270 char head_buf[sizeof(uint32_t)];
271 EncodeUInt32ToBytes(buf_len, head_buf);
272 children.Append(absl::string_view(head_buf, sizeof(uint32_t)));
273 children.Append(absl::string_view(buf, buf_len));
274 status->SetPayload(kChildrenPropertyUrl, std::move(children));
275 }
276
277 std::vector<absl::Status> StatusGetChildren(absl::Status status) {
278 absl::optional<absl::Cord> children = status.GetPayload(kChildrenPropertyUrl);
279 return children.has_value() ? ParseChildren(*children)
280 : std::vector<absl::Status>();
281 }
282
283 std::string StatusToString(const absl::Status& status) {
284 if (status.ok()) {
285 return "OK";
286 }
287 std::string head;
288 absl::StrAppend(&head, absl::StatusCodeToString(status.code()));
289 if (!status.message().empty()) {
290 absl::StrAppend(&head, ":", status.message());
291 }
292 std::vector<std::string> kvs;
293 absl::optional<absl::Cord> children;
294 status.ForEachPayload([&](absl::string_view type_url,
295 const absl::Cord& payload) {
296 if (absl::StartsWith(type_url, kTypeUrlPrefix)) {
297 type_url.remove_prefix(kTypeUrlPrefix.size());
298 if (type_url == kTypeChildrenTag) {
299 children = payload;
300 return;
301 }
302 absl::string_view payload_view;
303 std::string payload_storage;
304 if (payload.TryFlat().has_value()) {
305 payload_view = payload.TryFlat().value();
306 } else {
307 payload_storage = std::string(payload);
308 payload_view = payload_storage;
309 }
310 if (absl::StartsWith(type_url, kTypeIntTag)) {
311 type_url.remove_prefix(kTypeIntTag.size());
312 kvs.push_back(absl::StrCat(type_url, ":", payload_view));
313 } else if (absl::StartsWith(type_url, kTypeStrTag)) {
314 type_url.remove_prefix(kTypeStrTag.size());
315 kvs.push_back(absl::StrCat(type_url, ":\"",
316 absl::CHexEscape(payload_view), "\""));
317 } else if (absl::StartsWith(type_url, kTypeTimeTag)) {
318 type_url.remove_prefix(kTypeTimeTag.size());
319 absl::Time t;
320 if (absl::ParseTime(absl::RFC3339_full, payload_view, &t, nullptr)) {
321 kvs.push_back(
322 absl::StrCat(type_url, ":\"", absl::FormatTime(t), "\""));
323 } else {
324 kvs.push_back(absl::StrCat(type_url, ":\"",
325 absl::CHexEscape(payload_view), "\""));
326 }
327 } else {
328 kvs.push_back(absl::StrCat(type_url, ":\"",
329 absl::CHexEscape(payload_view), "\""));
330 }
331 } else {
332 absl::optional<absl::string_view> payload_view = payload.TryFlat();
333 std::string payload_str = absl::CHexEscape(
334 payload_view.has_value() ? *payload_view : std::string(payload));
335 kvs.push_back(absl::StrCat(type_url, ":\"", payload_str, "\""));
336 }
337 });
338 if (children.has_value()) {
339 std::vector<absl::Status> children_status = ParseChildren(*children);
340 std::vector<std::string> children_text;
341 children_text.reserve(children_status.size());
342 for (const absl::Status& child_status : children_status) {
343 children_text.push_back(StatusToString(child_status));
344 }
345 kvs.push_back(
346 absl::StrCat("children:[", absl::StrJoin(children_text, ", "), "]"));
347 }
348 return kvs.empty() ? head
349 : absl::StrCat(head, " {", absl::StrJoin(kvs, ", "), "}");
350 }
351
352 namespace internal {
353
354 google_rpc_Status* StatusToProto(const absl::Status& status, upb_Arena* arena) {
355 google_rpc_Status* msg = google_rpc_Status_new(arena);
356 google_rpc_Status_set_code(msg, int32_t(status.code()));
357 // Protobuf string field requires to be utf-8 encoding but C++ string doesn't
358 // this requirement so it can be a non utf-8 string. So it should be converted
359 // to a percent-encoded string to keep it as a utf-8 string.
360 Slice message_percent_slice =
361 PercentEncodeSlice(Slice::FromExternalString(status.message()),
362 PercentEncodingType::Compatible);
363 char* message_percent = reinterpret_cast<char*>(
364 upb_Arena_Malloc(arena, message_percent_slice.length()));
365 if (message_percent_slice.length() > 0) {
366 memcpy(message_percent, message_percent_slice.data(),
367 message_percent_slice.length());
368 }
369 google_rpc_Status_set_message(
370 msg, upb_StringView_FromDataAndSize(message_percent,
371 message_percent_slice.length()));
372 status.ForEachPayload([&](absl::string_view type_url,
373 const absl::Cord& payload) {
374 google_protobuf_Any* any = google_rpc_Status_add_details(msg, arena);
375 char* type_url_buf =
376 reinterpret_cast<char*>(upb_Arena_Malloc(arena, type_url.size()));
377 memcpy(type_url_buf, type_url.data(), type_url.size());
378 google_protobuf_Any_set_type_url(
379 any, upb_StringView_FromDataAndSize(type_url_buf, type_url.size()));
380 absl::optional<absl::string_view> v_view = payload.TryFlat();
381 if (v_view.has_value()) {
382 google_protobuf_Any_set_value(
383 any, upb_StringView_FromDataAndSize(v_view->data(), v_view->size()));
384 } else {
385 char* buf =
386 reinterpret_cast<char*>(upb_Arena_Malloc(arena, payload.size()));
387 char* cur = buf;
388 for (absl::string_view chunk : payload.Chunks()) {
389 memcpy(cur, chunk.data(), chunk.size());
390 cur += chunk.size();
391 }
392 google_protobuf_Any_set_value(
393 any, upb_StringView_FromDataAndSize(buf, payload.size()));
394 }
395 });
396 return msg;
397 }
398
399 absl::Status StatusFromProto(google_rpc_Status* msg) {
400 int32_t code = google_rpc_Status_code(msg);
401 upb_StringView message_percent_upb = google_rpc_Status_message(msg);
402 Slice message_percent_slice = Slice::FromExternalString(
403 absl::string_view(message_percent_upb.data, message_percent_upb.size));
404 Slice message_slice =
405 PermissivePercentDecodeSlice(std::move(message_percent_slice));
406 absl::Status status(
407 static_cast<absl::StatusCode>(code),
408 absl::string_view(reinterpret_cast<const char*>(message_slice.data()),
409 message_slice.size()));
410 size_t detail_len;
411 const google_protobuf_Any* const* details =
412 google_rpc_Status_details(msg, &detail_len);
413 for (size_t i = 0; i < detail_len; i++) {
414 upb_StringView type_url = google_protobuf_Any_type_url(details[i]);
415 upb_StringView value = google_protobuf_Any_value(details[i]);
416 status.SetPayload(absl::string_view(type_url.data, type_url.size),
417 absl::Cord(absl::string_view(value.data, value.size)));
418 }
419 return status;
420 }
421
422 uintptr_t StatusAllocHeapPtr(absl::Status s) {
423 if (s.ok()) return 0;
424 absl::Status* ptr = new absl::Status(s);
425 return reinterpret_cast<uintptr_t>(ptr);
426 }
427
428 void StatusFreeHeapPtr(uintptr_t ptr) {
429 absl::Status* s = reinterpret_cast<absl::Status*>(ptr);
430 delete s;
431 }
432
433 absl::Status StatusGetFromHeapPtr(uintptr_t ptr) {
434 if (ptr == 0) {
435 return absl::OkStatus();
436 } else {
437 return *reinterpret_cast<absl::Status*>(ptr);
438 }
439 }
440
441 absl::Status StatusMoveFromHeapPtr(uintptr_t ptr) {
442 if (ptr == 0) {
443 return absl::OkStatus();
444 } else {
445 absl::Status* s = reinterpret_cast<absl::Status*>(ptr);
446 absl::Status ret = std::move(*s);
447 delete s;
448 return ret;
449 }
450 }
451
452 } // namespace internal
453
454 } // namespace grpc_core