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