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#
16import warnings
17from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
18
19from google.api_core import gapic_v1
20from google.api_core import grpc_helpers_async
21from google.auth import credentials as ga_credentials # type: ignore
22from google.auth.transport.grpc import SslCredentials # type: ignore
23
24import grpc # type: ignore
25from grpc.experimental import aio # type: ignore
26
27from google.cloud.logging_v2.types import logging_metrics
28from google.longrunning import operations_pb2 # type: ignore
29from google.protobuf import empty_pb2 # type: ignore
30from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO
31from .grpc import MetricsServiceV2GrpcTransport
32
33
34class MetricsServiceV2GrpcAsyncIOTransport(MetricsServiceV2Transport):
35 """gRPC AsyncIO backend transport for MetricsServiceV2.
36
37 Service for configuring logs-based metrics.
38
39 This class defines the same methods as the primary client, so the
40 primary client can load the underlying transport implementation
41 and call it.
42
43 It sends protocol buffers over the wire using gRPC (which is built on
44 top of HTTP/2); the ``grpcio`` package must be installed.
45 """
46
47 _grpc_channel: aio.Channel
48 _stubs: Dict[str, Callable] = {}
49
50 @classmethod
51 def create_channel(
52 cls,
53 host: str = "logging.googleapis.com",
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 **kwargs,
59 ) -> aio.Channel:
60 """Create and return a gRPC AsyncIO channel object.
61 Args:
62 host (Optional[str]): The host for the channel to use.
63 credentials (Optional[~.Credentials]): The
64 authorization credentials to attach to requests. These
65 credentials identify this application to the service. If
66 none are specified, the client will attempt to ascertain
67 the credentials from the environment.
68 credentials_file (Optional[str]): A file with credentials that can
69 be loaded with :func:`google.auth.load_credentials_from_file`.
70 This argument is ignored if ``channel`` is provided.
71 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
72 service. These are only used when credentials are not specified and
73 are passed to :func:`google.auth.default`.
74 quota_project_id (Optional[str]): An optional project to use for billing
75 and quota.
76 kwargs (Optional[dict]): Keyword arguments, which are passed to the
77 channel creation.
78 Returns:
79 aio.Channel: A gRPC AsyncIO channel object.
80 """
81
82 return grpc_helpers_async.create_channel(
83 host,
84 credentials=credentials,
85 credentials_file=credentials_file,
86 quota_project_id=quota_project_id,
87 default_scopes=cls.AUTH_SCOPES,
88 scopes=scopes,
89 default_host=cls.DEFAULT_HOST,
90 **kwargs,
91 )
92
93 def __init__(
94 self,
95 *,
96 host: str = "logging.googleapis.com",
97 credentials: Optional[ga_credentials.Credentials] = None,
98 credentials_file: Optional[str] = None,
99 scopes: Optional[Sequence[str]] = None,
100 channel: Optional[aio.Channel] = None,
101 api_mtls_endpoint: Optional[str] = None,
102 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
103 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
104 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
105 quota_project_id: Optional[str] = None,
106 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
107 always_use_jwt_access: Optional[bool] = False,
108 api_audience: Optional[str] = None,
109 ) -> None:
110 """Instantiate the transport.
111
112 Args:
113 host (Optional[str]):
114 The hostname to connect to.
115 credentials (Optional[google.auth.credentials.Credentials]): The
116 authorization credentials to attach to requests. These
117 credentials identify the application to the service; if none
118 are specified, the client will attempt to ascertain the
119 credentials from the environment.
120 This argument is ignored if ``channel`` is provided.
121 credentials_file (Optional[str]): A file with credentials that can
122 be loaded with :func:`google.auth.load_credentials_from_file`.
123 This argument is ignored if ``channel`` is provided.
124 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
125 service. These are only used when credentials are not specified and
126 are passed to :func:`google.auth.default`.
127 channel (Optional[aio.Channel]): A ``Channel`` instance through
128 which to make calls.
129 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
130 If provided, it overrides the ``host`` argument and tries to create
131 a mutual TLS channel with client SSL credentials from
132 ``client_cert_source`` or application default SSL credentials.
133 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
134 Deprecated. A callback to provide client SSL certificate bytes and
135 private key bytes, both in PEM format. It is ignored if
136 ``api_mtls_endpoint`` is None.
137 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
138 for the grpc channel. It is ignored if ``channel`` is provided.
139 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
140 A callback to provide client certificate bytes and private key bytes,
141 both in PEM format. It is used to configure a mutual TLS channel. It is
142 ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
143 quota_project_id (Optional[str]): An optional project to use for billing
144 and quota.
145 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
146 The client info used to send a user-agent string along with
147 API requests. If ``None``, then default info will be used.
148 Generally, you only need to set this if you're developing
149 your own client library.
150 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
151 be used for service account credentials.
152
153 Raises:
154 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
155 creation failed for any reason.
156 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
157 and ``credentials_file`` are passed.
158 """
159 self._grpc_channel = None
160 self._ssl_channel_credentials = ssl_channel_credentials
161 self._stubs: Dict[str, Callable] = {}
162
163 if api_mtls_endpoint:
164 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
165 if client_cert_source:
166 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
167
168 if channel:
169 # Ignore credentials if a channel was passed.
170 credentials = False
171 # If a channel was explicitly provided, set it.
172 self._grpc_channel = channel
173 self._ssl_channel_credentials = None
174 else:
175 if api_mtls_endpoint:
176 host = api_mtls_endpoint
177
178 # Create SSL credentials with client_cert_source or application
179 # default SSL credentials.
180 if client_cert_source:
181 cert, key = client_cert_source()
182 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
183 certificate_chain=cert, private_key=key
184 )
185 else:
186 self._ssl_channel_credentials = SslCredentials().ssl_credentials
187
188 else:
189 if client_cert_source_for_mtls and not ssl_channel_credentials:
190 cert, key = client_cert_source_for_mtls()
191 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
192 certificate_chain=cert, private_key=key
193 )
194
195 # The base transport sets the host, credentials and scopes
196 super().__init__(
197 host=host,
198 credentials=credentials,
199 credentials_file=credentials_file,
200 scopes=scopes,
201 quota_project_id=quota_project_id,
202 client_info=client_info,
203 always_use_jwt_access=always_use_jwt_access,
204 api_audience=api_audience,
205 )
206
207 if not self._grpc_channel:
208 self._grpc_channel = type(self).create_channel(
209 self._host,
210 # use the credentials which are saved
211 credentials=self._credentials,
212 # Set ``credentials_file`` to ``None`` here as
213 # the credentials that we saved earlier should be used.
214 credentials_file=None,
215 scopes=self._scopes,
216 ssl_credentials=self._ssl_channel_credentials,
217 quota_project_id=quota_project_id,
218 options=[
219 ("grpc.max_send_message_length", -1),
220 ("grpc.max_receive_message_length", -1),
221 ],
222 )
223
224 # Wrap messages. This must be done after self._grpc_channel exists
225 self._prep_wrapped_messages(client_info)
226
227 @property
228 def grpc_channel(self) -> aio.Channel:
229 """Create the channel designed to connect to this service.
230
231 This property caches on the instance; repeated calls return
232 the same channel.
233 """
234 # Return the channel from cache.
235 return self._grpc_channel
236
237 @property
238 def list_log_metrics(
239 self,
240 ) -> Callable[
241 [logging_metrics.ListLogMetricsRequest],
242 Awaitable[logging_metrics.ListLogMetricsResponse],
243 ]:
244 r"""Return a callable for the list log metrics method over gRPC.
245
246 Lists logs-based metrics.
247
248 Returns:
249 Callable[[~.ListLogMetricsRequest],
250 Awaitable[~.ListLogMetricsResponse]]:
251 A function that, when called, will call the underlying RPC
252 on the server.
253 """
254 # Generate a "stub function" on-the-fly which will actually make
255 # the request.
256 # gRPC handles serialization and deserialization, so we just need
257 # to pass in the functions for each.
258 if "list_log_metrics" not in self._stubs:
259 self._stubs["list_log_metrics"] = self.grpc_channel.unary_unary(
260 "/google.logging.v2.MetricsServiceV2/ListLogMetrics",
261 request_serializer=logging_metrics.ListLogMetricsRequest.serialize,
262 response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize,
263 )
264 return self._stubs["list_log_metrics"]
265
266 @property
267 def get_log_metric(
268 self,
269 ) -> Callable[
270 [logging_metrics.GetLogMetricRequest], Awaitable[logging_metrics.LogMetric]
271 ]:
272 r"""Return a callable for the get log metric method over gRPC.
273
274 Gets a logs-based metric.
275
276 Returns:
277 Callable[[~.GetLogMetricRequest],
278 Awaitable[~.LogMetric]]:
279 A function that, when called, will call the underlying RPC
280 on the server.
281 """
282 # Generate a "stub function" on-the-fly which will actually make
283 # the request.
284 # gRPC handles serialization and deserialization, so we just need
285 # to pass in the functions for each.
286 if "get_log_metric" not in self._stubs:
287 self._stubs["get_log_metric"] = self.grpc_channel.unary_unary(
288 "/google.logging.v2.MetricsServiceV2/GetLogMetric",
289 request_serializer=logging_metrics.GetLogMetricRequest.serialize,
290 response_deserializer=logging_metrics.LogMetric.deserialize,
291 )
292 return self._stubs["get_log_metric"]
293
294 @property
295 def create_log_metric(
296 self,
297 ) -> Callable[
298 [logging_metrics.CreateLogMetricRequest], Awaitable[logging_metrics.LogMetric]
299 ]:
300 r"""Return a callable for the create log metric method over gRPC.
301
302 Creates a logs-based metric.
303
304 Returns:
305 Callable[[~.CreateLogMetricRequest],
306 Awaitable[~.LogMetric]]:
307 A function that, when called, will call the underlying RPC
308 on the server.
309 """
310 # Generate a "stub function" on-the-fly which will actually make
311 # the request.
312 # gRPC handles serialization and deserialization, so we just need
313 # to pass in the functions for each.
314 if "create_log_metric" not in self._stubs:
315 self._stubs["create_log_metric"] = self.grpc_channel.unary_unary(
316 "/google.logging.v2.MetricsServiceV2/CreateLogMetric",
317 request_serializer=logging_metrics.CreateLogMetricRequest.serialize,
318 response_deserializer=logging_metrics.LogMetric.deserialize,
319 )
320 return self._stubs["create_log_metric"]
321
322 @property
323 def update_log_metric(
324 self,
325 ) -> Callable[
326 [logging_metrics.UpdateLogMetricRequest], Awaitable[logging_metrics.LogMetric]
327 ]:
328 r"""Return a callable for the update log metric method over gRPC.
329
330 Creates or updates a logs-based metric.
331
332 Returns:
333 Callable[[~.UpdateLogMetricRequest],
334 Awaitable[~.LogMetric]]:
335 A function that, when called, will call the underlying RPC
336 on the server.
337 """
338 # Generate a "stub function" on-the-fly which will actually make
339 # the request.
340 # gRPC handles serialization and deserialization, so we just need
341 # to pass in the functions for each.
342 if "update_log_metric" not in self._stubs:
343 self._stubs["update_log_metric"] = self.grpc_channel.unary_unary(
344 "/google.logging.v2.MetricsServiceV2/UpdateLogMetric",
345 request_serializer=logging_metrics.UpdateLogMetricRequest.serialize,
346 response_deserializer=logging_metrics.LogMetric.deserialize,
347 )
348 return self._stubs["update_log_metric"]
349
350 @property
351 def delete_log_metric(
352 self,
353 ) -> Callable[[logging_metrics.DeleteLogMetricRequest], Awaitable[empty_pb2.Empty]]:
354 r"""Return a callable for the delete log metric method over gRPC.
355
356 Deletes a logs-based metric.
357
358 Returns:
359 Callable[[~.DeleteLogMetricRequest],
360 Awaitable[~.Empty]]:
361 A function that, when called, will call the underlying RPC
362 on the server.
363 """
364 # Generate a "stub function" on-the-fly which will actually make
365 # the request.
366 # gRPC handles serialization and deserialization, so we just need
367 # to pass in the functions for each.
368 if "delete_log_metric" not in self._stubs:
369 self._stubs["delete_log_metric"] = self.grpc_channel.unary_unary(
370 "/google.logging.v2.MetricsServiceV2/DeleteLogMetric",
371 request_serializer=logging_metrics.DeleteLogMetricRequest.serialize,
372 response_deserializer=empty_pb2.Empty.FromString,
373 )
374 return self._stubs["delete_log_metric"]
375
376 def close(self):
377 return self.grpc_channel.close()
378
379 @property
380 def cancel_operation(
381 self,
382 ) -> Callable[[operations_pb2.CancelOperationRequest], None]:
383 r"""Return a callable for the cancel_operation method over gRPC."""
384 # Generate a "stub function" on-the-fly which will actually make
385 # the request.
386 # gRPC handles serialization and deserialization, so we just need
387 # to pass in the functions for each.
388 if "cancel_operation" not in self._stubs:
389 self._stubs["cancel_operation"] = self.grpc_channel.unary_unary(
390 "/google.longrunning.Operations/CancelOperation",
391 request_serializer=operations_pb2.CancelOperationRequest.SerializeToString,
392 response_deserializer=None,
393 )
394 return self._stubs["cancel_operation"]
395
396 @property
397 def get_operation(
398 self,
399 ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
400 r"""Return a callable for the get_operation method over gRPC."""
401 # Generate a "stub function" on-the-fly which will actually make
402 # the request.
403 # gRPC handles serialization and deserialization, so we just need
404 # to pass in the functions for each.
405 if "get_operation" not in self._stubs:
406 self._stubs["get_operation"] = self.grpc_channel.unary_unary(
407 "/google.longrunning.Operations/GetOperation",
408 request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
409 response_deserializer=operations_pb2.Operation.FromString,
410 )
411 return self._stubs["get_operation"]
412
413 @property
414 def list_operations(
415 self,
416 ) -> Callable[
417 [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
418 ]:
419 r"""Return a callable for the list_operations method over gRPC."""
420 # Generate a "stub function" on-the-fly which will actually make
421 # the request.
422 # gRPC handles serialization and deserialization, so we just need
423 # to pass in the functions for each.
424 if "list_operations" not in self._stubs:
425 self._stubs["list_operations"] = self.grpc_channel.unary_unary(
426 "/google.longrunning.Operations/ListOperations",
427 request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
428 response_deserializer=operations_pb2.ListOperationsResponse.FromString,
429 )
430 return self._stubs["list_operations"]
431
432
433__all__ = ("MetricsServiceV2GrpcAsyncIOTransport",)