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 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.protobuf import empty_pb2 # type: ignore
29from .base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO
30from .grpc import LoggingServiceV2GrpcTransport
31
32
33class LoggingServiceV2GrpcAsyncIOTransport(LoggingServiceV2Transport):
34 """gRPC AsyncIO backend transport for LoggingServiceV2.
35
36 Service for ingesting and querying logs.
37
38 This class defines the same methods as the primary client, so the
39 primary client can load the underlying transport implementation
40 and call it.
41
42 It sends protocol buffers over the wire using gRPC (which is built on
43 top of HTTP/2); the ``grpcio`` package must be installed.
44 """
45
46 _grpc_channel: aio.Channel
47 _stubs: Dict[str, Callable] = {}
48
49 @classmethod
50 def create_channel(
51 cls,
52 host: str = "logging.googleapis.com",
53 credentials: Optional[ga_credentials.Credentials] = None,
54 credentials_file: Optional[str] = None,
55 scopes: Optional[Sequence[str]] = None,
56 quota_project_id: Optional[str] = None,
57 **kwargs,
58 ) -> aio.Channel:
59 """Create and return a gRPC AsyncIO channel object.
60 Args:
61 host (Optional[str]): The host for the channel to use.
62 credentials (Optional[~.Credentials]): The
63 authorization credentials to attach to requests. These
64 credentials identify this application to the service. If
65 none are specified, the client will attempt to ascertain
66 the credentials from the environment.
67 credentials_file (Optional[str]): A file with credentials that can
68 be loaded with :func:`google.auth.load_credentials_from_file`.
69 This argument is ignored if ``channel`` is provided.
70 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
71 service. These are only used when credentials are not specified and
72 are passed to :func:`google.auth.default`.
73 quota_project_id (Optional[str]): An optional project to use for billing
74 and quota.
75 kwargs (Optional[dict]): Keyword arguments, which are passed to the
76 channel creation.
77 Returns:
78 aio.Channel: A gRPC AsyncIO channel object.
79 """
80
81 return grpc_helpers_async.create_channel(
82 host,
83 credentials=credentials,
84 credentials_file=credentials_file,
85 quota_project_id=quota_project_id,
86 default_scopes=cls.AUTH_SCOPES,
87 scopes=scopes,
88 default_host=cls.DEFAULT_HOST,
89 **kwargs,
90 )
91
92 def __init__(
93 self,
94 *,
95 host: str = "logging.googleapis.com",
96 credentials: Optional[ga_credentials.Credentials] = None,
97 credentials_file: Optional[str] = None,
98 scopes: Optional[Sequence[str]] = None,
99 channel: Optional[aio.Channel] = None,
100 api_mtls_endpoint: Optional[str] = None,
101 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
102 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
103 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
104 quota_project_id: Optional[str] = None,
105 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
106 always_use_jwt_access: Optional[bool] = False,
107 api_audience: Optional[str] = None,
108 ) -> None:
109 """Instantiate the transport.
110
111 Args:
112 host (Optional[str]):
113 The hostname to connect to.
114 credentials (Optional[google.auth.credentials.Credentials]): The
115 authorization credentials to attach to requests. These
116 credentials identify the application to the service; if none
117 are specified, the client will attempt to ascertain the
118 credentials from the environment.
119 This argument is ignored if ``channel`` is provided.
120 credentials_file (Optional[str]): A file with credentials that can
121 be loaded with :func:`google.auth.load_credentials_from_file`.
122 This argument is ignored if ``channel`` is provided.
123 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
124 service. These are only used when credentials are not specified and
125 are passed to :func:`google.auth.default`.
126 channel (Optional[aio.Channel]): A ``Channel`` instance through
127 which to make calls.
128 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
129 If provided, it overrides the ``host`` argument and tries to create
130 a mutual TLS channel with client SSL credentials from
131 ``client_cert_source`` or application default SSL credentials.
132 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
133 Deprecated. A callback to provide client SSL certificate bytes and
134 private key bytes, both in PEM format. It is ignored if
135 ``api_mtls_endpoint`` is None.
136 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
137 for the grpc channel. It is ignored if ``channel`` is provided.
138 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
139 A callback to provide client certificate bytes and private key bytes,
140 both in PEM format. It is used to configure a mutual TLS channel. It is
141 ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
142 quota_project_id (Optional[str]): An optional project to use for billing
143 and quota.
144 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
145 The client info used to send a user-agent string along with
146 API requests. If ``None``, then default info will be used.
147 Generally, you only need to set this if you're developing
148 your own client library.
149 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
150 be used for service account credentials.
151
152 Raises:
153 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
154 creation failed for any reason.
155 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
156 and ``credentials_file`` are passed.
157 """
158 self._grpc_channel = None
159 self._ssl_channel_credentials = ssl_channel_credentials
160 self._stubs: Dict[str, Callable] = {}
161
162 if api_mtls_endpoint:
163 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
164 if client_cert_source:
165 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
166
167 if channel:
168 # Ignore credentials if a channel was passed.
169 credentials = False
170 # If a channel was explicitly provided, set it.
171 self._grpc_channel = channel
172 self._ssl_channel_credentials = None
173 else:
174 if api_mtls_endpoint:
175 host = api_mtls_endpoint
176
177 # Create SSL credentials with client_cert_source or application
178 # default SSL credentials.
179 if client_cert_source:
180 cert, key = client_cert_source()
181 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
182 certificate_chain=cert, private_key=key
183 )
184 else:
185 self._ssl_channel_credentials = SslCredentials().ssl_credentials
186
187 else:
188 if client_cert_source_for_mtls and not ssl_channel_credentials:
189 cert, key = client_cert_source_for_mtls()
190 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
191 certificate_chain=cert, private_key=key
192 )
193
194 # The base transport sets the host, credentials and scopes
195 super().__init__(
196 host=host,
197 credentials=credentials,
198 credentials_file=credentials_file,
199 scopes=scopes,
200 quota_project_id=quota_project_id,
201 client_info=client_info,
202 always_use_jwt_access=always_use_jwt_access,
203 api_audience=api_audience,
204 )
205
206 if not self._grpc_channel:
207 self._grpc_channel = type(self).create_channel(
208 self._host,
209 # use the credentials which are saved
210 credentials=self._credentials,
211 # Set ``credentials_file`` to ``None`` here as
212 # the credentials that we saved earlier should be used.
213 credentials_file=None,
214 scopes=self._scopes,
215 ssl_credentials=self._ssl_channel_credentials,
216 quota_project_id=quota_project_id,
217 options=[
218 ("grpc.max_send_message_length", -1),
219 ("grpc.max_receive_message_length", -1),
220 ],
221 )
222
223 # Wrap messages. This must be done after self._grpc_channel exists
224 self._prep_wrapped_messages(client_info)
225
226 @property
227 def grpc_channel(self) -> aio.Channel:
228 """Create the channel designed to connect to this service.
229
230 This property caches on the instance; repeated calls return
231 the same channel.
232 """
233 # Return the channel from cache.
234 return self._grpc_channel
235
236 @property
237 def delete_log(
238 self,
239 ) -> Callable[[logging.DeleteLogRequest], Awaitable[empty_pb2.Empty]]:
240 r"""Return a callable for the delete log method over gRPC.
241
242 Deletes all the log entries in a log for the \_Default Log
243 Bucket. The log reappears if it receives new entries. Log
244 entries written shortly before the delete operation might not be
245 deleted. Entries received after the delete operation with a
246 timestamp before the operation will be deleted.
247
248 Returns:
249 Callable[[~.DeleteLogRequest],
250 Awaitable[~.Empty]]:
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 "delete_log" not in self._stubs:
259 self._stubs["delete_log"] = self.grpc_channel.unary_unary(
260 "/google.logging.v2.LoggingServiceV2/DeleteLog",
261 request_serializer=logging.DeleteLogRequest.serialize,
262 response_deserializer=empty_pb2.Empty.FromString,
263 )
264 return self._stubs["delete_log"]
265
266 @property
267 def write_log_entries(
268 self,
269 ) -> Callable[
270 [logging.WriteLogEntriesRequest], Awaitable[logging.WriteLogEntriesResponse]
271 ]:
272 r"""Return a callable for the write log entries method over gRPC.
273
274 Writes log entries to Logging. This API method is the
275 only way to send log entries to Logging. This method is
276 used, directly or indirectly, by the Logging agent
277 (fluentd) and all logging libraries configured to use
278 Logging. A single request may contain log entries for a
279 maximum of 1000 different resources (projects,
280 organizations, billing accounts or folders)
281
282 Returns:
283 Callable[[~.WriteLogEntriesRequest],
284 Awaitable[~.WriteLogEntriesResponse]]:
285 A function that, when called, will call the underlying RPC
286 on the server.
287 """
288 # Generate a "stub function" on-the-fly which will actually make
289 # the request.
290 # gRPC handles serialization and deserialization, so we just need
291 # to pass in the functions for each.
292 if "write_log_entries" not in self._stubs:
293 self._stubs["write_log_entries"] = self.grpc_channel.unary_unary(
294 "/google.logging.v2.LoggingServiceV2/WriteLogEntries",
295 request_serializer=logging.WriteLogEntriesRequest.serialize,
296 response_deserializer=logging.WriteLogEntriesResponse.deserialize,
297 )
298 return self._stubs["write_log_entries"]
299
300 @property
301 def list_log_entries(
302 self,
303 ) -> Callable[
304 [logging.ListLogEntriesRequest], Awaitable[logging.ListLogEntriesResponse]
305 ]:
306 r"""Return a callable for the list log entries method over gRPC.
307
308 Lists log entries. Use this method to retrieve log entries that
309 originated from a project/folder/organization/billing account.
310 For ways to export log entries, see `Exporting
311 Logs <https://cloud.google.com/logging/docs/export>`__.
312
313 Returns:
314 Callable[[~.ListLogEntriesRequest],
315 Awaitable[~.ListLogEntriesResponse]]:
316 A function that, when called, will call the underlying RPC
317 on the server.
318 """
319 # Generate a "stub function" on-the-fly which will actually make
320 # the request.
321 # gRPC handles serialization and deserialization, so we just need
322 # to pass in the functions for each.
323 if "list_log_entries" not in self._stubs:
324 self._stubs["list_log_entries"] = self.grpc_channel.unary_unary(
325 "/google.logging.v2.LoggingServiceV2/ListLogEntries",
326 request_serializer=logging.ListLogEntriesRequest.serialize,
327 response_deserializer=logging.ListLogEntriesResponse.deserialize,
328 )
329 return self._stubs["list_log_entries"]
330
331 @property
332 def list_monitored_resource_descriptors(
333 self,
334 ) -> Callable[
335 [logging.ListMonitoredResourceDescriptorsRequest],
336 Awaitable[logging.ListMonitoredResourceDescriptorsResponse],
337 ]:
338 r"""Return a callable for the list monitored resource
339 descriptors method over gRPC.
340
341 Lists the descriptors for monitored resource types
342 used by Logging.
343
344 Returns:
345 Callable[[~.ListMonitoredResourceDescriptorsRequest],
346 Awaitable[~.ListMonitoredResourceDescriptorsResponse]]:
347 A function that, when called, will call the underlying RPC
348 on the server.
349 """
350 # Generate a "stub function" on-the-fly which will actually make
351 # the request.
352 # gRPC handles serialization and deserialization, so we just need
353 # to pass in the functions for each.
354 if "list_monitored_resource_descriptors" not in self._stubs:
355 self._stubs[
356 "list_monitored_resource_descriptors"
357 ] = self.grpc_channel.unary_unary(
358 "/google.logging.v2.LoggingServiceV2/ListMonitoredResourceDescriptors",
359 request_serializer=logging.ListMonitoredResourceDescriptorsRequest.serialize,
360 response_deserializer=logging.ListMonitoredResourceDescriptorsResponse.deserialize,
361 )
362 return self._stubs["list_monitored_resource_descriptors"]
363
364 @property
365 def list_logs(
366 self,
367 ) -> Callable[[logging.ListLogsRequest], Awaitable[logging.ListLogsResponse]]:
368 r"""Return a callable for the list logs method over gRPC.
369
370 Lists the logs in projects, organizations, folders,
371 or billing accounts. Only logs that have entries are
372 listed.
373
374 Returns:
375 Callable[[~.ListLogsRequest],
376 Awaitable[~.ListLogsResponse]]:
377 A function that, when called, will call the underlying RPC
378 on the server.
379 """
380 # Generate a "stub function" on-the-fly which will actually make
381 # the request.
382 # gRPC handles serialization and deserialization, so we just need
383 # to pass in the functions for each.
384 if "list_logs" not in self._stubs:
385 self._stubs["list_logs"] = self.grpc_channel.unary_unary(
386 "/google.logging.v2.LoggingServiceV2/ListLogs",
387 request_serializer=logging.ListLogsRequest.serialize,
388 response_deserializer=logging.ListLogsResponse.deserialize,
389 )
390 return self._stubs["list_logs"]
391
392 @property
393 def tail_log_entries(
394 self,
395 ) -> Callable[
396 [logging.TailLogEntriesRequest], Awaitable[logging.TailLogEntriesResponse]
397 ]:
398 r"""Return a callable for the tail log entries method over gRPC.
399
400 Streaming read of log entries as they are ingested.
401 Until the stream is terminated, it will continue reading
402 logs.
403
404 Returns:
405 Callable[[~.TailLogEntriesRequest],
406 Awaitable[~.TailLogEntriesResponse]]:
407 A function that, when called, will call the underlying RPC
408 on the server.
409 """
410 # Generate a "stub function" on-the-fly which will actually make
411 # the request.
412 # gRPC handles serialization and deserialization, so we just need
413 # to pass in the functions for each.
414 if "tail_log_entries" not in self._stubs:
415 self._stubs["tail_log_entries"] = self.grpc_channel.stream_stream(
416 "/google.logging.v2.LoggingServiceV2/TailLogEntries",
417 request_serializer=logging.TailLogEntriesRequest.serialize,
418 response_deserializer=logging.TailLogEntriesResponse.deserialize,
419 )
420 return self._stubs["tail_log_entries"]
421
422 def close(self):
423 return self.grpc_channel.close()
424
425
426__all__ = ("LoggingServiceV2GrpcAsyncIOTransport",)