1# -*- coding: utf-8 -*-
2# Copyright 2020 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 distutils import util
18import os
19import re
20from typing import Dict, Optional, Sequence, Tuple, Type, Union
21import pkg_resources
22
23from google.api_core import client_options as client_options_lib  # type: ignore
24from google.api_core import exceptions as core_exceptions  # type: ignore
25from google.api_core import gapic_v1  # type: ignore
26from google.api_core import retry as retries  # type: ignore
27from google.auth import credentials as ga_credentials  # type: ignore
28from google.auth.transport import mtls  # type: ignore
29from google.auth.transport.grpc import SslCredentials  # type: ignore
30from google.auth.exceptions import MutualTLSChannelError  # type: ignore
31from google.oauth2 import service_account  # type: ignore
32
33OptionalRetry = Union[retries.Retry, object]
34
35from google.api import distribution_pb2  # type: ignore
36from google.api import metric_pb2  # type: ignore
37from google.cloud.logging_v2.services.metrics_service_v2 import pagers
38from google.cloud.logging_v2.types import logging_metrics
39from google.protobuf import timestamp_pb2  # type: ignore
40from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO
41from .transports.grpc import MetricsServiceV2GrpcTransport
42from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport
43
44
45class MetricsServiceV2ClientMeta(type):
46    """Metaclass for the MetricsServiceV2 client.
47
48    This provides class-level methods for building and retrieving
49    support objects (e.g. transport) without polluting the client instance
50    objects.
51    """
52
53    _transport_registry = (
54        OrderedDict()
55    )  # type: Dict[str, Type[MetricsServiceV2Transport]]
56    _transport_registry["grpc"] = MetricsServiceV2GrpcTransport
57    _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport
58
59    def get_transport_class(cls, label: str = None,) -> Type[MetricsServiceV2Transport]:
60        """Returns an appropriate transport class.
61
62        Args:
63            label: The name of the desired transport. If none is
64                provided, then the first transport in the registry is used.
65
66        Returns:
67            The transport class to use.
68        """
69        # If a specific transport is requested, return that one.
70        if label:
71            return cls._transport_registry[label]
72
73        # No transport is requested; return the default (that is, the first one
74        # in the dictionary).
75        return next(iter(cls._transport_registry.values()))
76
77
78class MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta):
79    """Service for configuring logs-based metrics."""
80
81    @staticmethod
82    def _get_default_mtls_endpoint(api_endpoint):
83        """Converts api endpoint to mTLS endpoint.
84
85        Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
86        "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
87        Args:
88            api_endpoint (Optional[str]): the api endpoint to convert.
89        Returns:
90            str: converted mTLS api endpoint.
91        """
92        if not api_endpoint:
93            return api_endpoint
94
95        mtls_endpoint_re = re.compile(
96            r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
97        )
98
99        m = mtls_endpoint_re.match(api_endpoint)
100        name, mtls, sandbox, googledomain = m.groups()
101        if mtls or not googledomain:
102            return api_endpoint
103
104        if sandbox:
105            return api_endpoint.replace(
106                "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
107            )
108
109        return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
110
111    DEFAULT_ENDPOINT = "logging.googleapis.com"
112    DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__(  # type: ignore
113        DEFAULT_ENDPOINT
114    )
115
116    @classmethod
117    def from_service_account_info(cls, info: dict, *args, **kwargs):
118        """Creates an instance of this client using the provided credentials
119            info.
120
121        Args:
122            info (dict): The service account private key info.
123            args: Additional arguments to pass to the constructor.
124            kwargs: Additional arguments to pass to the constructor.
125
126        Returns:
127            MetricsServiceV2Client: The constructed client.
128        """
129        credentials = service_account.Credentials.from_service_account_info(info)
130        kwargs["credentials"] = credentials
131        return cls(*args, **kwargs)
132
133    @classmethod
134    def from_service_account_file(cls, filename: str, *args, **kwargs):
135        """Creates an instance of this client using the provided credentials
136            file.
137
138        Args:
139            filename (str): The path to the service account private key json
140                file.
141            args: Additional arguments to pass to the constructor.
142            kwargs: Additional arguments to pass to the constructor.
143
144        Returns:
145            MetricsServiceV2Client: The constructed client.
146        """
147        credentials = service_account.Credentials.from_service_account_file(filename)
148        kwargs["credentials"] = credentials
149        return cls(*args, **kwargs)
150
151    from_service_account_json = from_service_account_file
152
153    @property
154    def transport(self) -> MetricsServiceV2Transport:
155        """Returns the transport used by the client instance.
156
157        Returns:
158            MetricsServiceV2Transport: The transport used by the client
159                instance.
160        """
161        return self._transport
162
163    @staticmethod
164    def log_metric_path(project: str, metric: str,) -> str:
165        """Returns a fully-qualified log_metric string."""
166        return "projects/{project}/metrics/{metric}".format(
167            project=project, metric=metric,
168        )
169
170    @staticmethod
171    def parse_log_metric_path(path: str) -> Dict[str, str]:
172        """Parses a log_metric path into its component segments."""
173        m = re.match(r"^projects/(?P<project>.+?)/metrics/(?P<metric>.+?)$", path)
174        return m.groupdict() if m else {}
175
176    @staticmethod
177    def common_billing_account_path(billing_account: str,) -> str:
178        """Returns a fully-qualified billing_account string."""
179        return "billingAccounts/{billing_account}".format(
180            billing_account=billing_account,
181        )
182
183    @staticmethod
184    def parse_common_billing_account_path(path: str) -> Dict[str, str]:
185        """Parse a billing_account path into its component segments."""
186        m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
187        return m.groupdict() if m else {}
188
189    @staticmethod
190    def common_folder_path(folder: str,) -> str:
191        """Returns a fully-qualified folder string."""
192        return "folders/{folder}".format(folder=folder,)
193
194    @staticmethod
195    def parse_common_folder_path(path: str) -> Dict[str, str]:
196        """Parse a folder path into its component segments."""
197        m = re.match(r"^folders/(?P<folder>.+?)$", path)
198        return m.groupdict() if m else {}
199
200    @staticmethod
201    def common_organization_path(organization: str,) -> str:
202        """Returns a fully-qualified organization string."""
203        return "organizations/{organization}".format(organization=organization,)
204
205    @staticmethod
206    def parse_common_organization_path(path: str) -> Dict[str, str]:
207        """Parse a organization path into its component segments."""
208        m = re.match(r"^organizations/(?P<organization>.+?)$", path)
209        return m.groupdict() if m else {}
210
211    @staticmethod
212    def common_project_path(project: str,) -> str:
213        """Returns a fully-qualified project string."""
214        return "projects/{project}".format(project=project,)
215
216    @staticmethod
217    def parse_common_project_path(path: str) -> Dict[str, str]:
218        """Parse a project path into its component segments."""
219        m = re.match(r"^projects/(?P<project>.+?)$", path)
220        return m.groupdict() if m else {}
221
222    @staticmethod
223    def common_location_path(project: str, location: str,) -> str:
224        """Returns a fully-qualified location string."""
225        return "projects/{project}/locations/{location}".format(
226            project=project, location=location,
227        )
228
229    @staticmethod
230    def parse_common_location_path(path: str) -> Dict[str, str]:
231        """Parse a location path into its component segments."""
232        m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
233        return m.groupdict() if m else {}
234
235    def __init__(
236        self,
237        *,
238        credentials: Optional[ga_credentials.Credentials] = None,
239        transport: Union[str, MetricsServiceV2Transport, None] = None,
240        client_options: Optional[client_options_lib.ClientOptions] = None,
241        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
242    ) -> None:
243        """Instantiates the metrics service v2 client.
244
245        Args:
246            credentials (Optional[google.auth.credentials.Credentials]): The
247                authorization credentials to attach to requests. These
248                credentials identify the application to the service; if none
249                are specified, the client will attempt to ascertain the
250                credentials from the environment.
251            transport (Union[str, MetricsServiceV2Transport]): The
252                transport to use. If set to None, a transport is chosen
253                automatically.
254            client_options (google.api_core.client_options.ClientOptions): Custom options for the
255                client. It won't take effect if a ``transport`` instance is provided.
256                (1) The ``api_endpoint`` property can be used to override the
257                default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
258                environment variable can also be used to override the endpoint:
259                "always" (always use the default mTLS endpoint), "never" (always
260                use the default regular endpoint) and "auto" (auto switch to the
261                default mTLS endpoint if client certificate is present, this is
262                the default value). However, the ``api_endpoint`` property takes
263                precedence if provided.
264                (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
265                is "true", then the ``client_cert_source`` property can be used
266                to provide client certificate for mutual TLS transport. If
267                not provided, the default SSL client certificate will be used if
268                present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
269                set, no client certificate will be used.
270            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
271                The client info used to send a user-agent string along with
272                API requests. If ``None``, then default info will be used.
273                Generally, you only need to set this if you're developing
274                your own client library.
275
276        Raises:
277            google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
278                creation failed for any reason.
279        """
280        if isinstance(client_options, dict):
281            client_options = client_options_lib.from_dict(client_options)
282        if client_options is None:
283            client_options = client_options_lib.ClientOptions()
284
285        # Create SSL credentials for mutual TLS if needed.
286        use_client_cert = bool(
287            util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
288        )
289
290        client_cert_source_func = None
291        is_mtls = False
292        if use_client_cert:
293            if client_options.client_cert_source:
294                is_mtls = True
295                client_cert_source_func = client_options.client_cert_source
296            else:
297                is_mtls = mtls.has_default_client_cert_source()
298                if is_mtls:
299                    client_cert_source_func = mtls.default_client_cert_source()
300                else:
301                    client_cert_source_func = None
302
303        # Figure out which api endpoint to use.
304        if client_options.api_endpoint is not None:
305            api_endpoint = client_options.api_endpoint
306        else:
307            use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
308            if use_mtls_env == "never":
309                api_endpoint = self.DEFAULT_ENDPOINT
310            elif use_mtls_env == "always":
311                api_endpoint = self.DEFAULT_MTLS_ENDPOINT
312            elif use_mtls_env == "auto":
313                if is_mtls:
314                    api_endpoint = self.DEFAULT_MTLS_ENDPOINT
315                else:
316                    api_endpoint = self.DEFAULT_ENDPOINT
317            else:
318                raise MutualTLSChannelError(
319                    "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
320                    "values: never, auto, always"
321                )
322
323        # Save or instantiate the transport.
324        # Ordinarily, we provide the transport, but allowing a custom transport
325        # instance provides an extensibility point for unusual situations.
326        if isinstance(transport, MetricsServiceV2Transport):
327            # transport is a MetricsServiceV2Transport instance.
328            if credentials or client_options.credentials_file:
329                raise ValueError(
330                    "When providing a transport instance, "
331                    "provide its credentials directly."
332                )
333            if client_options.scopes:
334                raise ValueError(
335                    "When providing a transport instance, provide its scopes "
336                    "directly."
337                )
338            self._transport = transport
339        else:
340            Transport = type(self).get_transport_class(transport)
341            self._transport = Transport(
342                credentials=credentials,
343                credentials_file=client_options.credentials_file,
344                host=api_endpoint,
345                scopes=client_options.scopes,
346                client_cert_source_for_mtls=client_cert_source_func,
347                quota_project_id=client_options.quota_project_id,
348                client_info=client_info,
349                always_use_jwt_access=True,
350            )
351
352    def list_log_metrics(
353        self,
354        request: Union[logging_metrics.ListLogMetricsRequest, dict] = None,
355        *,
356        parent: str = None,
357        retry: OptionalRetry = gapic_v1.method.DEFAULT,
358        timeout: float = None,
359        metadata: Sequence[Tuple[str, str]] = (),
360    ) -> pagers.ListLogMetricsPager:
361        r"""Lists logs-based metrics.
362
363        Args:
364            request (Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]):
365                The request object. The parameters to ListLogMetrics.
366            parent (str):
367                Required. The name of the project containing the
368                metrics:
369
370                ::
371
372                    "projects/[PROJECT_ID]"
373
374                This corresponds to the ``parent`` field
375                on the ``request`` instance; if ``request`` is provided, this
376                should not be set.
377            retry (google.api_core.retry.Retry): Designation of what errors, if any,
378                should be retried.
379            timeout (float): The timeout for this request.
380            metadata (Sequence[Tuple[str, str]]): Strings which should be
381                sent along with the request as metadata.
382
383        Returns:
384            google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsPager:
385                Result returned from ListLogMetrics.
386                Iterating over this object will yield
387                results and resolve additional pages
388                automatically.
389
390        """
391        # Create or coerce a protobuf request object.
392        # Sanity check: If we got a request object, we should *not* have
393        # gotten any keyword arguments that map to the request.
394        has_flattened_params = any([parent])
395        if request is not None and has_flattened_params:
396            raise ValueError(
397                "If the `request` argument is set, then none of "
398                "the individual field arguments should be set."
399            )
400
401        # Minor optimization to avoid making a copy if the user passes
402        # in a logging_metrics.ListLogMetricsRequest.
403        # There's no risk of modifying the input as we've already verified
404        # there are no flattened fields.
405        if not isinstance(request, logging_metrics.ListLogMetricsRequest):
406            request = logging_metrics.ListLogMetricsRequest(request)
407            # If we have keyword arguments corresponding to fields on the
408            # request, apply these.
409            if parent is not None:
410                request.parent = parent
411
412        # Wrap the RPC method; this adds retry and timeout information,
413        # and friendly error handling.
414        rpc = self._transport._wrapped_methods[self._transport.list_log_metrics]
415
416        # Certain fields should be provided within the metadata header;
417        # add these here.
418        metadata = tuple(metadata) + (
419            gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
420        )
421
422        # Send the request.
423        response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
424
425        # This method is paged; wrap the response in a pager, which provides
426        # an `__iter__` convenience method.
427        response = pagers.ListLogMetricsPager(
428            method=rpc, request=request, response=response, metadata=metadata,
429        )
430
431        # Done; return the response.
432        return response
433
434    def get_log_metric(
435        self,
436        request: Union[logging_metrics.GetLogMetricRequest, dict] = None,
437        *,
438        metric_name: str = None,
439        retry: OptionalRetry = gapic_v1.method.DEFAULT,
440        timeout: float = None,
441        metadata: Sequence[Tuple[str, str]] = (),
442    ) -> logging_metrics.LogMetric:
443        r"""Gets a logs-based metric.
444
445        Args:
446            request (Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]):
447                The request object. The parameters to GetLogMetric.
448            metric_name (str):
449                Required. The resource name of the desired metric:
450
451                ::
452
453                    "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
454
455                This corresponds to the ``metric_name`` field
456                on the ``request`` instance; if ``request`` is provided, this
457                should not be set.
458            retry (google.api_core.retry.Retry): Designation of what errors, if any,
459                should be retried.
460            timeout (float): The timeout for this request.
461            metadata (Sequence[Tuple[str, str]]): Strings which should be
462                sent along with the request as metadata.
463
464        Returns:
465            google.cloud.logging_v2.types.LogMetric:
466                Describes a logs-based metric. The
467                value of the metric is the number of log
468                entries that match a logs filter in a
469                given time interval.
470                Logs-based metrics can also be used to
471                extract values from logs and create a
472                distribution of the values. The
473                distribution records the statistics of
474                the extracted values along with an
475                optional histogram of the values as
476                specified by the bucket options.
477
478        """
479        # Create or coerce a protobuf request object.
480        # Sanity check: If we got a request object, we should *not* have
481        # gotten any keyword arguments that map to the request.
482        has_flattened_params = any([metric_name])
483        if request is not None and has_flattened_params:
484            raise ValueError(
485                "If the `request` argument is set, then none of "
486                "the individual field arguments should be set."
487            )
488
489        # Minor optimization to avoid making a copy if the user passes
490        # in a logging_metrics.GetLogMetricRequest.
491        # There's no risk of modifying the input as we've already verified
492        # there are no flattened fields.
493        if not isinstance(request, logging_metrics.GetLogMetricRequest):
494            request = logging_metrics.GetLogMetricRequest(request)
495            # If we have keyword arguments corresponding to fields on the
496            # request, apply these.
497            if metric_name is not None:
498                request.metric_name = metric_name
499
500        # Wrap the RPC method; this adds retry and timeout information,
501        # and friendly error handling.
502        rpc = self._transport._wrapped_methods[self._transport.get_log_metric]
503
504        # Certain fields should be provided within the metadata header;
505        # add these here.
506        metadata = tuple(metadata) + (
507            gapic_v1.routing_header.to_grpc_metadata(
508                (("metric_name", request.metric_name),)
509            ),
510        )
511
512        # Send the request.
513        response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
514
515        # Done; return the response.
516        return response
517
518    def create_log_metric(
519        self,
520        request: Union[logging_metrics.CreateLogMetricRequest, dict] = None,
521        *,
522        parent: str = None,
523        metric: logging_metrics.LogMetric = None,
524        retry: OptionalRetry = gapic_v1.method.DEFAULT,
525        timeout: float = None,
526        metadata: Sequence[Tuple[str, str]] = (),
527    ) -> logging_metrics.LogMetric:
528        r"""Creates a logs-based metric.
529
530        Args:
531            request (Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]):
532                The request object. The parameters to CreateLogMetric.
533            parent (str):
534                Required. The resource name of the project in which to
535                create the metric:
536
537                ::
538
539                    "projects/[PROJECT_ID]"
540
541                The new metric must be provided in the request.
542
543                This corresponds to the ``parent`` field
544                on the ``request`` instance; if ``request`` is provided, this
545                should not be set.
546            metric (google.cloud.logging_v2.types.LogMetric):
547                Required. The new logs-based metric,
548                which must not have an identifier that
549                already exists.
550
551                This corresponds to the ``metric`` field
552                on the ``request`` instance; if ``request`` is provided, this
553                should not be set.
554            retry (google.api_core.retry.Retry): Designation of what errors, if any,
555                should be retried.
556            timeout (float): The timeout for this request.
557            metadata (Sequence[Tuple[str, str]]): Strings which should be
558                sent along with the request as metadata.
559
560        Returns:
561            google.cloud.logging_v2.types.LogMetric:
562                Describes a logs-based metric. The
563                value of the metric is the number of log
564                entries that match a logs filter in a
565                given time interval.
566                Logs-based metrics can also be used to
567                extract values from logs and create a
568                distribution of the values. The
569                distribution records the statistics of
570                the extracted values along with an
571                optional histogram of the values as
572                specified by the bucket options.
573
574        """
575        # Create or coerce a protobuf request object.
576        # Sanity check: If we got a request object, we should *not* have
577        # gotten any keyword arguments that map to the request.
578        has_flattened_params = any([parent, metric])
579        if request is not None and has_flattened_params:
580            raise ValueError(
581                "If the `request` argument is set, then none of "
582                "the individual field arguments should be set."
583            )
584
585        # Minor optimization to avoid making a copy if the user passes
586        # in a logging_metrics.CreateLogMetricRequest.
587        # There's no risk of modifying the input as we've already verified
588        # there are no flattened fields.
589        if not isinstance(request, logging_metrics.CreateLogMetricRequest):
590            request = logging_metrics.CreateLogMetricRequest(request)
591            # If we have keyword arguments corresponding to fields on the
592            # request, apply these.
593            if parent is not None:
594                request.parent = parent
595            if metric is not None:
596                request.metric = metric
597
598        # Wrap the RPC method; this adds retry and timeout information,
599        # and friendly error handling.
600        rpc = self._transport._wrapped_methods[self._transport.create_log_metric]
601
602        # Certain fields should be provided within the metadata header;
603        # add these here.
604        metadata = tuple(metadata) + (
605            gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
606        )
607
608        # Send the request.
609        response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
610
611        # Done; return the response.
612        return response
613
614    def update_log_metric(
615        self,
616        request: Union[logging_metrics.UpdateLogMetricRequest, dict] = None,
617        *,
618        metric_name: str = None,
619        metric: logging_metrics.LogMetric = None,
620        retry: OptionalRetry = gapic_v1.method.DEFAULT,
621        timeout: float = None,
622        metadata: Sequence[Tuple[str, str]] = (),
623    ) -> logging_metrics.LogMetric:
624        r"""Creates or updates a logs-based metric.
625
626        Args:
627            request (Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]):
628                The request object. The parameters to UpdateLogMetric.
629            metric_name (str):
630                Required. The resource name of the metric to update:
631
632                ::
633
634                    "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
635
636                The updated metric must be provided in the request and
637                it's ``name`` field must be the same as ``[METRIC_ID]``
638                If the metric does not exist in ``[PROJECT_ID]``, then a
639                new metric is created.
640
641                This corresponds to the ``metric_name`` field
642                on the ``request`` instance; if ``request`` is provided, this
643                should not be set.
644            metric (google.cloud.logging_v2.types.LogMetric):
645                Required. The updated metric.
646                This corresponds to the ``metric`` field
647                on the ``request`` instance; if ``request`` is provided, this
648                should not be set.
649            retry (google.api_core.retry.Retry): Designation of what errors, if any,
650                should be retried.
651            timeout (float): The timeout for this request.
652            metadata (Sequence[Tuple[str, str]]): Strings which should be
653                sent along with the request as metadata.
654
655        Returns:
656            google.cloud.logging_v2.types.LogMetric:
657                Describes a logs-based metric. The
658                value of the metric is the number of log
659                entries that match a logs filter in a
660                given time interval.
661                Logs-based metrics can also be used to
662                extract values from logs and create a
663                distribution of the values. The
664                distribution records the statistics of
665                the extracted values along with an
666                optional histogram of the values as
667                specified by the bucket options.
668
669        """
670        # Create or coerce a protobuf request object.
671        # Sanity check: If we got a request object, we should *not* have
672        # gotten any keyword arguments that map to the request.
673        has_flattened_params = any([metric_name, metric])
674        if request is not None and has_flattened_params:
675            raise ValueError(
676                "If the `request` argument is set, then none of "
677                "the individual field arguments should be set."
678            )
679
680        # Minor optimization to avoid making a copy if the user passes
681        # in a logging_metrics.UpdateLogMetricRequest.
682        # There's no risk of modifying the input as we've already verified
683        # there are no flattened fields.
684        if not isinstance(request, logging_metrics.UpdateLogMetricRequest):
685            request = logging_metrics.UpdateLogMetricRequest(request)
686            # If we have keyword arguments corresponding to fields on the
687            # request, apply these.
688            if metric_name is not None:
689                request.metric_name = metric_name
690            if metric is not None:
691                request.metric = metric
692
693        # Wrap the RPC method; this adds retry and timeout information,
694        # and friendly error handling.
695        rpc = self._transport._wrapped_methods[self._transport.update_log_metric]
696
697        # Certain fields should be provided within the metadata header;
698        # add these here.
699        metadata = tuple(metadata) + (
700            gapic_v1.routing_header.to_grpc_metadata(
701                (("metric_name", request.metric_name),)
702            ),
703        )
704
705        # Send the request.
706        response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
707
708        # Done; return the response.
709        return response
710
711    def delete_log_metric(
712        self,
713        request: Union[logging_metrics.DeleteLogMetricRequest, dict] = None,
714        *,
715        metric_name: str = None,
716        retry: OptionalRetry = gapic_v1.method.DEFAULT,
717        timeout: float = None,
718        metadata: Sequence[Tuple[str, str]] = (),
719    ) -> None:
720        r"""Deletes a logs-based metric.
721
722        Args:
723            request (Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]):
724                The request object. The parameters to DeleteLogMetric.
725            metric_name (str):
726                Required. The resource name of the metric to delete:
727
728                ::
729
730                    "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
731
732                This corresponds to the ``metric_name`` field
733                on the ``request`` instance; if ``request`` is provided, this
734                should not be set.
735            retry (google.api_core.retry.Retry): Designation of what errors, if any,
736                should be retried.
737            timeout (float): The timeout for this request.
738            metadata (Sequence[Tuple[str, str]]): Strings which should be
739                sent along with the request as metadata.
740        """
741        # Create or coerce a protobuf request object.
742        # Sanity check: If we got a request object, we should *not* have
743        # gotten any keyword arguments that map to the request.
744        has_flattened_params = any([metric_name])
745        if request is not None and has_flattened_params:
746            raise ValueError(
747                "If the `request` argument is set, then none of "
748                "the individual field arguments should be set."
749            )
750
751        # Minor optimization to avoid making a copy if the user passes
752        # in a logging_metrics.DeleteLogMetricRequest.
753        # There's no risk of modifying the input as we've already verified
754        # there are no flattened fields.
755        if not isinstance(request, logging_metrics.DeleteLogMetricRequest):
756            request = logging_metrics.DeleteLogMetricRequest(request)
757            # If we have keyword arguments corresponding to fields on the
758            # request, apply these.
759            if metric_name is not None:
760                request.metric_name = metric_name
761
762        # Wrap the RPC method; this adds retry and timeout information,
763        # and friendly error handling.
764        rpc = self._transport._wrapped_methods[self._transport.delete_log_metric]
765
766        # Certain fields should be provided within the metadata header;
767        # add these here.
768        metadata = tuple(metadata) + (
769            gapic_v1.routing_header.to_grpc_metadata(
770                (("metric_name", request.metric_name),)
771            ),
772        )
773
774        # Send the request.
775        rpc(
776            request, retry=retry, timeout=timeout, metadata=metadata,
777        )
778
779    def __enter__(self):
780        return self
781
782    def __exit__(self, type, value, traceback):
783        """Releases underlying transport's resources.
784
785        .. warning::
786            ONLY use as a context manager if the transport is NOT shared
787            with other clients! Exiting the with block will CLOSE the transport
788            and may cause errors in other clients!
789        """
790        self.transport.close()
791
792
793try:
794    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
795        gapic_version=pkg_resources.get_distribution("google-cloud-logging",).version,
796    )
797except pkg_resources.DistributionNotFound:
798    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
799
800
801__all__ = ("MetricsServiceV2Client",)
802