1# -*- coding: utf-8 -*-
2# Copyright 2022 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16import abc
17from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
18
19from google.cloud.logging_v2 import gapic_version as package_version
20
21import google.auth # type: ignore
22import google.api_core
23from google.api_core import exceptions as core_exceptions
24from google.api_core import gapic_v1
25from google.api_core import retry as retries
26from google.auth import credentials as ga_credentials # type: ignore
27from google.oauth2 import service_account # type: ignore
28
29from google.cloud.logging_v2.types import logging_metrics
30from google.protobuf import empty_pb2 # type: ignore
31
32DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
33 gapic_version=package_version.__version__
34)
35
36
37class MetricsServiceV2Transport(abc.ABC):
38 """Abstract transport class for MetricsServiceV2."""
39
40 AUTH_SCOPES = (
41 "https://www.googleapis.com/auth/cloud-platform",
42 "https://www.googleapis.com/auth/cloud-platform.read-only",
43 "https://www.googleapis.com/auth/logging.admin",
44 "https://www.googleapis.com/auth/logging.read",
45 "https://www.googleapis.com/auth/logging.write",
46 )
47
48 DEFAULT_HOST: str = "logging.googleapis.com"
49
50 def __init__(
51 self,
52 *,
53 host: str = DEFAULT_HOST,
54 credentials: Optional[ga_credentials.Credentials] = None,
55 credentials_file: Optional[str] = None,
56 scopes: Optional[Sequence[str]] = None,
57 quota_project_id: Optional[str] = None,
58 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
59 always_use_jwt_access: Optional[bool] = False,
60 api_audience: Optional[str] = None,
61 **kwargs,
62 ) -> None:
63 """Instantiate the transport.
64
65 Args:
66 host (Optional[str]):
67 The hostname to connect to.
68 credentials (Optional[google.auth.credentials.Credentials]): The
69 authorization credentials to attach to requests. These
70 credentials identify the application to the service; if none
71 are specified, the client will attempt to ascertain the
72 credentials from the environment.
73 credentials_file (Optional[str]): A file with credentials that can
74 be loaded with :func:`google.auth.load_credentials_from_file`.
75 This argument is mutually exclusive with credentials.
76 scopes (Optional[Sequence[str]]): A list of scopes.
77 quota_project_id (Optional[str]): An optional project to use for billing
78 and quota.
79 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
80 The client info used to send a user-agent string along with
81 API requests. If ``None``, then default info will be used.
82 Generally, you only need to set this if you're developing
83 your own client library.
84 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
85 be used for service account credentials.
86 """
87
88 scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
89
90 # Save the scopes.
91 self._scopes = scopes
92
93 # If no credentials are provided, then determine the appropriate
94 # defaults.
95 if credentials and credentials_file:
96 raise core_exceptions.DuplicateCredentialArgs(
97 "'credentials_file' and 'credentials' are mutually exclusive"
98 )
99
100 if credentials_file is not None:
101 credentials, _ = google.auth.load_credentials_from_file(
102 credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
103 )
104 elif credentials is None:
105 credentials, _ = google.auth.default(
106 **scopes_kwargs, quota_project_id=quota_project_id
107 )
108 # Don't apply audience if the credentials file passed from user.
109 if hasattr(credentials, "with_gdch_audience"):
110 credentials = credentials.with_gdch_audience(
111 api_audience if api_audience else host
112 )
113
114 # If the credentials are service account credentials, then always try to use self signed JWT.
115 if (
116 always_use_jwt_access
117 and isinstance(credentials, service_account.Credentials)
118 and hasattr(service_account.Credentials, "with_always_use_jwt_access")
119 ):
120 credentials = credentials.with_always_use_jwt_access(True)
121
122 # Save the credentials.
123 self._credentials = credentials
124
125 # Save the hostname. Default to port 443 (HTTPS) if none is specified.
126 if ":" not in host:
127 host += ":443"
128 self._host = host
129
130 def _prep_wrapped_messages(self, client_info):
131 # Precompute the wrapped methods.
132 self._wrapped_methods = {
133 self.list_log_metrics: gapic_v1.method.wrap_method(
134 self.list_log_metrics,
135 default_retry=retries.Retry(
136 initial=0.1,
137 maximum=60.0,
138 multiplier=1.3,
139 predicate=retries.if_exception_type(
140 core_exceptions.DeadlineExceeded,
141 core_exceptions.InternalServerError,
142 core_exceptions.ServiceUnavailable,
143 ),
144 deadline=60.0,
145 ),
146 default_timeout=60.0,
147 client_info=client_info,
148 ),
149 self.get_log_metric: gapic_v1.method.wrap_method(
150 self.get_log_metric,
151 default_retry=retries.Retry(
152 initial=0.1,
153 maximum=60.0,
154 multiplier=1.3,
155 predicate=retries.if_exception_type(
156 core_exceptions.DeadlineExceeded,
157 core_exceptions.InternalServerError,
158 core_exceptions.ServiceUnavailable,
159 ),
160 deadline=60.0,
161 ),
162 default_timeout=60.0,
163 client_info=client_info,
164 ),
165 self.create_log_metric: gapic_v1.method.wrap_method(
166 self.create_log_metric,
167 default_timeout=60.0,
168 client_info=client_info,
169 ),
170 self.update_log_metric: gapic_v1.method.wrap_method(
171 self.update_log_metric,
172 default_retry=retries.Retry(
173 initial=0.1,
174 maximum=60.0,
175 multiplier=1.3,
176 predicate=retries.if_exception_type(
177 core_exceptions.DeadlineExceeded,
178 core_exceptions.InternalServerError,
179 core_exceptions.ServiceUnavailable,
180 ),
181 deadline=60.0,
182 ),
183 default_timeout=60.0,
184 client_info=client_info,
185 ),
186 self.delete_log_metric: gapic_v1.method.wrap_method(
187 self.delete_log_metric,
188 default_retry=retries.Retry(
189 initial=0.1,
190 maximum=60.0,
191 multiplier=1.3,
192 predicate=retries.if_exception_type(
193 core_exceptions.DeadlineExceeded,
194 core_exceptions.InternalServerError,
195 core_exceptions.ServiceUnavailable,
196 ),
197 deadline=60.0,
198 ),
199 default_timeout=60.0,
200 client_info=client_info,
201 ),
202 }
203
204 def close(self):
205 """Closes resources associated with the transport.
206
207 .. warning::
208 Only call this method if the transport is NOT shared
209 with other clients - this may cause errors in other clients!
210 """
211 raise NotImplementedError()
212
213 @property
214 def list_log_metrics(
215 self,
216 ) -> Callable[
217 [logging_metrics.ListLogMetricsRequest],
218 Union[
219 logging_metrics.ListLogMetricsResponse,
220 Awaitable[logging_metrics.ListLogMetricsResponse],
221 ],
222 ]:
223 raise NotImplementedError()
224
225 @property
226 def get_log_metric(
227 self,
228 ) -> Callable[
229 [logging_metrics.GetLogMetricRequest],
230 Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]],
231 ]:
232 raise NotImplementedError()
233
234 @property
235 def create_log_metric(
236 self,
237 ) -> Callable[
238 [logging_metrics.CreateLogMetricRequest],
239 Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]],
240 ]:
241 raise NotImplementedError()
242
243 @property
244 def update_log_metric(
245 self,
246 ) -> Callable[
247 [logging_metrics.UpdateLogMetricRequest],
248 Union[logging_metrics.LogMetric, Awaitable[logging_metrics.LogMetric]],
249 ]:
250 raise NotImplementedError()
251
252 @property
253 def delete_log_metric(
254 self,
255 ) -> Callable[
256 [logging_metrics.DeleteLogMetricRequest],
257 Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
258 ]:
259 raise NotImplementedError()
260
261 @property
262 def kind(self) -> str:
263 raise NotImplementedError()
264
265
266__all__ = ("MetricsServiceV2Transport",)