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_metrics
28from google.protobuf import empty_pb2 # type: ignore
29from .base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO
30
31
32class MetricsServiceV2GrpcTransport(MetricsServiceV2Transport):
33 """gRPC backend transport for MetricsServiceV2.
34
35 Service for configuring logs-based metrics.
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 list_log_metrics(
235 self,
236 ) -> Callable[
237 [logging_metrics.ListLogMetricsRequest], logging_metrics.ListLogMetricsResponse
238 ]:
239 r"""Return a callable for the list log metrics method over gRPC.
240
241 Lists logs-based metrics.
242
243 Returns:
244 Callable[[~.ListLogMetricsRequest],
245 ~.ListLogMetricsResponse]:
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 "list_log_metrics" not in self._stubs:
254 self._stubs["list_log_metrics"] = self.grpc_channel.unary_unary(
255 "/google.logging.v2.MetricsServiceV2/ListLogMetrics",
256 request_serializer=logging_metrics.ListLogMetricsRequest.serialize,
257 response_deserializer=logging_metrics.ListLogMetricsResponse.deserialize,
258 )
259 return self._stubs["list_log_metrics"]
260
261 @property
262 def get_log_metric(
263 self,
264 ) -> Callable[[logging_metrics.GetLogMetricRequest], logging_metrics.LogMetric]:
265 r"""Return a callable for the get log metric method over gRPC.
266
267 Gets a logs-based metric.
268
269 Returns:
270 Callable[[~.GetLogMetricRequest],
271 ~.LogMetric]:
272 A function that, when called, will call the underlying RPC
273 on the server.
274 """
275 # Generate a "stub function" on-the-fly which will actually make
276 # the request.
277 # gRPC handles serialization and deserialization, so we just need
278 # to pass in the functions for each.
279 if "get_log_metric" not in self._stubs:
280 self._stubs["get_log_metric"] = self.grpc_channel.unary_unary(
281 "/google.logging.v2.MetricsServiceV2/GetLogMetric",
282 request_serializer=logging_metrics.GetLogMetricRequest.serialize,
283 response_deserializer=logging_metrics.LogMetric.deserialize,
284 )
285 return self._stubs["get_log_metric"]
286
287 @property
288 def create_log_metric(
289 self,
290 ) -> Callable[[logging_metrics.CreateLogMetricRequest], logging_metrics.LogMetric]:
291 r"""Return a callable for the create log metric method over gRPC.
292
293 Creates a logs-based metric.
294
295 Returns:
296 Callable[[~.CreateLogMetricRequest],
297 ~.LogMetric]:
298 A function that, when called, will call the underlying RPC
299 on the server.
300 """
301 # Generate a "stub function" on-the-fly which will actually make
302 # the request.
303 # gRPC handles serialization and deserialization, so we just need
304 # to pass in the functions for each.
305 if "create_log_metric" not in self._stubs:
306 self._stubs["create_log_metric"] = self.grpc_channel.unary_unary(
307 "/google.logging.v2.MetricsServiceV2/CreateLogMetric",
308 request_serializer=logging_metrics.CreateLogMetricRequest.serialize,
309 response_deserializer=logging_metrics.LogMetric.deserialize,
310 )
311 return self._stubs["create_log_metric"]
312
313 @property
314 def update_log_metric(
315 self,
316 ) -> Callable[[logging_metrics.UpdateLogMetricRequest], logging_metrics.LogMetric]:
317 r"""Return a callable for the update log metric method over gRPC.
318
319 Creates or updates a logs-based metric.
320
321 Returns:
322 Callable[[~.UpdateLogMetricRequest],
323 ~.LogMetric]:
324 A function that, when called, will call the underlying RPC
325 on the server.
326 """
327 # Generate a "stub function" on-the-fly which will actually make
328 # the request.
329 # gRPC handles serialization and deserialization, so we just need
330 # to pass in the functions for each.
331 if "update_log_metric" not in self._stubs:
332 self._stubs["update_log_metric"] = self.grpc_channel.unary_unary(
333 "/google.logging.v2.MetricsServiceV2/UpdateLogMetric",
334 request_serializer=logging_metrics.UpdateLogMetricRequest.serialize,
335 response_deserializer=logging_metrics.LogMetric.deserialize,
336 )
337 return self._stubs["update_log_metric"]
338
339 @property
340 def delete_log_metric(
341 self,
342 ) -> Callable[[logging_metrics.DeleteLogMetricRequest], empty_pb2.Empty]:
343 r"""Return a callable for the delete log metric method over gRPC.
344
345 Deletes a logs-based metric.
346
347 Returns:
348 Callable[[~.DeleteLogMetricRequest],
349 ~.Empty]:
350 A function that, when called, will call the underlying RPC
351 on the server.
352 """
353 # Generate a "stub function" on-the-fly which will actually make
354 # the request.
355 # gRPC handles serialization and deserialization, so we just need
356 # to pass in the functions for each.
357 if "delete_log_metric" not in self._stubs:
358 self._stubs["delete_log_metric"] = self.grpc_channel.unary_unary(
359 "/google.logging.v2.MetricsServiceV2/DeleteLogMetric",
360 request_serializer=logging_metrics.DeleteLogMetricRequest.serialize,
361 response_deserializer=empty_pb2.Empty.FromString,
362 )
363 return self._stubs["delete_log_metric"]
364
365 def close(self):
366 self.grpc_channel.close()
367
368 @property
369 def kind(self) -> str:
370 return "grpc"
371
372
373__all__ = ("MetricsServiceV2GrpcTransport",)