1# -*- coding: utf-8 -*-
2# Copyright 2025 Google LLC
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#
16import abc
17from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
18
19from google.cloud.logging_v2 import gapic_version as package_version
20
21import google.auth # type: ignore
22import google.api_core
23from google.api_core import exceptions as core_exceptions
24from google.api_core import gapic_v1
25from google.api_core import retry as retries
26from google.auth import credentials as ga_credentials # type: ignore
27from google.oauth2 import service_account # type: ignore
28import google.protobuf
29
30from google.cloud.logging_v2.types import logging_metrics
31from google.longrunning import operations_pb2 # type: ignore
32import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
33
34DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
35 gapic_version=package_version.__version__
36)
37
38if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
39 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
40
41
42class MetricsServiceV2Transport(abc.ABC):
43 """Abstract transport class for MetricsServiceV2."""
44
45 AUTH_SCOPES = (
46 "https://www.googleapis.com/auth/cloud-platform",
47 "https://www.googleapis.com/auth/cloud-platform.read-only",
48 "https://www.googleapis.com/auth/logging.admin",
49 "https://www.googleapis.com/auth/logging.read",
50 "https://www.googleapis.com/auth/logging.write",
51 )
52
53 DEFAULT_HOST: str = "logging.googleapis.com"
54
55 def __init__(
56 self,
57 *,
58 host: str = DEFAULT_HOST,
59 credentials: Optional[ga_credentials.Credentials] = None,
60 credentials_file: Optional[str] = None,
61 scopes: Optional[Sequence[str]] = None,
62 quota_project_id: Optional[str] = None,
63 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
64 always_use_jwt_access: Optional[bool] = False,
65 api_audience: Optional[str] = None,
66 **kwargs,
67 ) -> None:
68 """Instantiate the transport.
69
70 Args:
71 host (Optional[str]):
72 The hostname to connect to (default: 'logging.googleapis.com').
73 credentials (Optional[google.auth.credentials.Credentials]): The
74 authorization credentials to attach to requests. These
75 credentials identify the application to the service; if none
76 are specified, the client will attempt to ascertain the
77 credentials from the environment.
78 credentials_file (Optional[str]): Deprecated. A file with credentials that can
79 be loaded with :func:`google.auth.load_credentials_from_file`.
80 This argument is mutually exclusive with credentials. This argument will be
81 removed in the next major version of this library.
82 scopes (Optional[Sequence[str]]): A list of scopes.
83 quota_project_id (Optional[str]): An optional project to use for billing
84 and quota.
85 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
86 The client info used to send a user-agent string along with
87 API requests. If ``None``, then default info will be used.
88 Generally, you only need to set this if you're developing
89 your own client library.
90 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
91 be used for service account credentials.
92 """
93
94 # Save the scopes.
95 self._scopes = scopes
96 if not hasattr(self, "_ignore_credentials"):
97 self._ignore_credentials: bool = False
98
99 # If no credentials are provided, then determine the appropriate
100 # defaults.
101 if credentials and credentials_file:
102 raise core_exceptions.DuplicateCredentialArgs(
103 "'credentials_file' and 'credentials' are mutually exclusive"
104 )
105
106 if credentials_file is not None:
107 credentials, _ = google.auth.load_credentials_from_file(
108 credentials_file,
109 scopes=scopes,
110 quota_project_id=quota_project_id,
111 default_scopes=self.AUTH_SCOPES,
112 )
113 elif credentials is None and not self._ignore_credentials:
114 credentials, _ = google.auth.default(
115 scopes=scopes,
116 quota_project_id=quota_project_id,
117 default_scopes=self.AUTH_SCOPES,
118 )
119 # Don't apply audience if the credentials file passed from user.
120 if hasattr(credentials, "with_gdch_audience"):
121 credentials = credentials.with_gdch_audience(
122 api_audience if api_audience else host
123 )
124
125 # If the credentials are service account credentials, then always try to use self signed JWT.
126 if (
127 always_use_jwt_access
128 and isinstance(credentials, service_account.Credentials)
129 and hasattr(service_account.Credentials, "with_always_use_jwt_access")
130 ):
131 credentials = credentials.with_always_use_jwt_access(True)
132
133 # Save the credentials.
134 self._credentials = credentials
135
136 # Save the hostname. Default to port 443 (HTTPS) if none is specified.
137 if ":" not in host:
138 host += ":443"
139 self._host = host
140
141 @property
142 def host(self):
143 return self._host
144
145 def _prep_wrapped_messages(self, client_info):
146 # Precompute the wrapped methods.
147 self._wrapped_methods = {
148 self.list_log_metrics: gapic_v1.method.wrap_method(
149 self.list_log_metrics,
150 default_retry=retries.Retry(
151 initial=0.1,
152 maximum=60.0,
153 multiplier=1.3,
154 predicate=retries.if_exception_type(
155 core_exceptions.DeadlineExceeded,
156 core_exceptions.InternalServerError,
157 core_exceptions.ServiceUnavailable,
158 ),
159 deadline=60.0,
160 ),
161 default_timeout=60.0,
162 client_info=client_info,
163 ),
164 self.get_log_metric: gapic_v1.method.wrap_method(
165 self.get_log_metric,
166 default_retry=retries.Retry(
167 initial=0.1,
168 maximum=60.0,
169 multiplier=1.3,
170 predicate=retries.if_exception_type(
171 core_exceptions.DeadlineExceeded,
172 core_exceptions.InternalServerError,
173 core_exceptions.ServiceUnavailable,
174 ),
175 deadline=60.0,
176 ),
177 default_timeout=60.0,
178 client_info=client_info,
179 ),
180 self.create_log_metric: gapic_v1.method.wrap_method(
181 self.create_log_metric,
182 default_timeout=60.0,
183 client_info=client_info,
184 ),
185 self.update_log_metric: gapic_v1.method.wrap_method(
186 self.update_log_metric,
187 default_retry=retries.Retry(
188 initial=0.1,
189 maximum=60.0,
190 multiplier=1.3,
191 predicate=retries.if_exception_type(
192 core_exceptions.DeadlineExceeded,
193 core_exceptions.InternalServerError,
194 core_exceptions.ServiceUnavailable,
195 ),
196 deadline=60.0,
197 ),
198 default_timeout=60.0,
199 client_info=client_info,
200 ),
201 self.delete_log_metric: gapic_v1.method.wrap_method(
202 self.delete_log_metric,
203 default_retry=retries.Retry(
204 initial=0.1,
205 maximum=60.0,
206 multiplier=1.3,
207 predicate=retries.if_exception_type(
208 core_exceptions.DeadlineExceeded,
209 core_exceptions.InternalServerError,
210 core_exceptions.ServiceUnavailable,
211 ),
212 deadline=60.0,
213 ),
214 default_timeout=60.0,
215 client_info=client_info,
216 ),
217 self.cancel_operation: gapic_v1.method.wrap_method(
218 self.cancel_operation,
219 default_timeout=None,
220 client_info=client_info,
221 ),
222 self.get_operation: gapic_v1.method.wrap_method(
223 self.get_operation,
224 default_timeout=None,
225 client_info=client_info,
226 ),
227 self.list_operations: gapic_v1.method.wrap_method(
228 self.list_operations,
229 default_timeout=None,
230 client_info=client_info,
231 ),
232 }
233
234 def close(self):
235 """Closes resources associated with the transport.
236
237 .. warning::
238 Only call this method if the transport is NOT shared
239 with other clients - this may cause errors in other clients!
240 """
241 raise NotImplementedError()
242
243 @property
244 def list_log_metrics(
245 self,
246 ) -> Callable[
247 [logging_metrics.ListLogMetricsRequest],
248 Union[
249 logging_metrics.ListLogMetricsResponse,
250 Awaitable[logging_metrics.ListLogMetricsResponse],
251 ],
252 ]:
253 raise NotImplementedError()
254
255 @property
256 def get_log_metric(
257 self,
258 ) -> Callable[
259 [logging_metrics.GetLogMetricRequest],
260 Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]],
261 ]:
262 raise NotImplementedError()
263
264 @property
265 def create_log_metric(
266 self,
267 ) -> Callable[
268 [logging_metrics.CreateLogMetricRequest],
269 Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]],
270 ]:
271 raise NotImplementedError()
272
273 @property
274 def update_log_metric(
275 self,
276 ) -> Callable[
277 [logging_metrics.UpdateLogMetricRequest],
278 Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]],
279 ]:
280 raise NotImplementedError()
281
282 @property
283 def delete_log_metric(
284 self,
285 ) -> Callable[
286 [logging_metrics.DeleteLogMetricRequest],
287 Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
288 ]:
289 raise NotImplementedError()
290
291 @property
292 def list_operations(
293 self,
294 ) -> Callable[
295 [operations_pb2.ListOperationsRequest],
296 Union[
297 operations_pb2.ListOperationsResponse,
298 Awaitable[operations_pb2.ListOperationsResponse],
299 ],
300 ]:
301 raise NotImplementedError()
302
303 @property
304 def get_operation(
305 self,
306 ) -> Callable[
307 [operations_pb2.GetOperationRequest],
308 Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
309 ]:
310 raise NotImplementedError()
311
312 @property
313 def cancel_operation(
314 self,
315 ) -> Callable[[operations_pb2.CancelOperationRequest], None,]:
316 raise NotImplementedError()
317
318 @property
319 def kind(self) -> str:
320 raise NotImplementedError()
321
322
323__all__ = ("MetricsServiceV2Transport",)