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.errorreporting_v1beta1.types import report_errors_service
28from .base import ReportErrorsServiceTransport, DEFAULT_CLIENT_INFO
29
30
31class ReportErrorsServiceGrpcTransport(ReportErrorsServiceTransport):
32 """gRPC backend transport for ReportErrorsService.
33
34 An API for reporting error events.
35
36 This class defines the same methods as the primary client, so the
37 primary client can load the underlying transport implementation
38 and call it.
39
40 It sends protocol buffers over the wire using gRPC (which is built on
41 top of HTTP/2); the ``grpcio`` package must be installed.
42 """
43
44 _stubs: Dict[str, Callable]
45
46 def __init__(
47 self,
48 *,
49 host: str = "clouderrorreporting.googleapis.com",
50 credentials: Optional[ga_credentials.Credentials] = None,
51 credentials_file: Optional[str] = None,
52 scopes: Optional[Sequence[str]] = None,
53 channel: Optional[grpc.Channel] = None,
54 api_mtls_endpoint: Optional[str] = None,
55 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
56 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
57 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
58 quota_project_id: Optional[str] = None,
59 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
60 always_use_jwt_access: Optional[bool] = False,
61 api_audience: Optional[str] = None,
62 ) -> None:
63 """Instantiate the transport.
64
65 Args:
66 host (Optional[str]):
67 The hostname to connect to.
68 credentials (Optional[google.auth.credentials.Credentials]): The
69 authorization credentials to attach to requests. These
70 credentials identify the application to the service; if none
71 are specified, the client will attempt to ascertain the
72 credentials from the environment.
73 This argument is ignored if ``channel`` is provided.
74 credentials_file (Optional[str]): A file with credentials that can
75 be loaded with :func:`google.auth.load_credentials_from_file`.
76 This argument is ignored if ``channel`` is provided.
77 scopes (Optional(Sequence[str])): A list of scopes. This argument is
78 ignored if ``channel`` is provided.
79 channel (Optional[grpc.Channel]): A ``Channel`` instance through
80 which to make calls.
81 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
82 If provided, it overrides the ``host`` argument and tries to create
83 a mutual TLS channel with client SSL credentials from
84 ``client_cert_source`` or application default SSL credentials.
85 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
86 Deprecated. A callback to provide client SSL certificate bytes and
87 private key bytes, both in PEM format. It is ignored if
88 ``api_mtls_endpoint`` is None.
89 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
90 for the grpc channel. It is ignored if ``channel`` is provided.
91 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
92 A callback to provide client certificate bytes and private key bytes,
93 both in PEM format. It is used to configure a mutual TLS channel. It is
94 ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
95 quota_project_id (Optional[str]): An optional project to use for billing
96 and quota.
97 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
98 The client info used to send a user-agent string along with
99 API requests. If ``None``, then default info will be used.
100 Generally, you only need to set this if you're developing
101 your own client library.
102 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
103 be used for service account credentials.
104
105 Raises:
106 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
107 creation failed for any reason.
108 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
109 and ``credentials_file`` are passed.
110 """
111 self._grpc_channel = None
112 self._ssl_channel_credentials = ssl_channel_credentials
113 self._stubs: Dict[str, Callable] = {}
114
115 if api_mtls_endpoint:
116 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
117 if client_cert_source:
118 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
119
120 if channel:
121 # Ignore credentials if a channel was passed.
122 credentials = False
123 # If a channel was explicitly provided, set it.
124 self._grpc_channel = channel
125 self._ssl_channel_credentials = None
126
127 else:
128 if api_mtls_endpoint:
129 host = api_mtls_endpoint
130
131 # Create SSL credentials with client_cert_source or application
132 # default SSL credentials.
133 if client_cert_source:
134 cert, key = client_cert_source()
135 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
136 certificate_chain=cert, private_key=key
137 )
138 else:
139 self._ssl_channel_credentials = SslCredentials().ssl_credentials
140
141 else:
142 if client_cert_source_for_mtls and not ssl_channel_credentials:
143 cert, key = client_cert_source_for_mtls()
144 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
145 certificate_chain=cert, private_key=key
146 )
147
148 # The base transport sets the host, credentials and scopes
149 super().__init__(
150 host=host,
151 credentials=credentials,
152 credentials_file=credentials_file,
153 scopes=scopes,
154 quota_project_id=quota_project_id,
155 client_info=client_info,
156 always_use_jwt_access=always_use_jwt_access,
157 api_audience=api_audience,
158 )
159
160 if not self._grpc_channel:
161 self._grpc_channel = type(self).create_channel(
162 self._host,
163 # use the credentials which are saved
164 credentials=self._credentials,
165 # Set ``credentials_file`` to ``None`` here as
166 # the credentials that we saved earlier should be used.
167 credentials_file=None,
168 scopes=self._scopes,
169 ssl_credentials=self._ssl_channel_credentials,
170 quota_project_id=quota_project_id,
171 options=[
172 ("grpc.max_send_message_length", -1),
173 ("grpc.max_receive_message_length", -1),
174 ],
175 )
176
177 # Wrap messages. This must be done after self._grpc_channel exists
178 self._prep_wrapped_messages(client_info)
179
180 @classmethod
181 def create_channel(
182 cls,
183 host: str = "clouderrorreporting.googleapis.com",
184 credentials: Optional[ga_credentials.Credentials] = None,
185 credentials_file: Optional[str] = None,
186 scopes: Optional[Sequence[str]] = None,
187 quota_project_id: Optional[str] = None,
188 **kwargs,
189 ) -> grpc.Channel:
190 """Create and return a gRPC channel object.
191 Args:
192 host (Optional[str]): The host for the channel to use.
193 credentials (Optional[~.Credentials]): The
194 authorization credentials to attach to requests. These
195 credentials identify this application to the service. If
196 none are specified, the client will attempt to ascertain
197 the credentials from the environment.
198 credentials_file (Optional[str]): A file with credentials that can
199 be loaded with :func:`google.auth.load_credentials_from_file`.
200 This argument is mutually exclusive with credentials.
201 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
202 service. These are only used when credentials are not specified and
203 are passed to :func:`google.auth.default`.
204 quota_project_id (Optional[str]): An optional project to use for billing
205 and quota.
206 kwargs (Optional[dict]): Keyword arguments, which are passed to the
207 channel creation.
208 Returns:
209 grpc.Channel: A gRPC channel object.
210
211 Raises:
212 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
213 and ``credentials_file`` are passed.
214 """
215
216 return grpc_helpers.create_channel(
217 host,
218 credentials=credentials,
219 credentials_file=credentials_file,
220 quota_project_id=quota_project_id,
221 default_scopes=cls.AUTH_SCOPES,
222 scopes=scopes,
223 default_host=cls.DEFAULT_HOST,
224 **kwargs,
225 )
226
227 @property
228 def grpc_channel(self) -> grpc.Channel:
229 """Return the channel designed to connect to this service."""
230 return self._grpc_channel
231
232 @property
233 def report_error_event(
234 self,
235 ) -> Callable[
236 [report_errors_service.ReportErrorEventRequest],
237 report_errors_service.ReportErrorEventResponse,
238 ]:
239 r"""Return a callable for the report error event method over gRPC.
240
241 Report an individual error event and record the event to a log.
242
243 This endpoint accepts **either** an OAuth token, **or** an `API
244 key <https://support.google.com/cloud/answer/6158862>`__ for
245 authentication. To use an API key, append it to the URL as the
246 value of a ``key`` parameter. For example:
247
248 ``POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456``
249
250 **Note:** `Error Reporting </error-reporting>`__ is a global
251 service built on Cloud Logging and doesn't analyze logs stored
252 in regional log buckets or logs routed to other Google Cloud
253 projects.
254
255 Returns:
256 Callable[[~.ReportErrorEventRequest],
257 ~.ReportErrorEventResponse]:
258 A function that, when called, will call the underlying RPC
259 on the server.
260 """
261 # Generate a "stub function" on-the-fly which will actually make
262 # the request.
263 # gRPC handles serialization and deserialization, so we just need
264 # to pass in the functions for each.
265 if "report_error_event" not in self._stubs:
266 self._stubs["report_error_event"] = self.grpc_channel.unary_unary(
267 "/google.devtools.clouderrorreporting.v1beta1.ReportErrorsService/ReportErrorEvent",
268 request_serializer=report_errors_service.ReportErrorEventRequest.serialize,
269 response_deserializer=report_errors_service.ReportErrorEventResponse.deserialize,
270 )
271 return self._stubs["report_error_event"]
272
273 def close(self):
274 self.grpc_channel.close()
275
276 @property
277 def kind(self) -> str:
278 return "grpc"
279
280
281__all__ = ("ReportErrorsServiceGrpcTransport",)