1 // 2 // Copyright 2023 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 #ifndef GRPC_SRC_CORE_EXT_GCP_METADATA_QUERY_H 18 #define GRPC_SRC_CORE_EXT_GCP_METADATA_QUERY_H 19 20 #include <grpc/support/port_platform.h> 21 22 #include <string> 23 24 #include "absl/functional/any_invocable.h" 25 #include "absl/status/statusor.h" 26 27 #include "src/core/lib/gprpp/orphanable.h" 28 #include "src/core/lib/gprpp/time.h" 29 #include "src/core/lib/http/httpcli.h" 30 #include "src/core/lib/http/parser.h" 31 #include "src/core/lib/iomgr/closure.h" 32 #include "src/core/lib/iomgr/error.h" 33 #include "src/core/lib/iomgr/polling_entity.h" 34 35 namespace grpc_core { 36 37 // Fetches the value of an attribute from the MetadataServer on a GCP 38 // environment. 39 class MetadataQuery : public InternallyRefCounted<MetadataQuery> { 40 public: 41 static constexpr const char kZoneAttribute[] = 42 "/computeMetadata/v1/instance/zone"; 43 static constexpr const char kClusterNameAttribute[] = 44 "/computeMetadata/v1/instance/attributes/cluster-name"; 45 static constexpr const char kRegionAttribute[] = 46 "/computeMetadata/v1/instance/region"; 47 static constexpr const char kInstanceIdAttribute[] = 48 "/computeMetadata/v1/instance/id"; 49 static constexpr const char kIPv6Attribute[] = 50 "/computeMetadata/v1/instance/network-interfaces/0/ipv6s"; 51 52 MetadataQuery( 53 std::string attribute, grpc_polling_entity* pollent, 54 absl::AnyInvocable<void(std::string /* attribute */, 55 absl::StatusOr<std::string> /* result */)> 56 callback, 57 Duration timeout); 58 59 // Alternative ctor allows overriding the metadata server address, mainly 60 // to inject fakes in tests 61 MetadataQuery( 62 std::string metadata_server_name, std::string attribute, 63 grpc_polling_entity* pollent, 64 absl::AnyInvocable<void(std::string /* attribute */, 65 absl::StatusOr<std::string> /* result */)> 66 callback, 67 Duration timeout); 68 69 ~MetadataQuery() override; 70 71 void Orphan() override; 72 73 private: 74 static void OnDone(void* arg, grpc_error_handle error); 75 76 grpc_closure on_done_; 77 std::string attribute_; 78 absl::AnyInvocable<void(std::string /* attribute */, 79 absl::StatusOr<std::string> /* result */)> 80 callback_; 81 OrphanablePtr<HttpRequest> http_request_; 82 grpc_http_response response_; 83 }; 84 85 } // namespace grpc_core 86 87 #endif // GRPC_SRC_CORE_EXT_GCP_METADATA_QUERY_H 88