2020import time
2121import base64
2222import threading
23+ import logging
2324
2425from google .protobuf .struct_pb2 import ListValue
2526from google .protobuf .struct_pb2 import Value
2930from google .api_core import datetime_helpers
3031from google .api_core .exceptions import Aborted
3132from google .cloud ._helpers import _date_from_iso8601_date
32- from google .cloud .spanner_v1 import TypeCode
33- from google .cloud .spanner_v1 import ExecuteSqlRequest
34- from google .cloud .spanner_v1 import JsonObject , Interval
35- from google .cloud .spanner_v1 import TransactionOptions
33+ from google .cloud .spanner_v1 .types import ExecuteSqlRequest
34+ from google .cloud .spanner_v1 .types import TransactionOptions
35+ from google .cloud .spanner_v1 .data_types import JsonObject , Interval
3636from google .cloud .spanner_v1 .request_id_header import with_request_id
37+ from google .cloud .spanner_v1 .types import TypeCode
38+ from opentelemetry .semconv .resource import ResourceAttributes
39+ from opentelemetry .resourcedetector .gcp_resource_detector import (
40+ GoogleCloudResourceDetector ,
41+ )
42+
3743from google .rpc .error_details_pb2 import RetryInfo
3844
3945try :
5561 + "numeric has a whole component with precision {}"
5662)
5763
64+ GOOGLE_CLOUD_REGION_GLOBAL = "global"
65+
66+ log = logging .getLogger (__name__ )
67+
5868
5969if HAS_OPENTELEMETRY_INSTALLED :
6070
@@ -79,6 +89,28 @@ def set(self, carrier: List[Tuple[str, str]], key: str, value: str) -> None:
7989 carrier .append ((key , value ))
8090
8191
92+ def _get_cloud_region () -> str :
93+ """Get the location of the resource.
94+
95+ Returns:
96+ str: The location of the resource. If OpenTelemetry is not installed, returns a global region.
97+ """
98+ if not HAS_OPENTELEMETRY_INSTALLED :
99+ return GOOGLE_CLOUD_REGION_GLOBAL
100+ try :
101+ detector = GoogleCloudResourceDetector ()
102+ resources = detector .detect ()
103+
104+ if ResourceAttributes .CLOUD_REGION in resources .attributes :
105+ return resources .attributes [ResourceAttributes .CLOUD_REGION ]
106+ except Exception as e :
107+ log .warning (
108+ "Failed to detect GCP resource location for Spanner metrics, defaulting to 'global'. Error: %s" ,
109+ e ,
110+ )
111+ return GOOGLE_CLOUD_REGION_GLOBAL
112+
113+
82114def _try_to_coerce_bytes (bytestring ):
83115 """Try to coerce a byte string into the right thing based on Python
84116 version and whether or not it is base64 encoded.
0 commit comments