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