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 json
17import logging as std_logging
18import pickle
19import warnings
20from typing import Callable, Dict, Optional, Sequence, Tuple, Union
21
22from google.api_core import grpc_helpers
23from google.api_core import gapic_v1
24import google.auth # type: ignore
25from google.auth import credentials as ga_credentials # type: ignore
26from google.auth.transport.grpc import SslCredentials # type: ignore
27from google.protobuf.json_format import MessageToJson
28import google.protobuf.message
29
30import grpc # type: ignore
31import proto # type: ignore
32
33from google.cloud.logging_v2.types import logging_metrics
34from google.longrunning import operations_pb2 # type: ignore
35from google.protobuf import empty_pb2 # type: ignore
36from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO
37
38try:
39 from google.api_core import client_logging # type: ignore
40
41 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
42except ImportError: # pragma: NO COVER
43 CLIENT_LOGGING_SUPPORTED = False
44
45_LOGGER = std_logging.getLogger(__name__)
46
47
48class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
49 def intercept_unary_unary(self, continuation, client_call_details, request):
50 logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
51 std_logging.DEBUG
52 )
53 if logging_enabled: # pragma: NO COVER
54 request_metadata = client_call_details.metadata
55 if isinstance(request, proto.Message):
56 request_payload = type(request).to_json(request)
57 elif isinstance(request, google.protobuf.message.Message):
58 request_payload = MessageToJson(request)
59 else:
60 request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
61
62 request_metadata = {
63 key: value.decode("utf-8") if isinstance(value, bytes) else value
64 for key, value in request_metadata
65 }
66 grpc_request = {
67 "payload": request_payload,
68 "requestMethod": "grpc",
69 "metadata": dict(request_metadata),
70 }
71 _LOGGER.debug(
72 f"Sending request for {client_call_details.method}",
73 extra={
74 "serviceName": "google.logging.v2.MetricsServiceV2",
75 "rpcName": client_call_details.method,
76 "request": grpc_request,
77 "metadata": grpc_request["metadata"],
78 },
79 )
80
81 response = continuation(client_call_details, request)
82 if logging_enabled: # pragma: NO COVER
83 response_metadata = response.trailing_metadata()
84 # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
85 metadata = (
86 dict([(k, str(v)) for k, v in response_metadata])
87 if response_metadata
88 else None
89 )
90 result = response.result()
91 if isinstance(result, proto.Message):
92 response_payload = type(result).to_json(result)
93 elif isinstance(result, google.protobuf.message.Message):
94 response_payload = MessageToJson(result)
95 else:
96 response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
97 grpc_response = {
98 "payload": response_payload,
99 "metadata": metadata,
100 "status": "OK",
101 }
102 _LOGGER.debug(
103 f"Received response for {client_call_details.method}.",
104 extra={
105 "serviceName": "google.logging.v2.MetricsServiceV2",
106 "rpcName": client_call_details.method,
107 "response": grpc_response,
108 "metadata": grpc_response["metadata"],
109 },
110 )
111 return response
112
113
114class MetricsServiceV2GrpcTransport(MetricsServiceV2Transport):
115 """gRPC backend transport for MetricsServiceV2.
116
117 Service for configuring logs-based metrics.
118
119 This class defines the same methods as the primary client, so the
120 primary client can load the underlying transport implementation
121 and call it.
122
123 It sends protocol buffers over the wire using gRPC (which is built on
124 top of HTTP/2); the ``grpcio`` package must be installed.
125 """
126
127 _stubs: Dict[str, Callable]
128
129 def __init__(
130 self,
131 *,
132 host: str = "logging.googleapis.com",
133 credentials: Optional[ga_credentials.Credentials] = None,
134 credentials_file: Optional[str] = None,
135 scopes: Optional[Sequence[str]] = None,
136 channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
137 api_mtls_endpoint: Optional[str] = None,
138 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
139 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
140 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
141 quota_project_id: Optional[str] = None,
142 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
143 always_use_jwt_access: Optional[bool] = False,
144 api_audience: Optional[str] = None,
145 ) -> None:
146 """Instantiate the transport.
147
148 Args:
149 host (Optional[str]):
150 The hostname to connect to (default: 'logging.googleapis.com').
151 credentials (Optional[google.auth.credentials.Credentials]): The
152 authorization credentials to attach to requests. These
153 credentials identify the application to the service; if none
154 are specified, the client will attempt to ascertain the
155 credentials from the environment.
156 This argument is ignored if a ``channel`` instance is provided.
157 credentials_file (Optional[str]): A file with credentials that can
158 be loaded with :func:`google.auth.load_credentials_from_file`.
159 This argument is ignored if a ``channel`` instance is provided.
160 scopes (Optional(Sequence[str])): A list of scopes. This argument is
161 ignored if a ``channel`` instance is provided.
162 channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
163 A ``Channel`` instance through which to make calls, or a Callable
164 that constructs and returns one. If set to None, ``self.create_channel``
165 is used to create the channel. If a Callable is given, it will be called
166 with the same arguments as used in ``self.create_channel``.
167 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
168 If provided, it overrides the ``host`` argument and tries to create
169 a mutual TLS channel with client SSL credentials from
170 ``client_cert_source`` or application default SSL credentials.
171 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
172 Deprecated. A callback to provide client SSL certificate bytes and
173 private key bytes, both in PEM format. It is ignored if
174 ``api_mtls_endpoint`` is None.
175 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
176 for the grpc channel. It is ignored if a ``channel`` instance is provided.
177 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
178 A callback to provide client certificate bytes and private key bytes,
179 both in PEM format. It is used to configure a mutual TLS channel. It is
180 ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
181 quota_project_id (Optional[str]): An optional project to use for billing
182 and quota.
183 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
184 The client info used to send a user-agent string along with
185 API requests. If ``None``, then default info will be used.
186 Generally, you only need to set this if you're developing
187 your own client library.
188 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
189 be used for service account credentials.
190
191 Raises:
192 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
193 creation failed for any reason.
194 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
195 and ``credentials_file`` are passed.
196 """
197 self._grpc_channel = None
198 self._ssl_channel_credentials = ssl_channel_credentials
199 self._stubs: Dict[str, Callable] = {}
200
201 if api_mtls_endpoint:
202 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
203 if client_cert_source:
204 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
205
206 if isinstance(channel, grpc.Channel):
207 # Ignore credentials if a channel was passed.
208 credentials = None
209 self._ignore_credentials = True
210 # If a channel was explicitly provided, set it.
211 self._grpc_channel = channel
212 self._ssl_channel_credentials = None
213
214 else:
215 if api_mtls_endpoint:
216 host = api_mtls_endpoint
217
218 # Create SSL credentials with client_cert_source or application
219 # default SSL credentials.
220 if client_cert_source:
221 cert, key = client_cert_source()
222 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
223 certificate_chain=cert, private_key=key
224 )
225 else:
226 self._ssl_channel_credentials = SslCredentials().ssl_credentials
227
228 else:
229 if client_cert_source_for_mtls and not ssl_channel_credentials:
230 cert, key = client_cert_source_for_mtls()
231 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
232 certificate_chain=cert, private_key=key
233 )
234
235 # The base transport sets the host, credentials and scopes
236 super().__init__(
237 host=host,
238 credentials=credentials,
239 credentials_file=credentials_file,
240 scopes=scopes,
241 quota_project_id=quota_project_id,
242 client_info=client_info,
243 always_use_jwt_access=always_use_jwt_access,
244 api_audience=api_audience,
245 )
246
247 if not self._grpc_channel:
248 # initialize with the provided callable or the default channel
249 channel_init = channel or type(self).create_channel
250 self._grpc_channel = channel_init(
251 self._host,
252 # use the credentials which are saved
253 credentials=self._credentials,
254 # Set ``credentials_file`` to ``None`` here as
255 # the credentials that we saved earlier should be used.
256 credentials_file=None,
257 scopes=self._scopes,
258 ssl_credentials=self._ssl_channel_credentials,
259 quota_project_id=quota_project_id,
260 options=[
261 ("grpc.max_send_message_length", -1),
262 ("grpc.max_receive_message_length", -1),
263 ],
264 )
265
266 self._interceptor = _LoggingClientInterceptor()
267 self._logged_channel = grpc.intercept_channel(
268 self._grpc_channel, self._interceptor
269 )
270
271 # Wrap messages. This must be done after self._logged_channel exists
272 self._prep_wrapped_messages(client_info)
273
274 @classmethod
275 def create_channel(
276 cls,
277 host: str = "logging.googleapis.com",
278 credentials: Optional[ga_credentials.Credentials] = None,
279 credentials_file: Optional[str] = None,
280 scopes: Optional[Sequence[str]] = None,
281 quota_project_id: Optional[str] = None,
282 **kwargs,
283 ) -> grpc.Channel:
284 """Create and return a gRPC channel object.
285 Args:
286 host (Optional[str]): The host for the channel to use.
287 credentials (Optional[~.Credentials]): The
288 authorization credentials to attach to requests. These
289 credentials identify this application to the service. If
290 none are specified, the client will attempt to ascertain
291 the credentials from the environment.
292 credentials_file (Optional[str]): A file with credentials that can
293 be loaded with :func:`google.auth.load_credentials_from_file`.
294 This argument is mutually exclusive with credentials.
295 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
296 service. These are only used when credentials are not specified and
297 are passed to :func:`google.auth.default`.
298 quota_project_id (Optional[str]): An optional project to use for billing
299 and quota.
300 kwargs (Optional[dict]): Keyword arguments, which are passed to the
301 channel creation.
302 Returns:
303 grpc.Channel: A gRPC channel object.
304
305 Raises:
306 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
307 and ``credentials_file`` are passed.
308 """
309
310 return grpc_helpers.create_channel(
311 host,
312 credentials=credentials,
313 credentials_file=credentials_file,
314 quota_project_id=quota_project_id,
315 default_scopes=cls.AUTH_SCOPES,
316 scopes=scopes,
317 default_host=cls.DEFAULT_HOST,
318 **kwargs,
319 )
320
321 @property
322 def grpc_channel(self) -> grpc.Channel:
323 """Return the channel designed to connect to this service."""
324 return self._grpc_channel
325
326 @property
327 def list_log_metrics(
328 self,
329 ) -> Callable[
330 [logging_metrics.ListLogMetricsRequest], logging_metrics.ListLogMetricsResponse
331 ]:
332 r"""Return a callable for the list log metrics method over gRPC.
333
334 Lists logs-based metrics.
335
336 Returns:
337 Callable[[~.ListLogMetricsRequest],
338 ~.ListLogMetricsResponse]:
339 A function that, when called, will call the underlying RPC
340 on the server.
341 """
342 # Generate a "stub function" on-the-fly which will actually make
343 # the request.
344 # gRPC handles serialization and deserialization, so we just need
345 # to pass in the functions for each.
346 if "list_log_metrics" not in self._stubs:
347 self._stubs["list_log_metrics"] = self._logged_channel.unary_unary(
348 "/google.logging.v2.MetricsServiceV2/ListLogMetrics",
349 request_serializer=logging_metrics.ListLogMetricsRequest.serialize,
350 response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize,
351 )
352 return self._stubs["list_log_metrics"]
353
354 @property
355 def get_log_metric(
356 self,
357 ) -> Callable[[logging_metrics.GetLogMetricRequest], logging_metrics.LogMetric]:
358 r"""Return a callable for the get log metric method over gRPC.
359
360 Gets a logs-based metric.
361
362 Returns:
363 Callable[[~.GetLogMetricRequest],
364 ~.LogMetric]:
365 A function that, when called, will call the underlying RPC
366 on the server.
367 """
368 # Generate a "stub function" on-the-fly which will actually make
369 # the request.
370 # gRPC handles serialization and deserialization, so we just need
371 # to pass in the functions for each.
372 if "get_log_metric" not in self._stubs:
373 self._stubs["get_log_metric"] = self._logged_channel.unary_unary(
374 "/google.logging.v2.MetricsServiceV2/GetLogMetric",
375 request_serializer=logging_metrics.GetLogMetricRequest.serialize,
376 response_deserializer=logging_metrics.LogMetric.deserialize,
377 )
378 return self._stubs["get_log_metric"]
379
380 @property
381 def create_log_metric(
382 self,
383 ) -> Callable[[logging_metrics.CreateLogMetricRequest], logging_metrics.LogMetric]:
384 r"""Return a callable for the create log metric method over gRPC.
385
386 Creates a logs-based metric.
387
388 Returns:
389 Callable[[~.CreateLogMetricRequest],
390 ~.LogMetric]:
391 A function that, when called, will call the underlying RPC
392 on the server.
393 """
394 # Generate a "stub function" on-the-fly which will actually make
395 # the request.
396 # gRPC handles serialization and deserialization, so we just need
397 # to pass in the functions for each.
398 if "create_log_metric" not in self._stubs:
399 self._stubs["create_log_metric"] = self._logged_channel.unary_unary(
400 "/google.logging.v2.MetricsServiceV2/CreateLogMetric",
401 request_serializer=logging_metrics.CreateLogMetricRequest.serialize,
402 response_deserializer=logging_metrics.LogMetric.deserialize,
403 )
404 return self._stubs["create_log_metric"]
405
406 @property
407 def update_log_metric(
408 self,
409 ) -> Callable[[logging_metrics.UpdateLogMetricRequest], logging_metrics.LogMetric]:
410 r"""Return a callable for the update log metric method over gRPC.
411
412 Creates or updates a logs-based metric.
413
414 Returns:
415 Callable[[~.UpdateLogMetricRequest],
416 ~.LogMetric]:
417 A function that, when called, will call the underlying RPC
418 on the server.
419 """
420 # Generate a "stub function" on-the-fly which will actually make
421 # the request.
422 # gRPC handles serialization and deserialization, so we just need
423 # to pass in the functions for each.
424 if "update_log_metric" not in self._stubs:
425 self._stubs["update_log_metric"] = self._logged_channel.unary_unary(
426 "/google.logging.v2.MetricsServiceV2/UpdateLogMetric",
427 request_serializer=logging_metrics.UpdateLogMetricRequest.serialize,
428 response_deserializer=logging_metrics.LogMetric.deserialize,
429 )
430 return self._stubs["update_log_metric"]
431
432 @property
433 def delete_log_metric(
434 self,
435 ) -> Callable[[logging_metrics.DeleteLogMetricRequest], empty_pb2.Empty]:
436 r"""Return a callable for the delete log metric method over gRPC.
437
438 Deletes a logs-based metric.
439
440 Returns:
441 Callable[[~.DeleteLogMetricRequest],
442 ~.Empty]:
443 A function that, when called, will call the underlying RPC
444 on the server.
445 """
446 # Generate a "stub function" on-the-fly which will actually make
447 # the request.
448 # gRPC handles serialization and deserialization, so we just need
449 # to pass in the functions for each.
450 if "delete_log_metric" not in self._stubs:
451 self._stubs["delete_log_metric"] = self._logged_channel.unary_unary(
452 "/google.logging.v2.MetricsServiceV2/DeleteLogMetric",
453 request_serializer=logging_metrics.DeleteLogMetricRequest.serialize,
454 response_deserializer=empty_pb2.Empty.FromString,
455 )
456 return self._stubs["delete_log_metric"]
457
458 def close(self):
459 self._logged_channel.close()
460
461 @property
462 def cancel_operation(
463 self,
464 ) -> Callable[[operations_pb2.CancelOperationRequest], None]:
465 r"""Return a callable for the cancel_operation method over gRPC."""
466 # Generate a "stub function" on-the-fly which will actually make
467 # the request.
468 # gRPC handles serialization and deserialization, so we just need
469 # to pass in the functions for each.
470 if "cancel_operation" not in self._stubs:
471 self._stubs["cancel_operation"] = self._logged_channel.unary_unary(
472 "/google.longrunning.Operations/CancelOperation",
473 request_serializer=operations_pb2.CancelOperationRequest.SerializeToString,
474 response_deserializer=None,
475 )
476 return self._stubs["cancel_operation"]
477
478 @property
479 def get_operation(
480 self,
481 ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
482 r"""Return a callable for the get_operation method over gRPC."""
483 # Generate a "stub function" on-the-fly which will actually make
484 # the request.
485 # gRPC handles serialization and deserialization, so we just need
486 # to pass in the functions for each.
487 if "get_operation" not in self._stubs:
488 self._stubs["get_operation"] = self._logged_channel.unary_unary(
489 "/google.longrunning.Operations/GetOperation",
490 request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
491 response_deserializer=operations_pb2.Operation.FromString,
492 )
493 return self._stubs["get_operation"]
494
495 @property
496 def list_operations(
497 self,
498 ) -> Callable[
499 [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
500 ]:
501 r"""Return a callable for the list_operations method over gRPC."""
502 # Generate a "stub function" on-the-fly which will actually make
503 # the request.
504 # gRPC handles serialization and deserialization, so we just need
505 # to pass in the functions for each.
506 if "list_operations" not in self._stubs:
507 self._stubs["list_operations"] = self._logged_channel.unary_unary(
508 "/google.longrunning.Operations/ListOperations",
509 request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
510 response_deserializer=operations_pb2.ListOperationsResponse.FromString,
511 )
512 return self._stubs["list_operations"]
513
514 @property
515 def kind(self) -> str:
516 return "grpc"
517
518
519__all__ = ("MetricsServiceV2GrpcTransport",)