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_CPP_EXT_GCP_ENVIRONMENT_AUTODETECT_H 18 #define GRPC_SRC_CPP_EXT_GCP_ENVIRONMENT_AUTODETECT_H 19 20 #include <grpc/support/port_platform.h> 21 22 #include <map> 23 #include <memory> 24 #include <string> 25 #include <vector> 26 27 #include "absl/base/thread_annotations.h" 28 #include "absl/functional/any_invocable.h" 29 #include "absl/status/status.h" 30 31 #include <grpc/event_engine/event_engine.h> 32 33 #include "src/core/lib/gprpp/sync.h" 34 35 namespace grpc { 36 37 namespace internal { 38 39 absl::Status GcpObservabilityInit(); 40 41 class EnvironmentAutoDetect { 42 public: 43 struct ResourceType { 44 // For example, "gce_instance", "gke_container", etc. 45 std::string resource_type; 46 // Values for all the labels listed in the associated resource type. 47 std::map<std::string, std::string> labels; 48 }; 49 50 static EnvironmentAutoDetect& Get(); 51 52 // Exposed for testing purposes only 53 explicit EnvironmentAutoDetect(std::string project_id); 54 55 // \a callback will be invoked once the environment is done being detected. 56 void NotifyOnDone(absl::AnyInvocable<void()> callback); 57 resource()58 const ResourceType* resource() { 59 grpc_core::MutexLock lock(&mu_); 60 return resource_.get(); 61 } 62 63 private: 64 friend absl::Status grpc::internal::GcpObservabilityInit(); 65 66 // GcpObservabilityInit() is responsible for setting up the singleton with the 67 // project_id. 68 static void Create(std::string project_id); 69 70 const std::string project_id_; 71 std::shared_ptr<grpc_event_engine::experimental::EventEngine> event_engine_; 72 grpc_core::Mutex mu_; 73 std::unique_ptr<ResourceType> resource_ ABSL_GUARDED_BY(mu_); 74 std::vector<absl::AnyInvocable<void()>> callbacks_ ABSL_GUARDED_BY(mu_); 75 }; 76 77 } // namespace internal 78 } // namespace grpc 79 80 #endif // GRPC_SRC_CPP_EXT_GCP_ENVIRONMENT_AUTODETECT_H 81