1# -*- coding: utf-8 -*-
2# Copyright 2023 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
17import functools
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Sequence,
26 Tuple,
27 Type,
28 Union,
29)
30
31from google.cloud.logging_v2 import gapic_version as package_version
32
33from google.api_core.client_options import ClientOptions
34from google.api_core import exceptions as core_exceptions
35from google.api_core import gapic_v1
36from google.api_core import retry as retries
37from google.auth import credentials as ga_credentials # type: ignore
38from google.oauth2 import service_account # type: ignore
39
40try:
41 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
42except AttributeError: # pragma: NO COVER
43 OptionalRetry = Union[retries.Retry, object] # type: ignore
44
45from google.api import distribution_pb2 # type: ignore
46from google.api import metric_pb2 # type: ignore
47from google.cloud.logging_v2.services.metrics_service_v2 import pagers
48from google.cloud.logging_v2.types import logging_metrics
49from google.longrunning import operations_pb2 # type: ignore
50from google.protobuf import timestamp_pb2 # type: ignore
51from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO
52from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport
53from .client import MetricsServiceV2Client
54
55
56class MetricsServiceV2AsyncClient:
57 """Service for configuring logs-based metrics."""
58
59 _client: MetricsServiceV2Client
60
61 DEFAULT_ENDPOINT = MetricsServiceV2Client.DEFAULT_ENDPOINT
62 DEFAULT_MTLS_ENDPOINT = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT
63
64 log_metric_path = staticmethod(MetricsServiceV2Client.log_metric_path)
65 parse_log_metric_path = staticmethod(MetricsServiceV2Client.parse_log_metric_path)
66 common_billing_account_path = staticmethod(
67 MetricsServiceV2Client.common_billing_account_path
68 )
69 parse_common_billing_account_path = staticmethod(
70 MetricsServiceV2Client.parse_common_billing_account_path
71 )
72 common_folder_path = staticmethod(MetricsServiceV2Client.common_folder_path)
73 parse_common_folder_path = staticmethod(
74 MetricsServiceV2Client.parse_common_folder_path
75 )
76 common_organization_path = staticmethod(
77 MetricsServiceV2Client.common_organization_path
78 )
79 parse_common_organization_path = staticmethod(
80 MetricsServiceV2Client.parse_common_organization_path
81 )
82 common_project_path = staticmethod(MetricsServiceV2Client.common_project_path)
83 parse_common_project_path = staticmethod(
84 MetricsServiceV2Client.parse_common_project_path
85 )
86 common_location_path = staticmethod(MetricsServiceV2Client.common_location_path)
87 parse_common_location_path = staticmethod(
88 MetricsServiceV2Client.parse_common_location_path
89 )
90
91 @classmethod
92 def from_service_account_info(cls, info: dict, *args, **kwargs):
93 """Creates an instance of this client using the provided credentials
94 info.
95
96 Args:
97 info (dict): The service account private key info.
98 args: Additional arguments to pass to the constructor.
99 kwargs: Additional arguments to pass to the constructor.
100
101 Returns:
102 MetricsServiceV2AsyncClient: The constructed client.
103 """
104 return MetricsServiceV2Client.from_service_account_info.__func__(MetricsServiceV2AsyncClient, info, *args, **kwargs) # type: ignore
105
106 @classmethod
107 def from_service_account_file(cls, filename: str, *args, **kwargs):
108 """Creates an instance of this client using the provided credentials
109 file.
110
111 Args:
112 filename (str): The path to the service account private key json
113 file.
114 args: Additional arguments to pass to the constructor.
115 kwargs: Additional arguments to pass to the constructor.
116
117 Returns:
118 MetricsServiceV2AsyncClient: The constructed client.
119 """
120 return MetricsServiceV2Client.from_service_account_file.__func__(MetricsServiceV2AsyncClient, filename, *args, **kwargs) # type: ignore
121
122 from_service_account_json = from_service_account_file
123
124 @classmethod
125 def get_mtls_endpoint_and_cert_source(
126 cls, client_options: Optional[ClientOptions] = None
127 ):
128 """Return the API endpoint and client cert source for mutual TLS.
129
130 The client cert source is determined in the following order:
131 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
132 client cert source is None.
133 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
134 default client cert source exists, use the default one; otherwise the client cert
135 source is None.
136
137 The API endpoint is determined in the following order:
138 (1) if `client_options.api_endpoint` if provided, use the provided one.
139 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
140 default mTLS endpoint; if the environment variable is "never", use the default API
141 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
142 use the default API endpoint.
143
144 More details can be found at https://google.aip.dev/auth/4114.
145
146 Args:
147 client_options (google.api_core.client_options.ClientOptions): Custom options for the
148 client. Only the `api_endpoint` and `client_cert_source` properties may be used
149 in this method.
150
151 Returns:
152 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
153 client cert source to use.
154
155 Raises:
156 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
157 """
158 return MetricsServiceV2Client.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
159
160 @property
161 def transport(self) -> MetricsServiceV2Transport:
162 """Returns the transport used by the client instance.
163
164 Returns:
165 MetricsServiceV2Transport: The transport used by the client instance.
166 """
167 return self._client.transport
168
169 get_transport_class = functools.partial(
170 type(MetricsServiceV2Client).get_transport_class, type(MetricsServiceV2Client)
171 )
172
173 def __init__(
174 self,
175 *,
176 credentials: Optional[ga_credentials.Credentials] = None,
177 transport: Union[str, MetricsServiceV2Transport] = "grpc_asyncio",
178 client_options: Optional[ClientOptions] = None,
179 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
180 ) -> None:
181 """Instantiates the metrics service v2 client.
182
183 Args:
184 credentials (Optional[google.auth.credentials.Credentials]): The
185 authorization credentials to attach to requests. These
186 credentials identify the application to the service; if none
187 are specified, the client will attempt to ascertain the
188 credentials from the environment.
189 transport (Union[str, ~.MetricsServiceV2Transport]): The
190 transport to use. If set to None, a transport is chosen
191 automatically.
192 client_options (ClientOptions): Custom options for the client. It
193 won't take effect if a ``transport`` instance is provided.
194 (1) The ``api_endpoint`` property can be used to override the
195 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
196 environment variable can also be used to override the endpoint:
197 "always" (always use the default mTLS endpoint), "never" (always
198 use the default regular endpoint) and "auto" (auto switch to the
199 default mTLS endpoint if client certificate is present, this is
200 the default value). However, the ``api_endpoint`` property takes
201 precedence if provided.
202 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
203 is "true", then the ``client_cert_source`` property can be used
204 to provide client certificate for mutual TLS transport. If
205 not provided, the default SSL client certificate will be used if
206 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
207 set, no client certificate will be used.
208
209 Raises:
210 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
211 creation failed for any reason.
212 """
213 self._client = MetricsServiceV2Client(
214 credentials=credentials,
215 transport=transport,
216 client_options=client_options,
217 client_info=client_info,
218 )
219
220 async def list_log_metrics(
221 self,
222 request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None,
223 *,
224 parent: Optional[str] = None,
225 retry: OptionalRetry = gapic_v1.method.DEFAULT,
226 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
227 metadata: Sequence[Tuple[str, str]] = (),
228 ) -> pagers.ListLogMetricsAsyncPager:
229 r"""Lists logs-based metrics.
230
231 .. code-block:: python
232
233 # This snippet has been automatically generated and should be regarded as a
234 # code template only.
235 # It will require modifications to work:
236 # - It may require correct/in-range values for request initialization.
237 # - It may require specifying regional endpoints when creating the service
238 # client as shown in:
239 # https://googleapis.dev/python/google-api-core/latest/client_options.html
240 from google.cloud import logging_v2
241
242 async def sample_list_log_metrics():
243 # Create a client
244 client = logging_v2.MetricsServiceV2AsyncClient()
245
246 # Initialize request argument(s)
247 request = logging_v2.ListLogMetricsRequest(
248 parent="parent_value",
249 )
250
251 # Make the request
252 page_result = client.list_log_metrics(request=request)
253
254 # Handle the response
255 async for response in page_result:
256 print(response)
257
258 Args:
259 request (Optional[Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]]):
260 The request object. The parameters to ListLogMetrics.
261 parent (:class:`str`):
262 Required. The name of the project containing the
263 metrics:
264
265 ::
266
267 "projects/[PROJECT_ID]"
268
269 This corresponds to the ``parent`` field
270 on the ``request`` instance; if ``request`` is provided, this
271 should not be set.
272 retry (google.api_core.retry.Retry): Designation of what errors, if any,
273 should be retried.
274 timeout (float): The timeout for this request.
275 metadata (Sequence[Tuple[str, str]]): Strings which should be
276 sent along with the request as metadata.
277
278 Returns:
279 google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsAsyncPager:
280 Result returned from ListLogMetrics.
281
282 Iterating over this object will yield
283 results and resolve additional pages
284 automatically.
285
286 """
287 # Create or coerce a protobuf request object.
288 # Quick check: If we got a request object, we should *not* have
289 # gotten any keyword arguments that map to the request.
290 has_flattened_params = any([parent])
291 if request is not None and has_flattened_params:
292 raise ValueError(
293 "If the `request` argument is set, then none of "
294 "the individual field arguments should be set."
295 )
296
297 request = logging_metrics.ListLogMetricsRequest(request)
298
299 # If we have keyword arguments corresponding to fields on the
300 # request, apply these.
301 if parent is not None:
302 request.parent = parent
303
304 # Wrap the RPC method; this adds retry and timeout information,
305 # and friendly error handling.
306 rpc = gapic_v1.method_async.wrap_method(
307 self._client._transport.list_log_metrics,
308 default_retry=retries.Retry(
309 initial=0.1,
310 maximum=60.0,
311 multiplier=1.3,
312 predicate=retries.if_exception_type(
313 core_exceptions.DeadlineExceeded,
314 core_exceptions.InternalServerError,
315 core_exceptions.ServiceUnavailable,
316 ),
317 deadline=60.0,
318 ),
319 default_timeout=60.0,
320 client_info=DEFAULT_CLIENT_INFO,
321 )
322
323 # Certain fields should be provided within the metadata header;
324 # add these here.
325 metadata = tuple(metadata) + (
326 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
327 )
328
329 # Send the request.
330 response = await rpc(
331 request,
332 retry=retry,
333 timeout=timeout,
334 metadata=metadata,
335 )
336
337 # This method is paged; wrap the response in a pager, which provides
338 # an `__aiter__` convenience method.
339 response = pagers.ListLogMetricsAsyncPager(
340 method=rpc,
341 request=request,
342 response=response,
343 metadata=metadata,
344 )
345
346 # Done; return the response.
347 return response
348
349 async def get_log_metric(
350 self,
351 request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None,
352 *,
353 metric_name: Optional[str] = None,
354 retry: OptionalRetry = gapic_v1.method.DEFAULT,
355 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
356 metadata: Sequence[Tuple[str, str]] = (),
357 ) -> logging_metrics.LogMetric:
358 r"""Gets a logs-based metric.
359
360 .. code-block:: python
361
362 # This snippet has been automatically generated and should be regarded as a
363 # code template only.
364 # It will require modifications to work:
365 # - It may require correct/in-range values for request initialization.
366 # - It may require specifying regional endpoints when creating the service
367 # client as shown in:
368 # https://googleapis.dev/python/google-api-core/latest/client_options.html
369 from google.cloud import logging_v2
370
371 async def sample_get_log_metric():
372 # Create a client
373 client = logging_v2.MetricsServiceV2AsyncClient()
374
375 # Initialize request argument(s)
376 request = logging_v2.GetLogMetricRequest(
377 metric_name="metric_name_value",
378 )
379
380 # Make the request
381 response = await client.get_log_metric(request=request)
382
383 # Handle the response
384 print(response)
385
386 Args:
387 request (Optional[Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]]):
388 The request object. The parameters to GetLogMetric.
389 metric_name (:class:`str`):
390 Required. The resource name of the desired metric:
391
392 ::
393
394 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
395
396 This corresponds to the ``metric_name`` field
397 on the ``request`` instance; if ``request`` is provided, this
398 should not be set.
399 retry (google.api_core.retry.Retry): Designation of what errors, if any,
400 should be retried.
401 timeout (float): The timeout for this request.
402 metadata (Sequence[Tuple[str, str]]): Strings which should be
403 sent along with the request as metadata.
404
405 Returns:
406 google.cloud.logging_v2.types.LogMetric:
407 Describes a logs-based metric. The
408 value of the metric is the number of log
409 entries that match a logs filter in a
410 given time interval.
411
412 Logs-based metrics can also be used to
413 extract values from logs and create a
414 distribution of the values. The
415 distribution records the statistics of
416 the extracted values along with an
417 optional histogram of the values as
418 specified by the bucket options.
419
420 """
421 # Create or coerce a protobuf request object.
422 # Quick check: If we got a request object, we should *not* have
423 # gotten any keyword arguments that map to the request.
424 has_flattened_params = any([metric_name])
425 if request is not None and has_flattened_params:
426 raise ValueError(
427 "If the `request` argument is set, then none of "
428 "the individual field arguments should be set."
429 )
430
431 request = logging_metrics.GetLogMetricRequest(request)
432
433 # If we have keyword arguments corresponding to fields on the
434 # request, apply these.
435 if metric_name is not None:
436 request.metric_name = metric_name
437
438 # Wrap the RPC method; this adds retry and timeout information,
439 # and friendly error handling.
440 rpc = gapic_v1.method_async.wrap_method(
441 self._client._transport.get_log_metric,
442 default_retry=retries.Retry(
443 initial=0.1,
444 maximum=60.0,
445 multiplier=1.3,
446 predicate=retries.if_exception_type(
447 core_exceptions.DeadlineExceeded,
448 core_exceptions.InternalServerError,
449 core_exceptions.ServiceUnavailable,
450 ),
451 deadline=60.0,
452 ),
453 default_timeout=60.0,
454 client_info=DEFAULT_CLIENT_INFO,
455 )
456
457 # Certain fields should be provided within the metadata header;
458 # add these here.
459 metadata = tuple(metadata) + (
460 gapic_v1.routing_header.to_grpc_metadata(
461 (("metric_name", request.metric_name),)
462 ),
463 )
464
465 # Send the request.
466 response = await rpc(
467 request,
468 retry=retry,
469 timeout=timeout,
470 metadata=metadata,
471 )
472
473 # Done; return the response.
474 return response
475
476 async def create_log_metric(
477 self,
478 request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None,
479 *,
480 parent: Optional[str] = None,
481 metric: Optional[logging_metrics.LogMetric] = None,
482 retry: OptionalRetry = gapic_v1.method.DEFAULT,
483 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
484 metadata: Sequence[Tuple[str, str]] = (),
485 ) -> logging_metrics.LogMetric:
486 r"""Creates a logs-based metric.
487
488 .. code-block:: python
489
490 # This snippet has been automatically generated and should be regarded as a
491 # code template only.
492 # It will require modifications to work:
493 # - It may require correct/in-range values for request initialization.
494 # - It may require specifying regional endpoints when creating the service
495 # client as shown in:
496 # https://googleapis.dev/python/google-api-core/latest/client_options.html
497 from google.cloud import logging_v2
498
499 async def sample_create_log_metric():
500 # Create a client
501 client = logging_v2.MetricsServiceV2AsyncClient()
502
503 # Initialize request argument(s)
504 metric = logging_v2.LogMetric()
505 metric.name = "name_value"
506 metric.filter = "filter_value"
507
508 request = logging_v2.CreateLogMetricRequest(
509 parent="parent_value",
510 metric=metric,
511 )
512
513 # Make the request
514 response = await client.create_log_metric(request=request)
515
516 # Handle the response
517 print(response)
518
519 Args:
520 request (Optional[Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]]):
521 The request object. The parameters to CreateLogMetric.
522 parent (:class:`str`):
523 Required. The resource name of the project in which to
524 create the metric:
525
526 ::
527
528 "projects/[PROJECT_ID]"
529
530 The new metric must be provided in the request.
531
532 This corresponds to the ``parent`` field
533 on the ``request`` instance; if ``request`` is provided, this
534 should not be set.
535 metric (:class:`google.cloud.logging_v2.types.LogMetric`):
536 Required. The new logs-based metric,
537 which must not have an identifier that
538 already exists.
539
540 This corresponds to the ``metric`` field
541 on the ``request`` instance; if ``request`` is provided, this
542 should not be set.
543 retry (google.api_core.retry.Retry): Designation of what errors, if any,
544 should be retried.
545 timeout (float): The timeout for this request.
546 metadata (Sequence[Tuple[str, str]]): Strings which should be
547 sent along with the request as metadata.
548
549 Returns:
550 google.cloud.logging_v2.types.LogMetric:
551 Describes a logs-based metric. The
552 value of the metric is the number of log
553 entries that match a logs filter in a
554 given time interval.
555
556 Logs-based metrics can also be used to
557 extract values from logs and create a
558 distribution of the values. The
559 distribution records the statistics of
560 the extracted values along with an
561 optional histogram of the values as
562 specified by the bucket options.
563
564 """
565 # Create or coerce a protobuf request object.
566 # Quick check: If we got a request object, we should *not* have
567 # gotten any keyword arguments that map to the request.
568 has_flattened_params = any([parent, metric])
569 if request is not None and has_flattened_params:
570 raise ValueError(
571 "If the `request` argument is set, then none of "
572 "the individual field arguments should be set."
573 )
574
575 request = logging_metrics.CreateLogMetricRequest(request)
576
577 # If we have keyword arguments corresponding to fields on the
578 # request, apply these.
579 if parent is not None:
580 request.parent = parent
581 if metric is not None:
582 request.metric = metric
583
584 # Wrap the RPC method; this adds retry and timeout information,
585 # and friendly error handling.
586 rpc = gapic_v1.method_async.wrap_method(
587 self._client._transport.create_log_metric,
588 default_timeout=60.0,
589 client_info=DEFAULT_CLIENT_INFO,
590 )
591
592 # Certain fields should be provided within the metadata header;
593 # add these here.
594 metadata = tuple(metadata) + (
595 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
596 )
597
598 # Send the request.
599 response = await rpc(
600 request,
601 retry=retry,
602 timeout=timeout,
603 metadata=metadata,
604 )
605
606 # Done; return the response.
607 return response
608
609 async def update_log_metric(
610 self,
611 request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None,
612 *,
613 metric_name: Optional[str] = None,
614 metric: Optional[logging_metrics.LogMetric] = None,
615 retry: OptionalRetry = gapic_v1.method.DEFAULT,
616 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
617 metadata: Sequence[Tuple[str, str]] = (),
618 ) -> logging_metrics.LogMetric:
619 r"""Creates or updates a logs-based metric.
620
621 .. code-block:: python
622
623 # This snippet has been automatically generated and should be regarded as a
624 # code template only.
625 # It will require modifications to work:
626 # - It may require correct/in-range values for request initialization.
627 # - It may require specifying regional endpoints when creating the service
628 # client as shown in:
629 # https://googleapis.dev/python/google-api-core/latest/client_options.html
630 from google.cloud import logging_v2
631
632 async def sample_update_log_metric():
633 # Create a client
634 client = logging_v2.MetricsServiceV2AsyncClient()
635
636 # Initialize request argument(s)
637 metric = logging_v2.LogMetric()
638 metric.name = "name_value"
639 metric.filter = "filter_value"
640
641 request = logging_v2.UpdateLogMetricRequest(
642 metric_name="metric_name_value",
643 metric=metric,
644 )
645
646 # Make the request
647 response = await client.update_log_metric(request=request)
648
649 # Handle the response
650 print(response)
651
652 Args:
653 request (Optional[Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]]):
654 The request object. The parameters to UpdateLogMetric.
655 metric_name (:class:`str`):
656 Required. The resource name of the metric to update:
657
658 ::
659
660 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
661
662 The updated metric must be provided in the request and
663 it's ``name`` field must be the same as ``[METRIC_ID]``
664 If the metric does not exist in ``[PROJECT_ID]``, then a
665 new metric is created.
666
667 This corresponds to the ``metric_name`` field
668 on the ``request`` instance; if ``request`` is provided, this
669 should not be set.
670 metric (:class:`google.cloud.logging_v2.types.LogMetric`):
671 Required. The updated metric.
672 This corresponds to the ``metric`` field
673 on the ``request`` instance; if ``request`` is provided, this
674 should not be set.
675 retry (google.api_core.retry.Retry): Designation of what errors, if any,
676 should be retried.
677 timeout (float): The timeout for this request.
678 metadata (Sequence[Tuple[str, str]]): Strings which should be
679 sent along with the request as metadata.
680
681 Returns:
682 google.cloud.logging_v2.types.LogMetric:
683 Describes a logs-based metric. The
684 value of the metric is the number of log
685 entries that match a logs filter in a
686 given time interval.
687
688 Logs-based metrics can also be used to
689 extract values from logs and create a
690 distribution of the values. The
691 distribution records the statistics of
692 the extracted values along with an
693 optional histogram of the values as
694 specified by the bucket options.
695
696 """
697 # Create or coerce a protobuf request object.
698 # Quick check: If we got a request object, we should *not* have
699 # gotten any keyword arguments that map to the request.
700 has_flattened_params = any([metric_name, metric])
701 if request is not None and has_flattened_params:
702 raise ValueError(
703 "If the `request` argument is set, then none of "
704 "the individual field arguments should be set."
705 )
706
707 request = logging_metrics.UpdateLogMetricRequest(request)
708
709 # If we have keyword arguments corresponding to fields on the
710 # request, apply these.
711 if metric_name is not None:
712 request.metric_name = metric_name
713 if metric is not None:
714 request.metric = metric
715
716 # Wrap the RPC method; this adds retry and timeout information,
717 # and friendly error handling.
718 rpc = gapic_v1.method_async.wrap_method(
719 self._client._transport.update_log_metric,
720 default_retry=retries.Retry(
721 initial=0.1,
722 maximum=60.0,
723 multiplier=1.3,
724 predicate=retries.if_exception_type(
725 core_exceptions.DeadlineExceeded,
726 core_exceptions.InternalServerError,
727 core_exceptions.ServiceUnavailable,
728 ),
729 deadline=60.0,
730 ),
731 default_timeout=60.0,
732 client_info=DEFAULT_CLIENT_INFO,
733 )
734
735 # Certain fields should be provided within the metadata header;
736 # add these here.
737 metadata = tuple(metadata) + (
738 gapic_v1.routing_header.to_grpc_metadata(
739 (("metric_name", request.metric_name),)
740 ),
741 )
742
743 # Send the request.
744 response = await rpc(
745 request,
746 retry=retry,
747 timeout=timeout,
748 metadata=metadata,
749 )
750
751 # Done; return the response.
752 return response
753
754 async def delete_log_metric(
755 self,
756 request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None,
757 *,
758 metric_name: Optional[str] = None,
759 retry: OptionalRetry = gapic_v1.method.DEFAULT,
760 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
761 metadata: Sequence[Tuple[str, str]] = (),
762 ) -> None:
763 r"""Deletes a logs-based metric.
764
765 .. code-block:: python
766
767 # This snippet has been automatically generated and should be regarded as a
768 # code template only.
769 # It will require modifications to work:
770 # - It may require correct/in-range values for request initialization.
771 # - It may require specifying regional endpoints when creating the service
772 # client as shown in:
773 # https://googleapis.dev/python/google-api-core/latest/client_options.html
774 from google.cloud import logging_v2
775
776 async def sample_delete_log_metric():
777 # Create a client
778 client = logging_v2.MetricsServiceV2AsyncClient()
779
780 # Initialize request argument(s)
781 request = logging_v2.DeleteLogMetricRequest(
782 metric_name="metric_name_value",
783 )
784
785 # Make the request
786 await client.delete_log_metric(request=request)
787
788 Args:
789 request (Optional[Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]]):
790 The request object. The parameters to DeleteLogMetric.
791 metric_name (:class:`str`):
792 Required. The resource name of the metric to delete:
793
794 ::
795
796 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
797
798 This corresponds to the ``metric_name`` field
799 on the ``request`` instance; if ``request`` is provided, this
800 should not be set.
801 retry (google.api_core.retry.Retry): Designation of what errors, if any,
802 should be retried.
803 timeout (float): The timeout for this request.
804 metadata (Sequence[Tuple[str, str]]): Strings which should be
805 sent along with the request as metadata.
806 """
807 # Create or coerce a protobuf request object.
808 # Quick check: If we got a request object, we should *not* have
809 # gotten any keyword arguments that map to the request.
810 has_flattened_params = any([metric_name])
811 if request is not None and has_flattened_params:
812 raise ValueError(
813 "If the `request` argument is set, then none of "
814 "the individual field arguments should be set."
815 )
816
817 request = logging_metrics.DeleteLogMetricRequest(request)
818
819 # If we have keyword arguments corresponding to fields on the
820 # request, apply these.
821 if metric_name is not None:
822 request.metric_name = metric_name
823
824 # Wrap the RPC method; this adds retry and timeout information,
825 # and friendly error handling.
826 rpc = gapic_v1.method_async.wrap_method(
827 self._client._transport.delete_log_metric,
828 default_retry=retries.Retry(
829 initial=0.1,
830 maximum=60.0,
831 multiplier=1.3,
832 predicate=retries.if_exception_type(
833 core_exceptions.DeadlineExceeded,
834 core_exceptions.InternalServerError,
835 core_exceptions.ServiceUnavailable,
836 ),
837 deadline=60.0,
838 ),
839 default_timeout=60.0,
840 client_info=DEFAULT_CLIENT_INFO,
841 )
842
843 # Certain fields should be provided within the metadata header;
844 # add these here.
845 metadata = tuple(metadata) + (
846 gapic_v1.routing_header.to_grpc_metadata(
847 (("metric_name", request.metric_name),)
848 ),
849 )
850
851 # Send the request.
852 await rpc(
853 request,
854 retry=retry,
855 timeout=timeout,
856 metadata=metadata,
857 )
858
859 async def list_operations(
860 self,
861 request: Optional[operations_pb2.ListOperationsRequest] = None,
862 *,
863 retry: OptionalRetry = gapic_v1.method.DEFAULT,
864 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
865 metadata: Sequence[Tuple[str, str]] = (),
866 ) -> operations_pb2.ListOperationsResponse:
867 r"""Lists operations that match the specified filter in the request.
868
869 Args:
870 request (:class:`~.operations_pb2.ListOperationsRequest`):
871 The request object. Request message for
872 `ListOperations` method.
873 retry (google.api_core.retry.Retry): Designation of what errors,
874 if any, should be retried.
875 timeout (float): The timeout for this request.
876 metadata (Sequence[Tuple[str, str]]): Strings which should be
877 sent along with the request as metadata.
878 Returns:
879 ~.operations_pb2.ListOperationsResponse:
880 Response message for ``ListOperations`` method.
881 """
882 # Create or coerce a protobuf request object.
883 # The request isn't a proto-plus wrapped type,
884 # so it must be constructed via keyword expansion.
885 if isinstance(request, dict):
886 request = operations_pb2.ListOperationsRequest(**request)
887
888 # Wrap the RPC method; this adds retry and timeout information,
889 # and friendly error handling.
890 rpc = gapic_v1.method.wrap_method(
891 self._client._transport.list_operations,
892 default_timeout=None,
893 client_info=DEFAULT_CLIENT_INFO,
894 )
895
896 # Certain fields should be provided within the metadata header;
897 # add these here.
898 metadata = tuple(metadata) + (
899 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
900 )
901
902 # Send the request.
903 response = await rpc(
904 request,
905 retry=retry,
906 timeout=timeout,
907 metadata=metadata,
908 )
909
910 # Done; return the response.
911 return response
912
913 async def get_operation(
914 self,
915 request: Optional[operations_pb2.GetOperationRequest] = None,
916 *,
917 retry: OptionalRetry = gapic_v1.method.DEFAULT,
918 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
919 metadata: Sequence[Tuple[str, str]] = (),
920 ) -> operations_pb2.Operation:
921 r"""Gets the latest state of a long-running operation.
922
923 Args:
924 request (:class:`~.operations_pb2.GetOperationRequest`):
925 The request object. Request message for
926 `GetOperation` method.
927 retry (google.api_core.retry.Retry): Designation of what errors,
928 if any, should be retried.
929 timeout (float): The timeout for this request.
930 metadata (Sequence[Tuple[str, str]]): Strings which should be
931 sent along with the request as metadata.
932 Returns:
933 ~.operations_pb2.Operation:
934 An ``Operation`` object.
935 """
936 # Create or coerce a protobuf request object.
937 # The request isn't a proto-plus wrapped type,
938 # so it must be constructed via keyword expansion.
939 if isinstance(request, dict):
940 request = operations_pb2.GetOperationRequest(**request)
941
942 # Wrap the RPC method; this adds retry and timeout information,
943 # and friendly error handling.
944 rpc = gapic_v1.method.wrap_method(
945 self._client._transport.get_operation,
946 default_timeout=None,
947 client_info=DEFAULT_CLIENT_INFO,
948 )
949
950 # Certain fields should be provided within the metadata header;
951 # add these here.
952 metadata = tuple(metadata) + (
953 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
954 )
955
956 # Send the request.
957 response = await rpc(
958 request,
959 retry=retry,
960 timeout=timeout,
961 metadata=metadata,
962 )
963
964 # Done; return the response.
965 return response
966
967 async def cancel_operation(
968 self,
969 request: Optional[operations_pb2.CancelOperationRequest] = None,
970 *,
971 retry: OptionalRetry = gapic_v1.method.DEFAULT,
972 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
973 metadata: Sequence[Tuple[str, str]] = (),
974 ) -> None:
975 r"""Starts asynchronous cancellation on a long-running operation.
976
977 The server makes a best effort to cancel the operation, but success
978 is not guaranteed. If the server doesn't support this method, it returns
979 `google.rpc.Code.UNIMPLEMENTED`.
980
981 Args:
982 request (:class:`~.operations_pb2.CancelOperationRequest`):
983 The request object. Request message for
984 `CancelOperation` method.
985 retry (google.api_core.retry.Retry): Designation of what errors,
986 if any, should be retried.
987 timeout (float): The timeout for this request.
988 metadata (Sequence[Tuple[str, str]]): Strings which should be
989 sent along with the request as metadata.
990 Returns:
991 None
992 """
993 # Create or coerce a protobuf request object.
994 # The request isn't a proto-plus wrapped type,
995 # so it must be constructed via keyword expansion.
996 if isinstance(request, dict):
997 request = operations_pb2.CancelOperationRequest(**request)
998
999 # Wrap the RPC method; this adds retry and timeout information,
1000 # and friendly error handling.
1001 rpc = gapic_v1.method.wrap_method(
1002 self._client._transport.cancel_operation,
1003 default_timeout=None,
1004 client_info=DEFAULT_CLIENT_INFO,
1005 )
1006
1007 # Certain fields should be provided within the metadata header;
1008 # add these here.
1009 metadata = tuple(metadata) + (
1010 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1011 )
1012
1013 # Send the request.
1014 await rpc(
1015 request,
1016 retry=retry,
1017 timeout=timeout,
1018 metadata=metadata,
1019 )
1020
1021 async def __aenter__(self) -> "MetricsServiceV2AsyncClient":
1022 return self
1023
1024 async def __aexit__(self, exc_type, exc, tb):
1025 await self.transport.close()
1026
1027
1028DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1029 gapic_version=package_version.__version__
1030)
1031
1032
1033__all__ = ("MetricsServiceV2AsyncClient",)