1 //
2 // Copyright 2022 gRPC authors.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include <grpc/support/port_platform.h>
18 
19 #include "src/core/ext/xds/xds_health_status.h"
20 
21 #include "absl/strings/str_cat.h"
22 #include "envoy/config/core/v3/health_check.upb.h"
23 
24 #include "src/core/lib/gpr/useful.h"
25 
26 namespace grpc_core {
27 
FromUpb(uint32_t status)28 absl::optional<XdsHealthStatus> XdsHealthStatus::FromUpb(uint32_t status) {
29   switch (status) {
30     case envoy_config_core_v3_UNKNOWN:
31       return XdsHealthStatus(kUnknown);
32     case envoy_config_core_v3_HEALTHY:
33       return XdsHealthStatus(kHealthy);
34     case envoy_config_core_v3_DRAINING:
35       return XdsHealthStatus(kDraining);
36     default:
37       return absl::nullopt;
38   }
39 }
40 
FromString(absl::string_view status)41 absl::optional<XdsHealthStatus> XdsHealthStatus::FromString(
42     absl::string_view status) {
43   if (status == "UNKNOWN") return XdsHealthStatus(kUnknown);
44   if (status == "HEALTHY") return XdsHealthStatus(kHealthy);
45   if (status == "DRAINING") return XdsHealthStatus(kDraining);
46   return absl::nullopt;
47 }
48 
ToString() const49 const char* XdsHealthStatus::ToString() const {
50   switch (status_) {
51     case kUnknown:
52       return "UNKNOWN";
53     case kHealthy:
54       return "HEALTHY";
55     case kDraining:
56       return "DRAINING";
57     default:
58       return "<INVALID>";
59   }
60 }
61 
operator <(const XdsHealthStatus & hs1,const XdsHealthStatus & hs2)62 bool operator<(const XdsHealthStatus& hs1, const XdsHealthStatus& hs2) {
63   return hs1.status() < hs2.status();
64 }
65 
66 const char* XdsEndpointHealthStatusAttribute::kKey =
67     "xds_endpoint_health_status";
68 
Cmp(const AttributeInterface * other) const69 int XdsEndpointHealthStatusAttribute::Cmp(
70     const AttributeInterface* other) const {
71   const auto* other_attr =
72       static_cast<const XdsEndpointHealthStatusAttribute*>(other);
73   return QsortCompare(status_, other_attr->status_);
74 }
75 
ToString() const76 std::string XdsEndpointHealthStatusAttribute::ToString() const {
77   return absl::StrCat("{status_=", status_.ToString(), "}");
78 }
79 
80 }  // namespace grpc_core
81