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#
16from collections import OrderedDict
17from http import HTTPStatus
18import json
19import logging as std_logging
20import os
21import re
22from typing import (
23 Dict,
24 Callable,
25 Mapping,
26 MutableMapping,
27 MutableSequence,
28 Optional,
29 Sequence,
30 Tuple,
31 Type,
32 Union,
33 cast,
34)
35import warnings
36
37from google.cloud.logging_v2 import gapic_version as package_version
38
39from google.api_core import client_options as client_options_lib
40from google.api_core import exceptions as core_exceptions
41from google.api_core import gapic_v1
42from google.api_core import retry as retries
43from google.auth import credentials as ga_credentials # type: ignore
44from google.auth.transport import mtls # type: ignore
45from google.auth.transport.grpc import SslCredentials # type: ignore
46from google.auth.exceptions import MutualTLSChannelError # type: ignore
47from google.oauth2 import service_account # type: ignore
48
49try:
50 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
51except AttributeError: # pragma: NO COVER
52 OptionalRetry = Union[retries.Retry, object, None] # type: ignore
53
54try:
55 from google.api_core import client_logging # type: ignore
56
57 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
58except ImportError: # pragma: NO COVER
59 CLIENT_LOGGING_SUPPORTED = False
60
61_LOGGER = std_logging.getLogger(__name__)
62
63from google.api import distribution_pb2 # type: ignore
64from google.api import metric_pb2 # type: ignore
65from google.cloud.logging_v2.services.metrics_service_v2 import pagers
66from google.cloud.logging_v2.types import logging_metrics
67from google.longrunning import operations_pb2 # type: ignore
68from google.protobuf import timestamp_pb2 # type: ignore
69from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO
70from .transports.grpc import MetricsServiceV2GrpcTransport
71from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport
72
73
74class MetricsServiceV2ClientMeta(type):
75 """Metaclass for the MetricsServiceV2 client.
76
77 This provides class-level methods for building and retrieving
78 support objects (e.g. transport) without polluting the client instance
79 objects.
80 """
81
82 _transport_registry = (
83 OrderedDict()
84 ) # type: Dict[str, Type[MetricsServiceV2Transport]]
85 _transport_registry["grpc"] = MetricsServiceV2GrpcTransport
86 _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport
87
88 def get_transport_class(
89 cls,
90 label: Optional[str] = None,
91 ) -> Type[MetricsServiceV2Transport]:
92 """Returns an appropriate transport class.
93
94 Args:
95 label: The name of the desired transport. If none is
96 provided, then the first transport in the registry is used.
97
98 Returns:
99 The transport class to use.
100 """
101 # If a specific transport is requested, return that one.
102 if label:
103 return cls._transport_registry[label]
104
105 # No transport is requested; return the default (that is, the first one
106 # in the dictionary).
107 return next(iter(cls._transport_registry.values()))
108
109
110class MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta):
111 """Service for configuring logs-based metrics."""
112
113 @staticmethod
114 def _get_default_mtls_endpoint(api_endpoint):
115 """Converts api endpoint to mTLS endpoint.
116
117 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
118 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
119 Args:
120 api_endpoint (Optional[str]): the api endpoint to convert.
121 Returns:
122 str: converted mTLS api endpoint.
123 """
124 if not api_endpoint:
125 return api_endpoint
126
127 mtls_endpoint_re = re.compile(
128 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
129 )
130
131 m = mtls_endpoint_re.match(api_endpoint)
132 name, mtls, sandbox, googledomain = m.groups()
133 if mtls or not googledomain:
134 return api_endpoint
135
136 if sandbox:
137 return api_endpoint.replace(
138 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
139 )
140
141 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
142
143 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
144 DEFAULT_ENDPOINT = "logging.googleapis.com"
145 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
146 DEFAULT_ENDPOINT
147 )
148
149 _DEFAULT_ENDPOINT_TEMPLATE = "logging.{UNIVERSE_DOMAIN}"
150 _DEFAULT_UNIVERSE = "googleapis.com"
151
152 @classmethod
153 def from_service_account_info(cls, info: dict, *args, **kwargs):
154 """Creates an instance of this client using the provided credentials
155 info.
156
157 Args:
158 info (dict): The service account private key info.
159 args: Additional arguments to pass to the constructor.
160 kwargs: Additional arguments to pass to the constructor.
161
162 Returns:
163 MetricsServiceV2Client: The constructed client.
164 """
165 credentials = service_account.Credentials.from_service_account_info(info)
166 kwargs["credentials"] = credentials
167 return cls(*args, **kwargs)
168
169 @classmethod
170 def from_service_account_file(cls, filename: str, *args, **kwargs):
171 """Creates an instance of this client using the provided credentials
172 file.
173
174 Args:
175 filename (str): The path to the service account private key json
176 file.
177 args: Additional arguments to pass to the constructor.
178 kwargs: Additional arguments to pass to the constructor.
179
180 Returns:
181 MetricsServiceV2Client: The constructed client.
182 """
183 credentials = service_account.Credentials.from_service_account_file(filename)
184 kwargs["credentials"] = credentials
185 return cls(*args, **kwargs)
186
187 from_service_account_json = from_service_account_file
188
189 @property
190 def transport(self) -> MetricsServiceV2Transport:
191 """Returns the transport used by the client instance.
192
193 Returns:
194 MetricsServiceV2Transport: The transport used by the client
195 instance.
196 """
197 return self._transport
198
199 @staticmethod
200 def log_metric_path(
201 project: str,
202 metric: str,
203 ) -> str:
204 """Returns a fully-qualified log_metric string."""
205 return "projects/{project}/metrics/{metric}".format(
206 project=project,
207 metric=metric,
208 )
209
210 @staticmethod
211 def parse_log_metric_path(path: str) -> Dict[str, str]:
212 """Parses a log_metric path into its component segments."""
213 m = re.match(r"^projects/(?P<project>.+?)/metrics/(?P<metric>.+?)$", path)
214 return m.groupdict() if m else {}
215
216 @staticmethod
217 def common_billing_account_path(
218 billing_account: str,
219 ) -> str:
220 """Returns a fully-qualified billing_account string."""
221 return "billingAccounts/{billing_account}".format(
222 billing_account=billing_account,
223 )
224
225 @staticmethod
226 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
227 """Parse a billing_account path into its component segments."""
228 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
229 return m.groupdict() if m else {}
230
231 @staticmethod
232 def common_folder_path(
233 folder: str,
234 ) -> str:
235 """Returns a fully-qualified folder string."""
236 return "folders/{folder}".format(
237 folder=folder,
238 )
239
240 @staticmethod
241 def parse_common_folder_path(path: str) -> Dict[str, str]:
242 """Parse a folder path into its component segments."""
243 m = re.match(r"^folders/(?P<folder>.+?)$", path)
244 return m.groupdict() if m else {}
245
246 @staticmethod
247 def common_organization_path(
248 organization: str,
249 ) -> str:
250 """Returns a fully-qualified organization string."""
251 return "organizations/{organization}".format(
252 organization=organization,
253 )
254
255 @staticmethod
256 def parse_common_organization_path(path: str) -> Dict[str, str]:
257 """Parse a organization path into its component segments."""
258 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
259 return m.groupdict() if m else {}
260
261 @staticmethod
262 def common_project_path(
263 project: str,
264 ) -> str:
265 """Returns a fully-qualified project string."""
266 return "projects/{project}".format(
267 project=project,
268 )
269
270 @staticmethod
271 def parse_common_project_path(path: str) -> Dict[str, str]:
272 """Parse a project path into its component segments."""
273 m = re.match(r"^projects/(?P<project>.+?)$", path)
274 return m.groupdict() if m else {}
275
276 @staticmethod
277 def common_location_path(
278 project: str,
279 location: str,
280 ) -> str:
281 """Returns a fully-qualified location string."""
282 return "projects/{project}/locations/{location}".format(
283 project=project,
284 location=location,
285 )
286
287 @staticmethod
288 def parse_common_location_path(path: str) -> Dict[str, str]:
289 """Parse a location path into its component segments."""
290 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
291 return m.groupdict() if m else {}
292
293 @classmethod
294 def get_mtls_endpoint_and_cert_source(
295 cls, client_options: Optional[client_options_lib.ClientOptions] = None
296 ):
297 """Deprecated. Return the API endpoint and client cert source for mutual TLS.
298
299 The client cert source is determined in the following order:
300 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
301 client cert source is None.
302 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
303 default client cert source exists, use the default one; otherwise the client cert
304 source is None.
305
306 The API endpoint is determined in the following order:
307 (1) if `client_options.api_endpoint` if provided, use the provided one.
308 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
309 default mTLS endpoint; if the environment variable is "never", use the default API
310 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
311 use the default API endpoint.
312
313 More details can be found at https://google.aip.dev/auth/4114.
314
315 Args:
316 client_options (google.api_core.client_options.ClientOptions): Custom options for the
317 client. Only the `api_endpoint` and `client_cert_source` properties may be used
318 in this method.
319
320 Returns:
321 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
322 client cert source to use.
323
324 Raises:
325 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
326 """
327
328 warnings.warn(
329 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
330 DeprecationWarning,
331 )
332 if client_options is None:
333 client_options = client_options_lib.ClientOptions()
334 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
335 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
336 if use_client_cert not in ("true", "false"):
337 raise ValueError(
338 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
339 )
340 if use_mtls_endpoint not in ("auto", "never", "always"):
341 raise MutualTLSChannelError(
342 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
343 )
344
345 # Figure out the client cert source to use.
346 client_cert_source = None
347 if use_client_cert == "true":
348 if client_options.client_cert_source:
349 client_cert_source = client_options.client_cert_source
350 elif mtls.has_default_client_cert_source():
351 client_cert_source = mtls.default_client_cert_source()
352
353 # Figure out which api endpoint to use.
354 if client_options.api_endpoint is not None:
355 api_endpoint = client_options.api_endpoint
356 elif use_mtls_endpoint == "always" or (
357 use_mtls_endpoint == "auto" and client_cert_source
358 ):
359 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
360 else:
361 api_endpoint = cls.DEFAULT_ENDPOINT
362
363 return api_endpoint, client_cert_source
364
365 @staticmethod
366 def _read_environment_variables():
367 """Returns the environment variables used by the client.
368
369 Returns:
370 Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
371 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
372
373 Raises:
374 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
375 any of ["true", "false"].
376 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
377 is not any of ["auto", "never", "always"].
378 """
379 use_client_cert = os.getenv(
380 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
381 ).lower()
382 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
383 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
384 if use_client_cert not in ("true", "false"):
385 raise ValueError(
386 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
387 )
388 if use_mtls_endpoint not in ("auto", "never", "always"):
389 raise MutualTLSChannelError(
390 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
391 )
392 return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
393
394 @staticmethod
395 def _get_client_cert_source(provided_cert_source, use_cert_flag):
396 """Return the client cert source to be used by the client.
397
398 Args:
399 provided_cert_source (bytes): The client certificate source provided.
400 use_cert_flag (bool): A flag indicating whether to use the client certificate.
401
402 Returns:
403 bytes or None: The client cert source to be used by the client.
404 """
405 client_cert_source = None
406 if use_cert_flag:
407 if provided_cert_source:
408 client_cert_source = provided_cert_source
409 elif mtls.has_default_client_cert_source():
410 client_cert_source = mtls.default_client_cert_source()
411 return client_cert_source
412
413 @staticmethod
414 def _get_api_endpoint(
415 api_override, client_cert_source, universe_domain, use_mtls_endpoint
416 ):
417 """Return the API endpoint used by the client.
418
419 Args:
420 api_override (str): The API endpoint override. If specified, this is always
421 the return value of this function and the other arguments are not used.
422 client_cert_source (bytes): The client certificate source used by the client.
423 universe_domain (str): The universe domain used by the client.
424 use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
425 Possible values are "always", "auto", or "never".
426
427 Returns:
428 str: The API endpoint to be used by the client.
429 """
430 if api_override is not None:
431 api_endpoint = api_override
432 elif use_mtls_endpoint == "always" or (
433 use_mtls_endpoint == "auto" and client_cert_source
434 ):
435 _default_universe = MetricsServiceV2Client._DEFAULT_UNIVERSE
436 if universe_domain != _default_universe:
437 raise MutualTLSChannelError(
438 f"mTLS is not supported in any universe other than {_default_universe}."
439 )
440 api_endpoint = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT
441 else:
442 api_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
443 UNIVERSE_DOMAIN=universe_domain
444 )
445 return api_endpoint
446
447 @staticmethod
448 def _get_universe_domain(
449 client_universe_domain: Optional[str], universe_domain_env: Optional[str]
450 ) -> str:
451 """Return the universe domain used by the client.
452
453 Args:
454 client_universe_domain (Optional[str]): The universe domain configured via the client options.
455 universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
456
457 Returns:
458 str: The universe domain to be used by the client.
459
460 Raises:
461 ValueError: If the universe domain is an empty string.
462 """
463 universe_domain = MetricsServiceV2Client._DEFAULT_UNIVERSE
464 if client_universe_domain is not None:
465 universe_domain = client_universe_domain
466 elif universe_domain_env is not None:
467 universe_domain = universe_domain_env
468 if len(universe_domain.strip()) == 0:
469 raise ValueError("Universe Domain cannot be an empty string.")
470 return universe_domain
471
472 def _validate_universe_domain(self):
473 """Validates client's and credentials' universe domains are consistent.
474
475 Returns:
476 bool: True iff the configured universe domain is valid.
477
478 Raises:
479 ValueError: If the configured universe domain is not valid.
480 """
481
482 # NOTE (b/349488459): universe validation is disabled until further notice.
483 return True
484
485 def _add_cred_info_for_auth_errors(
486 self, error: core_exceptions.GoogleAPICallError
487 ) -> None:
488 """Adds credential info string to error details for 401/403/404 errors.
489
490 Args:
491 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info.
492 """
493 if error.code not in [
494 HTTPStatus.UNAUTHORIZED,
495 HTTPStatus.FORBIDDEN,
496 HTTPStatus.NOT_FOUND,
497 ]:
498 return
499
500 cred = self._transport._credentials
501
502 # get_cred_info is only available in google-auth>=2.35.0
503 if not hasattr(cred, "get_cred_info"):
504 return
505
506 # ignore the type check since pypy test fails when get_cred_info
507 # is not available
508 cred_info = cred.get_cred_info() # type: ignore
509 if cred_info and hasattr(error._details, "append"):
510 error._details.append(json.dumps(cred_info))
511
512 @property
513 def api_endpoint(self):
514 """Return the API endpoint used by the client instance.
515
516 Returns:
517 str: The API endpoint used by the client instance.
518 """
519 return self._api_endpoint
520
521 @property
522 def universe_domain(self) -> str:
523 """Return the universe domain used by the client instance.
524
525 Returns:
526 str: The universe domain used by the client instance.
527 """
528 return self._universe_domain
529
530 def __init__(
531 self,
532 *,
533 credentials: Optional[ga_credentials.Credentials] = None,
534 transport: Optional[
535 Union[
536 str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]
537 ]
538 ] = None,
539 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
540 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
541 ) -> None:
542 """Instantiates the metrics service v2 client.
543
544 Args:
545 credentials (Optional[google.auth.credentials.Credentials]): The
546 authorization credentials to attach to requests. These
547 credentials identify the application to the service; if none
548 are specified, the client will attempt to ascertain the
549 credentials from the environment.
550 transport (Optional[Union[str,MetricsServiceV2Transport,Callable[..., MetricsServiceV2Transport]]]):
551 The transport to use, or a Callable that constructs and returns a new transport.
552 If a Callable is given, it will be called with the same set of initialization
553 arguments as used in the MetricsServiceV2Transport constructor.
554 If set to None, a transport is chosen automatically.
555 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
556 Custom options for the client.
557
558 1. The ``api_endpoint`` property can be used to override the
559 default endpoint provided by the client when ``transport`` is
560 not explicitly provided. Only if this property is not set and
561 ``transport`` was not explicitly provided, the endpoint is
562 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
563 variable, which have one of the following values:
564 "always" (always use the default mTLS endpoint), "never" (always
565 use the default regular endpoint) and "auto" (auto-switch to the
566 default mTLS endpoint if client certificate is present; this is
567 the default value).
568
569 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
570 is "true", then the ``client_cert_source`` property can be used
571 to provide a client certificate for mTLS transport. If
572 not provided, the default SSL client certificate will be used if
573 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
574 set, no client certificate will be used.
575
576 3. The ``universe_domain`` property can be used to override the
577 default "googleapis.com" universe. Note that the ``api_endpoint``
578 property still takes precedence; and ``universe_domain`` is
579 currently not supported for mTLS.
580
581 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
582 The client info used to send a user-agent string along with
583 API requests. If ``None``, then default info will be used.
584 Generally, you only need to set this if you're developing
585 your own client library.
586
587 Raises:
588 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
589 creation failed for any reason.
590 """
591 self._client_options = client_options
592 if isinstance(self._client_options, dict):
593 self._client_options = client_options_lib.from_dict(self._client_options)
594 if self._client_options is None:
595 self._client_options = client_options_lib.ClientOptions()
596 self._client_options = cast(
597 client_options_lib.ClientOptions, self._client_options
598 )
599
600 universe_domain_opt = getattr(self._client_options, "universe_domain", None)
601
602 (
603 self._use_client_cert,
604 self._use_mtls_endpoint,
605 self._universe_domain_env,
606 ) = MetricsServiceV2Client._read_environment_variables()
607 self._client_cert_source = MetricsServiceV2Client._get_client_cert_source(
608 self._client_options.client_cert_source, self._use_client_cert
609 )
610 self._universe_domain = MetricsServiceV2Client._get_universe_domain(
611 universe_domain_opt, self._universe_domain_env
612 )
613 self._api_endpoint = None # updated below, depending on `transport`
614
615 # Initialize the universe domain validation.
616 self._is_universe_domain_valid = False
617
618 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
619 # Setup logging.
620 client_logging.initialize_logging()
621
622 api_key_value = getattr(self._client_options, "api_key", None)
623 if api_key_value and credentials:
624 raise ValueError(
625 "client_options.api_key and credentials are mutually exclusive"
626 )
627
628 # Save or instantiate the transport.
629 # Ordinarily, we provide the transport, but allowing a custom transport
630 # instance provides an extensibility point for unusual situations.
631 transport_provided = isinstance(transport, MetricsServiceV2Transport)
632 if transport_provided:
633 # transport is a MetricsServiceV2Transport instance.
634 if credentials or self._client_options.credentials_file or api_key_value:
635 raise ValueError(
636 "When providing a transport instance, "
637 "provide its credentials directly."
638 )
639 if self._client_options.scopes:
640 raise ValueError(
641 "When providing a transport instance, provide its scopes "
642 "directly."
643 )
644 self._transport = cast(MetricsServiceV2Transport, transport)
645 self._api_endpoint = self._transport.host
646
647 self._api_endpoint = (
648 self._api_endpoint
649 or MetricsServiceV2Client._get_api_endpoint(
650 self._client_options.api_endpoint,
651 self._client_cert_source,
652 self._universe_domain,
653 self._use_mtls_endpoint,
654 )
655 )
656
657 if not transport_provided:
658 import google.auth._default # type: ignore
659
660 if api_key_value and hasattr(
661 google.auth._default, "get_api_key_credentials"
662 ):
663 credentials = google.auth._default.get_api_key_credentials(
664 api_key_value
665 )
666
667 transport_init: Union[
668 Type[MetricsServiceV2Transport],
669 Callable[..., MetricsServiceV2Transport],
670 ] = (
671 MetricsServiceV2Client.get_transport_class(transport)
672 if isinstance(transport, str) or transport is None
673 else cast(Callable[..., MetricsServiceV2Transport], transport)
674 )
675 # initialize with the provided callable or the passed in class
676 self._transport = transport_init(
677 credentials=credentials,
678 credentials_file=self._client_options.credentials_file,
679 host=self._api_endpoint,
680 scopes=self._client_options.scopes,
681 client_cert_source_for_mtls=self._client_cert_source,
682 quota_project_id=self._client_options.quota_project_id,
683 client_info=client_info,
684 always_use_jwt_access=True,
685 api_audience=self._client_options.api_audience,
686 )
687
688 if "async" not in str(self._transport):
689 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
690 std_logging.DEBUG
691 ): # pragma: NO COVER
692 _LOGGER.debug(
693 "Created client `google.logging_v2.MetricsServiceV2Client`.",
694 extra={
695 "serviceName": "google.logging.v2.MetricsServiceV2",
696 "universeDomain": getattr(
697 self._transport._credentials, "universe_domain", ""
698 ),
699 "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
700 "credentialsInfo": getattr(
701 self.transport._credentials, "get_cred_info", lambda: None
702 )(),
703 }
704 if hasattr(self._transport, "_credentials")
705 else {
706 "serviceName": "google.logging.v2.MetricsServiceV2",
707 "credentialsType": None,
708 },
709 )
710
711 def list_log_metrics(
712 self,
713 request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None,
714 *,
715 parent: Optional[str] = None,
716 retry: OptionalRetry = gapic_v1.method.DEFAULT,
717 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
718 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
719 ) -> pagers.ListLogMetricsPager:
720 r"""Lists logs-based metrics.
721
722 .. code-block:: python
723
724 # This snippet has been automatically generated and should be regarded as a
725 # code template only.
726 # It will require modifications to work:
727 # - It may require correct/in-range values for request initialization.
728 # - It may require specifying regional endpoints when creating the service
729 # client as shown in:
730 # https://googleapis.dev/python/google-api-core/latest/client_options.html
731 from google.cloud import logging_v2
732
733 def sample_list_log_metrics():
734 # Create a client
735 client = logging_v2.MetricsServiceV2Client()
736
737 # Initialize request argument(s)
738 request = logging_v2.ListLogMetricsRequest(
739 parent="parent_value",
740 )
741
742 # Make the request
743 page_result = client.list_log_metrics(request=request)
744
745 # Handle the response
746 for response in page_result:
747 print(response)
748
749 Args:
750 request (Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]):
751 The request object. The parameters to ListLogMetrics.
752 parent (str):
753 Required. The name of the project containing the
754 metrics:
755
756 ::
757
758 "projects/[PROJECT_ID]"
759
760 This corresponds to the ``parent`` field
761 on the ``request`` instance; if ``request`` is provided, this
762 should not be set.
763 retry (google.api_core.retry.Retry): Designation of what errors, if any,
764 should be retried.
765 timeout (float): The timeout for this request.
766 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
767 sent along with the request as metadata. Normally, each value must be of type `str`,
768 but for metadata keys ending with the suffix `-bin`, the corresponding values must
769 be of type `bytes`.
770
771 Returns:
772 google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsPager:
773 Result returned from ListLogMetrics.
774
775 Iterating over this object will yield
776 results and resolve additional pages
777 automatically.
778
779 """
780 # Create or coerce a protobuf request object.
781 # - Quick check: If we got a request object, we should *not* have
782 # gotten any keyword arguments that map to the request.
783 flattened_params = [parent]
784 has_flattened_params = (
785 len([param for param in flattened_params if param is not None]) > 0
786 )
787 if request is not None and has_flattened_params:
788 raise ValueError(
789 "If the `request` argument is set, then none of "
790 "the individual field arguments should be set."
791 )
792
793 # - Use the request object if provided (there's no risk of modifying the input as
794 # there are no flattened fields), or create one.
795 if not isinstance(request, logging_metrics.ListLogMetricsRequest):
796 request = logging_metrics.ListLogMetricsRequest(request)
797 # If we have keyword arguments corresponding to fields on the
798 # request, apply these.
799 if parent is not None:
800 request.parent = parent
801
802 # Wrap the RPC method; this adds retry and timeout information,
803 # and friendly error handling.
804 rpc = self._transport._wrapped_methods[self._transport.list_log_metrics]
805
806 # Certain fields should be provided within the metadata header;
807 # add these here.
808 metadata = tuple(metadata) + (
809 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
810 )
811
812 # Validate the universe domain.
813 self._validate_universe_domain()
814
815 # Send the request.
816 response = rpc(
817 request,
818 retry=retry,
819 timeout=timeout,
820 metadata=metadata,
821 )
822
823 # This method is paged; wrap the response in a pager, which provides
824 # an `__iter__` convenience method.
825 response = pagers.ListLogMetricsPager(
826 method=rpc,
827 request=request,
828 response=response,
829 retry=retry,
830 timeout=timeout,
831 metadata=metadata,
832 )
833
834 # Done; return the response.
835 return response
836
837 def get_log_metric(
838 self,
839 request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None,
840 *,
841 metric_name: Optional[str] = None,
842 retry: OptionalRetry = gapic_v1.method.DEFAULT,
843 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
844 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
845 ) -> logging_metrics.LogMetric:
846 r"""Gets a logs-based metric.
847
848 .. code-block:: python
849
850 # This snippet has been automatically generated and should be regarded as a
851 # code template only.
852 # It will require modifications to work:
853 # - It may require correct/in-range values for request initialization.
854 # - It may require specifying regional endpoints when creating the service
855 # client as shown in:
856 # https://googleapis.dev/python/google-api-core/latest/client_options.html
857 from google.cloud import logging_v2
858
859 def sample_get_log_metric():
860 # Create a client
861 client = logging_v2.MetricsServiceV2Client()
862
863 # Initialize request argument(s)
864 request = logging_v2.GetLogMetricRequest(
865 metric_name="metric_name_value",
866 )
867
868 # Make the request
869 response = client.get_log_metric(request=request)
870
871 # Handle the response
872 print(response)
873
874 Args:
875 request (Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]):
876 The request object. The parameters to GetLogMetric.
877 metric_name (str):
878 Required. The resource name of the desired metric:
879
880 ::
881
882 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
883
884 This corresponds to the ``metric_name`` field
885 on the ``request`` instance; if ``request`` is provided, this
886 should not be set.
887 retry (google.api_core.retry.Retry): Designation of what errors, if any,
888 should be retried.
889 timeout (float): The timeout for this request.
890 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
891 sent along with the request as metadata. Normally, each value must be of type `str`,
892 but for metadata keys ending with the suffix `-bin`, the corresponding values must
893 be of type `bytes`.
894
895 Returns:
896 google.cloud.logging_v2.types.LogMetric:
897 Describes a logs-based metric. The
898 value of the metric is the number of log
899 entries that match a logs filter in a
900 given time interval.
901
902 Logs-based metrics can also be used to
903 extract values from logs and create a
904 distribution of the values. The
905 distribution records the statistics of
906 the extracted values along with an
907 optional histogram of the values as
908 specified by the bucket options.
909
910 """
911 # Create or coerce a protobuf request object.
912 # - Quick check: If we got a request object, we should *not* have
913 # gotten any keyword arguments that map to the request.
914 flattened_params = [metric_name]
915 has_flattened_params = (
916 len([param for param in flattened_params if param is not None]) > 0
917 )
918 if request is not None and has_flattened_params:
919 raise ValueError(
920 "If the `request` argument is set, then none of "
921 "the individual field arguments should be set."
922 )
923
924 # - Use the request object if provided (there's no risk of modifying the input as
925 # there are no flattened fields), or create one.
926 if not isinstance(request, logging_metrics.GetLogMetricRequest):
927 request = logging_metrics.GetLogMetricRequest(request)
928 # If we have keyword arguments corresponding to fields on the
929 # request, apply these.
930 if metric_name is not None:
931 request.metric_name = metric_name
932
933 # Wrap the RPC method; this adds retry and timeout information,
934 # and friendly error handling.
935 rpc = self._transport._wrapped_methods[self._transport.get_log_metric]
936
937 # Certain fields should be provided within the metadata header;
938 # add these here.
939 metadata = tuple(metadata) + (
940 gapic_v1.routing_header.to_grpc_metadata(
941 (("metric_name", request.metric_name),)
942 ),
943 )
944
945 # Validate the universe domain.
946 self._validate_universe_domain()
947
948 # Send the request.
949 response = rpc(
950 request,
951 retry=retry,
952 timeout=timeout,
953 metadata=metadata,
954 )
955
956 # Done; return the response.
957 return response
958
959 def create_log_metric(
960 self,
961 request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None,
962 *,
963 parent: Optional[str] = None,
964 metric: Optional[logging_metrics.LogMetric] = None,
965 retry: OptionalRetry = gapic_v1.method.DEFAULT,
966 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
967 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
968 ) -> logging_metrics.LogMetric:
969 r"""Creates a logs-based metric.
970
971 .. code-block:: python
972
973 # This snippet has been automatically generated and should be regarded as a
974 # code template only.
975 # It will require modifications to work:
976 # - It may require correct/in-range values for request initialization.
977 # - It may require specifying regional endpoints when creating the service
978 # client as shown in:
979 # https://googleapis.dev/python/google-api-core/latest/client_options.html
980 from google.cloud import logging_v2
981
982 def sample_create_log_metric():
983 # Create a client
984 client = logging_v2.MetricsServiceV2Client()
985
986 # Initialize request argument(s)
987 metric = logging_v2.LogMetric()
988 metric.name = "name_value"
989 metric.filter = "filter_value"
990
991 request = logging_v2.CreateLogMetricRequest(
992 parent="parent_value",
993 metric=metric,
994 )
995
996 # Make the request
997 response = client.create_log_metric(request=request)
998
999 # Handle the response
1000 print(response)
1001
1002 Args:
1003 request (Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]):
1004 The request object. The parameters to CreateLogMetric.
1005 parent (str):
1006 Required. The resource name of the project in which to
1007 create the metric:
1008
1009 ::
1010
1011 "projects/[PROJECT_ID]"
1012
1013 The new metric must be provided in the request.
1014
1015 This corresponds to the ``parent`` field
1016 on the ``request`` instance; if ``request`` is provided, this
1017 should not be set.
1018 metric (google.cloud.logging_v2.types.LogMetric):
1019 Required. The new logs-based metric,
1020 which must not have an identifier that
1021 already exists.
1022
1023 This corresponds to the ``metric`` field
1024 on the ``request`` instance; if ``request`` is provided, this
1025 should not be set.
1026 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1027 should be retried.
1028 timeout (float): The timeout for this request.
1029 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1030 sent along with the request as metadata. Normally, each value must be of type `str`,
1031 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1032 be of type `bytes`.
1033
1034 Returns:
1035 google.cloud.logging_v2.types.LogMetric:
1036 Describes a logs-based metric. The
1037 value of the metric is the number of log
1038 entries that match a logs filter in a
1039 given time interval.
1040
1041 Logs-based metrics can also be used to
1042 extract values from logs and create a
1043 distribution of the values. The
1044 distribution records the statistics of
1045 the extracted values along with an
1046 optional histogram of the values as
1047 specified by the bucket options.
1048
1049 """
1050 # Create or coerce a protobuf request object.
1051 # - Quick check: If we got a request object, we should *not* have
1052 # gotten any keyword arguments that map to the request.
1053 flattened_params = [parent, metric]
1054 has_flattened_params = (
1055 len([param for param in flattened_params if param is not None]) > 0
1056 )
1057 if request is not None and has_flattened_params:
1058 raise ValueError(
1059 "If the `request` argument is set, then none of "
1060 "the individual field arguments should be set."
1061 )
1062
1063 # - Use the request object if provided (there's no risk of modifying the input as
1064 # there are no flattened fields), or create one.
1065 if not isinstance(request, logging_metrics.CreateLogMetricRequest):
1066 request = logging_metrics.CreateLogMetricRequest(request)
1067 # If we have keyword arguments corresponding to fields on the
1068 # request, apply these.
1069 if parent is not None:
1070 request.parent = parent
1071 if metric is not None:
1072 request.metric = metric
1073
1074 # Wrap the RPC method; this adds retry and timeout information,
1075 # and friendly error handling.
1076 rpc = self._transport._wrapped_methods[self._transport.create_log_metric]
1077
1078 # Certain fields should be provided within the metadata header;
1079 # add these here.
1080 metadata = tuple(metadata) + (
1081 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
1082 )
1083
1084 # Validate the universe domain.
1085 self._validate_universe_domain()
1086
1087 # Send the request.
1088 response = rpc(
1089 request,
1090 retry=retry,
1091 timeout=timeout,
1092 metadata=metadata,
1093 )
1094
1095 # Done; return the response.
1096 return response
1097
1098 def update_log_metric(
1099 self,
1100 request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None,
1101 *,
1102 metric_name: Optional[str] = None,
1103 metric: Optional[logging_metrics.LogMetric] = None,
1104 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1105 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1106 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1107 ) -> logging_metrics.LogMetric:
1108 r"""Creates or updates a logs-based metric.
1109
1110 .. code-block:: python
1111
1112 # This snippet has been automatically generated and should be regarded as a
1113 # code template only.
1114 # It will require modifications to work:
1115 # - It may require correct/in-range values for request initialization.
1116 # - It may require specifying regional endpoints when creating the service
1117 # client as shown in:
1118 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1119 from google.cloud import logging_v2
1120
1121 def sample_update_log_metric():
1122 # Create a client
1123 client = logging_v2.MetricsServiceV2Client()
1124
1125 # Initialize request argument(s)
1126 metric = logging_v2.LogMetric()
1127 metric.name = "name_value"
1128 metric.filter = "filter_value"
1129
1130 request = logging_v2.UpdateLogMetricRequest(
1131 metric_name="metric_name_value",
1132 metric=metric,
1133 )
1134
1135 # Make the request
1136 response = client.update_log_metric(request=request)
1137
1138 # Handle the response
1139 print(response)
1140
1141 Args:
1142 request (Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]):
1143 The request object. The parameters to UpdateLogMetric.
1144 metric_name (str):
1145 Required. The resource name of the metric to update:
1146
1147 ::
1148
1149 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
1150
1151 The updated metric must be provided in the request and
1152 it's ``name`` field must be the same as ``[METRIC_ID]``
1153 If the metric does not exist in ``[PROJECT_ID]``, then a
1154 new metric is created.
1155
1156 This corresponds to the ``metric_name`` field
1157 on the ``request`` instance; if ``request`` is provided, this
1158 should not be set.
1159 metric (google.cloud.logging_v2.types.LogMetric):
1160 Required. The updated metric.
1161 This corresponds to the ``metric`` field
1162 on the ``request`` instance; if ``request`` is provided, this
1163 should not be set.
1164 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1165 should be retried.
1166 timeout (float): The timeout for this request.
1167 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1168 sent along with the request as metadata. Normally, each value must be of type `str`,
1169 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1170 be of type `bytes`.
1171
1172 Returns:
1173 google.cloud.logging_v2.types.LogMetric:
1174 Describes a logs-based metric. The
1175 value of the metric is the number of log
1176 entries that match a logs filter in a
1177 given time interval.
1178
1179 Logs-based metrics can also be used to
1180 extract values from logs and create a
1181 distribution of the values. The
1182 distribution records the statistics of
1183 the extracted values along with an
1184 optional histogram of the values as
1185 specified by the bucket options.
1186
1187 """
1188 # Create or coerce a protobuf request object.
1189 # - Quick check: If we got a request object, we should *not* have
1190 # gotten any keyword arguments that map to the request.
1191 flattened_params = [metric_name, metric]
1192 has_flattened_params = (
1193 len([param for param in flattened_params if param is not None]) > 0
1194 )
1195 if request is not None and has_flattened_params:
1196 raise ValueError(
1197 "If the `request` argument is set, then none of "
1198 "the individual field arguments should be set."
1199 )
1200
1201 # - Use the request object if provided (there's no risk of modifying the input as
1202 # there are no flattened fields), or create one.
1203 if not isinstance(request, logging_metrics.UpdateLogMetricRequest):
1204 request = logging_metrics.UpdateLogMetricRequest(request)
1205 # If we have keyword arguments corresponding to fields on the
1206 # request, apply these.
1207 if metric_name is not None:
1208 request.metric_name = metric_name
1209 if metric is not None:
1210 request.metric = metric
1211
1212 # Wrap the RPC method; this adds retry and timeout information,
1213 # and friendly error handling.
1214 rpc = self._transport._wrapped_methods[self._transport.update_log_metric]
1215
1216 # Certain fields should be provided within the metadata header;
1217 # add these here.
1218 metadata = tuple(metadata) + (
1219 gapic_v1.routing_header.to_grpc_metadata(
1220 (("metric_name", request.metric_name),)
1221 ),
1222 )
1223
1224 # Validate the universe domain.
1225 self._validate_universe_domain()
1226
1227 # Send the request.
1228 response = rpc(
1229 request,
1230 retry=retry,
1231 timeout=timeout,
1232 metadata=metadata,
1233 )
1234
1235 # Done; return the response.
1236 return response
1237
1238 def delete_log_metric(
1239 self,
1240 request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None,
1241 *,
1242 metric_name: Optional[str] = None,
1243 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1244 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1245 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1246 ) -> None:
1247 r"""Deletes a logs-based metric.
1248
1249 .. code-block:: python
1250
1251 # This snippet has been automatically generated and should be regarded as a
1252 # code template only.
1253 # It will require modifications to work:
1254 # - It may require correct/in-range values for request initialization.
1255 # - It may require specifying regional endpoints when creating the service
1256 # client as shown in:
1257 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1258 from google.cloud import logging_v2
1259
1260 def sample_delete_log_metric():
1261 # Create a client
1262 client = logging_v2.MetricsServiceV2Client()
1263
1264 # Initialize request argument(s)
1265 request = logging_v2.DeleteLogMetricRequest(
1266 metric_name="metric_name_value",
1267 )
1268
1269 # Make the request
1270 client.delete_log_metric(request=request)
1271
1272 Args:
1273 request (Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]):
1274 The request object. The parameters to DeleteLogMetric.
1275 metric_name (str):
1276 Required. The resource name of the metric to delete:
1277
1278 ::
1279
1280 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
1281
1282 This corresponds to the ``metric_name`` field
1283 on the ``request`` instance; if ``request`` is provided, this
1284 should not be set.
1285 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1286 should be retried.
1287 timeout (float): The timeout for this request.
1288 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1289 sent along with the request as metadata. Normally, each value must be of type `str`,
1290 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1291 be of type `bytes`.
1292 """
1293 # Create or coerce a protobuf request object.
1294 # - Quick check: If we got a request object, we should *not* have
1295 # gotten any keyword arguments that map to the request.
1296 flattened_params = [metric_name]
1297 has_flattened_params = (
1298 len([param for param in flattened_params if param is not None]) > 0
1299 )
1300 if request is not None and has_flattened_params:
1301 raise ValueError(
1302 "If the `request` argument is set, then none of "
1303 "the individual field arguments should be set."
1304 )
1305
1306 # - Use the request object if provided (there's no risk of modifying the input as
1307 # there are no flattened fields), or create one.
1308 if not isinstance(request, logging_metrics.DeleteLogMetricRequest):
1309 request = logging_metrics.DeleteLogMetricRequest(request)
1310 # If we have keyword arguments corresponding to fields on the
1311 # request, apply these.
1312 if metric_name is not None:
1313 request.metric_name = metric_name
1314
1315 # Wrap the RPC method; this adds retry and timeout information,
1316 # and friendly error handling.
1317 rpc = self._transport._wrapped_methods[self._transport.delete_log_metric]
1318
1319 # Certain fields should be provided within the metadata header;
1320 # add these here.
1321 metadata = tuple(metadata) + (
1322 gapic_v1.routing_header.to_grpc_metadata(
1323 (("metric_name", request.metric_name),)
1324 ),
1325 )
1326
1327 # Validate the universe domain.
1328 self._validate_universe_domain()
1329
1330 # Send the request.
1331 rpc(
1332 request,
1333 retry=retry,
1334 timeout=timeout,
1335 metadata=metadata,
1336 )
1337
1338 def __enter__(self) -> "MetricsServiceV2Client":
1339 return self
1340
1341 def __exit__(self, type, value, traceback):
1342 """Releases underlying transport's resources.
1343
1344 .. warning::
1345 ONLY use as a context manager if the transport is NOT shared
1346 with other clients! Exiting the with block will CLOSE the transport
1347 and may cause errors in other clients!
1348 """
1349 self.transport.close()
1350
1351 def list_operations(
1352 self,
1353 request: Optional[operations_pb2.ListOperationsRequest] = None,
1354 *,
1355 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1356 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1357 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1358 ) -> operations_pb2.ListOperationsResponse:
1359 r"""Lists operations that match the specified filter in the request.
1360
1361 Args:
1362 request (:class:`~.operations_pb2.ListOperationsRequest`):
1363 The request object. Request message for
1364 `ListOperations` method.
1365 retry (google.api_core.retry.Retry): Designation of what errors,
1366 if any, should be retried.
1367 timeout (float): The timeout for this request.
1368 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1369 sent along with the request as metadata. Normally, each value must be of type `str`,
1370 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1371 be of type `bytes`.
1372 Returns:
1373 ~.operations_pb2.ListOperationsResponse:
1374 Response message for ``ListOperations`` method.
1375 """
1376 # Create or coerce a protobuf request object.
1377 # The request isn't a proto-plus wrapped type,
1378 # so it must be constructed via keyword expansion.
1379 if isinstance(request, dict):
1380 request = operations_pb2.ListOperationsRequest(**request)
1381
1382 # Wrap the RPC method; this adds retry and timeout information,
1383 # and friendly error handling.
1384 rpc = self._transport._wrapped_methods[self._transport.list_operations]
1385
1386 # Certain fields should be provided within the metadata header;
1387 # add these here.
1388 metadata = tuple(metadata) + (
1389 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1390 )
1391
1392 # Validate the universe domain.
1393 self._validate_universe_domain()
1394
1395 try:
1396 # Send the request.
1397 response = rpc(
1398 request,
1399 retry=retry,
1400 timeout=timeout,
1401 metadata=metadata,
1402 )
1403
1404 # Done; return the response.
1405 return response
1406 except core_exceptions.GoogleAPICallError as e:
1407 self._add_cred_info_for_auth_errors(e)
1408 raise e
1409
1410 def get_operation(
1411 self,
1412 request: Optional[operations_pb2.GetOperationRequest] = None,
1413 *,
1414 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1415 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1416 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1417 ) -> operations_pb2.Operation:
1418 r"""Gets the latest state of a long-running operation.
1419
1420 Args:
1421 request (:class:`~.operations_pb2.GetOperationRequest`):
1422 The request object. Request message for
1423 `GetOperation` method.
1424 retry (google.api_core.retry.Retry): Designation of what errors,
1425 if any, should be retried.
1426 timeout (float): The timeout for this request.
1427 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1428 sent along with the request as metadata. Normally, each value must be of type `str`,
1429 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1430 be of type `bytes`.
1431 Returns:
1432 ~.operations_pb2.Operation:
1433 An ``Operation`` object.
1434 """
1435 # Create or coerce a protobuf request object.
1436 # The request isn't a proto-plus wrapped type,
1437 # so it must be constructed via keyword expansion.
1438 if isinstance(request, dict):
1439 request = operations_pb2.GetOperationRequest(**request)
1440
1441 # Wrap the RPC method; this adds retry and timeout information,
1442 # and friendly error handling.
1443 rpc = self._transport._wrapped_methods[self._transport.get_operation]
1444
1445 # Certain fields should be provided within the metadata header;
1446 # add these here.
1447 metadata = tuple(metadata) + (
1448 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1449 )
1450
1451 # Validate the universe domain.
1452 self._validate_universe_domain()
1453
1454 try:
1455 # Send the request.
1456 response = rpc(
1457 request,
1458 retry=retry,
1459 timeout=timeout,
1460 metadata=metadata,
1461 )
1462
1463 # Done; return the response.
1464 return response
1465 except core_exceptions.GoogleAPICallError as e:
1466 self._add_cred_info_for_auth_errors(e)
1467 raise e
1468
1469 def cancel_operation(
1470 self,
1471 request: Optional[operations_pb2.CancelOperationRequest] = None,
1472 *,
1473 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1474 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1475 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1476 ) -> None:
1477 r"""Starts asynchronous cancellation on a long-running operation.
1478
1479 The server makes a best effort to cancel the operation, but success
1480 is not guaranteed. If the server doesn't support this method, it returns
1481 `google.rpc.Code.UNIMPLEMENTED`.
1482
1483 Args:
1484 request (:class:`~.operations_pb2.CancelOperationRequest`):
1485 The request object. Request message for
1486 `CancelOperation` method.
1487 retry (google.api_core.retry.Retry): Designation of what errors,
1488 if any, should be retried.
1489 timeout (float): The timeout for this request.
1490 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1491 sent along with the request as metadata. Normally, each value must be of type `str`,
1492 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1493 be of type `bytes`.
1494 Returns:
1495 None
1496 """
1497 # Create or coerce a protobuf request object.
1498 # The request isn't a proto-plus wrapped type,
1499 # so it must be constructed via keyword expansion.
1500 if isinstance(request, dict):
1501 request = operations_pb2.CancelOperationRequest(**request)
1502
1503 # Wrap the RPC method; this adds retry and timeout information,
1504 # and friendly error handling.
1505 rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
1506
1507 # Certain fields should be provided within the metadata header;
1508 # add these here.
1509 metadata = tuple(metadata) + (
1510 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1511 )
1512
1513 # Validate the universe domain.
1514 self._validate_universe_domain()
1515
1516 # Send the request.
1517 rpc(
1518 request,
1519 retry=retry,
1520 timeout=timeout,
1521 metadata=metadata,
1522 )
1523
1524
1525DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1526 gapic_version=package_version.__version__
1527)
1528
1529
1530__all__ = ("MetricsServiceV2Client",)