4242 from opentelemetry .propagate import inject
4343 from opentelemetry .propagators .textmap import Setter
4444 from opentelemetry .semconv .resource import ResourceAttributes
45+ from opentelemetry .resourcedetector import gcp_resource_detector
4546 from opentelemetry .resourcedetector .gcp_resource_detector import (
4647 GoogleCloudResourceDetector ,
4748 )
4849
50+ # Overwrite the requests timeout for the detector.
51+ # This is necessary as the client will wait the full timeout if the
52+ # code is not run in a GCP environment, with the location endpoints available.
53+ gcp_resource_detector ._TIMEOUT_SEC = 0.2
54+
4955 HAS_OPENTELEMETRY_INSTALLED = True
5056except ImportError :
5157 HAS_OPENTELEMETRY_INSTALLED = False
6571
6672log = logging .getLogger (__name__ )
6773
74+ _cloud_region : str = None
75+
6876
6977if HAS_OPENTELEMETRY_INSTALLED :
7078
@@ -90,25 +98,30 @@ def set(self, carrier: List[Tuple[str, str]], key: str, value: str) -> None:
9098
9199
92100def _get_cloud_region () -> str :
93- """Get the location of the resource.
101+ """Get the location of the resource, caching the result .
94102
95103 Returns:
96104 str: The location of the resource. If OpenTelemetry is not installed, returns a global region.
97105 """
98- if not HAS_OPENTELEMETRY_INSTALLED :
99- return GOOGLE_CLOUD_REGION_GLOBAL
106+ global _cloud_region
107+ if _cloud_region is not None :
108+ return _cloud_region
109+
100110 try :
101111 detector = GoogleCloudResourceDetector ()
102112 resources = detector .detect ()
103-
104113 if ResourceAttributes .CLOUD_REGION in resources .attributes :
105- return resources .attributes [ResourceAttributes .CLOUD_REGION ]
114+ _cloud_region = resources .attributes [ResourceAttributes .CLOUD_REGION ]
115+ else :
116+ _cloud_region = GOOGLE_CLOUD_REGION_GLOBAL
106117 except Exception as e :
107118 log .warning (
108119 "Failed to detect GCP resource location for Spanner metrics, defaulting to 'global'. Error: %s" ,
109120 e ,
110121 )
111- return GOOGLE_CLOUD_REGION_GLOBAL
122+ _cloud_region = GOOGLE_CLOUD_REGION_GLOBAL
123+
124+ return _cloud_region
112125
113126
114127def _try_to_coerce_bytes (bytestring ):
0 commit comments