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
28from google.longrunning import operations_pb2 # type: ignore
29from google.protobuf import empty_pb2 # type: ignore
30from .base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO
31from .grpc import LoggingServiceV2GrpcTransport
32
33
34class LoggingServiceV2GrpcAsyncIOTransport(LoggingServiceV2Transport):
35 """gRPC AsyncIO backend transport for LoggingServiceV2.
36
37 Service for ingesting and querying logs.
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 delete_log(
239 self,
240 ) -> Callable[[logging.DeleteLogRequest], Awaitable[empty_pb2.Empty]]:
241 r"""Return a callable for the delete log method over gRPC.
242
243 Deletes all the log entries in a log for the \_Default Log
244 Bucket. The log reappears if it receives new entries. Log
245 entries written shortly before the delete operation might not be
246 deleted. Entries received after the delete operation with a
247 timestamp before the operation will be deleted.
248
249 Returns:
250 Callable[[~.DeleteLogRequest],
251 Awaitable[~.Empty]]:
252 A function that, when called, will call the underlying RPC
253 on the server.
254 """
255 # Generate a "stub function" on-the-fly which will actually make
256 # the request.
257 # gRPC handles serialization and deserialization, so we just need
258 # to pass in the functions for each.
259 if "delete_log" not in self._stubs:
260 self._stubs["delete_log"] = self.grpc_channel.unary_unary(
261 "/google.logging.v2.LoggingServiceV2/DeleteLog",
262 request_serializer=logging.DeleteLogRequest.serialize,
263 response_deserializer=empty_pb2.Empty.FromString,
264 )
265 return self._stubs["delete_log"]
266
267 @property
268 def write_log_entries(
269 self,
270 ) -> Callable[
271 [logging.WriteLogEntriesRequest], Awaitable[logging.WriteLogEntriesResponse]
272 ]:
273 r"""Return a callable for the write log entries method over gRPC.
274
275 Writes log entries to Logging. This API method is the
276 only way to send log entries to Logging. This method is
277 used, directly or indirectly, by the Logging agent
278 (fluentd) and all logging libraries configured to use
279 Logging. A single request may contain log entries for a
280 maximum of 1000 different resources (projects,
281 organizations, billing accounts or folders)
282
283 Returns:
284 Callable[[~.WriteLogEntriesRequest],
285 Awaitable[~.WriteLogEntriesResponse]]:
286 A function that, when called, will call the underlying RPC
287 on the server.
288 """
289 # Generate a "stub function" on-the-fly which will actually make
290 # the request.
291 # gRPC handles serialization and deserialization, so we just need
292 # to pass in the functions for each.
293 if "write_log_entries" not in self._stubs:
294 self._stubs["write_log_entries"] = self.grpc_channel.unary_unary(
295 "/google.logging.v2.LoggingServiceV2/WriteLogEntries",
296 request_serializer=logging.WriteLogEntriesRequest.serialize,
297 response_deserializer=logging.WriteLogEntriesResponse.deserialize,
298 )
299 return self._stubs["write_log_entries"]
300
301 @property
302 def list_log_entries(
303 self,
304 ) -> Callable[
305 [logging.ListLogEntriesRequest], Awaitable[logging.ListLogEntriesResponse]
306 ]:
307 r"""Return a callable for the list log entries method over gRPC.
308
309 Lists log entries. Use this method to retrieve log entries that
310 originated from a project/folder/organization/billing account.
311 For ways to export log entries, see `Exporting
312 Logs <https://cloud.google.com/logging/docs/export>`__.
313
314 Returns:
315 Callable[[~.ListLogEntriesRequest],
316 Awaitable[~.ListLogEntriesResponse]]:
317 A function that, when called, will call the underlying RPC
318 on the server.
319 """
320 # Generate a "stub function" on-the-fly which will actually make
321 # the request.
322 # gRPC handles serialization and deserialization, so we just need
323 # to pass in the functions for each.
324 if "list_log_entries" not in self._stubs:
325 self._stubs["list_log_entries"] = self.grpc_channel.unary_unary(
326 "/google.logging.v2.LoggingServiceV2/ListLogEntries",
327 request_serializer=logging.ListLogEntriesRequest.serialize,
328 response_deserializer=logging.ListLogEntriesResponse.deserialize,
329 )
330 return self._stubs["list_log_entries"]
331
332 @property
333 def list_monitored_resource_descriptors(
334 self,
335 ) -> Callable[
336 [logging.ListMonitoredResourceDescriptorsRequest],
337 Awaitable[logging.ListMonitoredResourceDescriptorsResponse],
338 ]:
339 r"""Return a callable for the list monitored resource
340 descriptors method over gRPC.
341
342 Lists the descriptors for monitored resource types
343 used by Logging.
344
345 Returns:
346 Callable[[~.ListMonitoredResourceDescriptorsRequest],
347 Awaitable[~.ListMonitoredResourceDescriptorsResponse]]:
348 A function that, when called, will call the underlying RPC
349 on the server.
350 """
351 # Generate a "stub function" on-the-fly which will actually make
352 # the request.
353 # gRPC handles serialization and deserialization, so we just need
354 # to pass in the functions for each.
355 if "list_monitored_resource_descriptors" not in self._stubs:
356 self._stubs[
357 "list_monitored_resource_descriptors"
358 ] = self.grpc_channel.unary_unary(
359 "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors",
360 request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize,
361 response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize,
362 )
363 return self._stubs["list_monitored_resource_descriptors"]
364
365 @property
366 def list_logs(
367 self,
368 ) -> Callable[[logging.ListLogsRequest], Awaitable[logging.ListLogsResponse]]:
369 r"""Return a callable for the list logs method over gRPC.
370
371 Lists the logs in projects, organizations, folders,
372 or billing accounts. Only logs that have entries are
373 listed.
374
375 Returns:
376 Callable[[~.ListLogsRequest],
377 Awaitable[~.ListLogsResponse]]:
378 A function that, when called, will call the underlying RPC
379 on the server.
380 """
381 # Generate a "stub function" on-the-fly which will actually make
382 # the request.
383 # gRPC handles serialization and deserialization, so we just need
384 # to pass in the functions for each.
385 if "list_logs" not in self._stubs:
386 self._stubs["list_logs"] = self.grpc_channel.unary_unary(
387 "/google.logging.v2.LoggingServiceV2/ListLogs",
388 request_serializer=logging.ListLogsRequest.serialize,
389 response_deserializer=logging.ListLogsResponse.deserialize,
390 )
391 return self._stubs["list_logs"]
392
393 @property
394 def tail_log_entries(
395 self,
396 ) -> Callable[
397 [logging.TailLogEntriesRequest], Awaitable[logging.TailLogEntriesResponse]
398 ]:
399 r"""Return a callable for the tail log entries method over gRPC.
400
401 Streaming read of log entries as they are ingested.
402 Until the stream is terminated, it will continue reading
403 logs.
404
405 Returns:
406 Callable[[~.TailLogEntriesRequest],
407 Awaitable[~.TailLogEntriesResponse]]:
408 A function that, when called, will call the underlying RPC
409 on the server.
410 """
411 # Generate a "stub function" on-the-fly which will actually make
412 # the request.
413 # gRPC handles serialization and deserialization, so we just need
414 # to pass in the functions for each.
415 if "tail_log_entries" not in self._stubs:
416 self._stubs["tail_log_entries"] = self.grpc_channel.stream_stream(
417 "/google.logging.v2.LoggingServiceV2/TailLogEntries",
418 request_serializer=logging.TailLogEntriesRequest.serialize,
419 response_deserializer=logging.TailLogEntriesResponse.deserialize,
420 )
421 return self._stubs["tail_log_entries"]
422
423 def close(self):
424 return self.grpc_channel.close()
425
426 @property
427 def cancel_operation(
428 self,
429 ) -> Callable[[operations_pb2.CancelOperationRequest], None]:
430 r"""Return a callable for the cancel_operation method over gRPC."""
431 # Generate a "stub function" on-the-fly which will actually make
432 # the request.
433 # gRPC handles serialization and deserialization, so we just need
434 # to pass in the functions for each.
435 if "cancel_operation" not in self._stubs:
436 self._stubs["cancel_operation"] = self.grpc_channel.unary_unary(
437 "/google.longrunning.Operations/CancelOperation",
438 request_serializer=operations_pb2.CancelOperationRequest.SerializeToString,
439 response_deserializer=None,
440 )
441 return self._stubs["cancel_operation"]
442
443 @property
444 def get_operation(
445 self,
446 ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
447 r"""Return a callable for the get_operation method over gRPC."""
448 # Generate a "stub function" on-the-fly which will actually make
449 # the request.
450 # gRPC handles serialization and deserialization, so we just need
451 # to pass in the functions for each.
452 if "get_operation" not in self._stubs:
453 self._stubs["get_operation"] = self.grpc_channel.unary_unary(
454 "/google.longrunning.Operations/GetOperation",
455 request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
456 response_deserializer=operations_pb2.Operation.FromString,
457 )
458 return self._stubs["get_operation"]
459
460 @property
461 def list_operations(
462 self,
463 ) -> Callable[
464 [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse
465 ]:
466 r"""Return a callable for the list_operations method over gRPC."""
467 # Generate a "stub function" on-the-fly which will actually make
468 # the request.
469 # gRPC handles serialization and deserialization, so we just need
470 # to pass in the functions for each.
471 if "list_operations" not in self._stubs:
472 self._stubs["list_operations"] = self.grpc_channel.unary_unary(
473 "/google.longrunning.Operations/ListOperations",
474 request_serializer=operations_pb2.ListOperationsRequest.SerializeToString,
475 response_deserializer=operations_pb2.ListOperationsResponse.FromString,
476 )
477 return self._stubs["list_operations"]
478
479
480__all__ = ("LoggingServiceV2GrpcAsyncIOTransport",)