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