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