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#
16from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
17import warnings
18
19from google.api_core import gapic_v1, grpc_helpers_async, operations_v1
20from google.auth import credentials as ga_credentials # type: ignore
21from google.auth.transport.grpc import SslCredentials # type: ignore
22from google.longrunning import operations_pb2 # type: ignore
23import grpc # type: ignore
24from grpc.experimental import aio # type: ignore
25
26from google.cloud.resourcemanager_v3.types import tag_holds
27
28from .base import DEFAULT_CLIENT_INFO, TagHoldsTransport
29from .grpc import TagHoldsGrpcTransport
30
31
32class TagHoldsGrpcAsyncIOTransport(TagHoldsTransport):
33 """gRPC AsyncIO backend transport for TagHolds.
34
35 Allow users to create and manage TagHolds for TagValues.
36 TagHolds represent the use of a Tag Value that is not captured
37 by TagBindings but should still block TagValue deletion (such as
38 a reference in a policy condition). This service provides
39 isolated failure domains by cloud location so that TagHolds can
40 be managed in the same location as their usage.
41
42 This class defines the same methods as the primary client, so the
43 primary client can load the underlying transport implementation
44 and call it.
45
46 It sends protocol buffers over the wire using gRPC (which is built on
47 top of HTTP/2); the ``grpcio`` package must be installed.
48 """
49
50 _grpc_channel: aio.Channel
51 _stubs: Dict[str, Callable] = {}
52
53 @classmethod
54 def create_channel(
55 cls,
56 host: str = "cloudresourcemanager.googleapis.com",
57 credentials: Optional[ga_credentials.Credentials] = None,
58 credentials_file: Optional[str] = None,
59 scopes: Optional[Sequence[str]] = None,
60 quota_project_id: Optional[str] = None,
61 **kwargs,
62 ) -> aio.Channel:
63 """Create and return a gRPC AsyncIO channel object.
64 Args:
65 host (Optional[str]): The host for the channel to use.
66 credentials (Optional[~.Credentials]): The
67 authorization credentials to attach to requests. These
68 credentials identify this application to the service. If
69 none are specified, the client will attempt to ascertain
70 the credentials from the environment.
71 credentials_file (Optional[str]): A file with credentials that can
72 be loaded with :func:`google.auth.load_credentials_from_file`.
73 This argument is ignored if ``channel`` is provided.
74 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
75 service. These are only used when credentials are not specified and
76 are passed to :func:`google.auth.default`.
77 quota_project_id (Optional[str]): An optional project to use for billing
78 and quota.
79 kwargs (Optional[dict]): Keyword arguments, which are passed to the
80 channel creation.
81 Returns:
82 aio.Channel: A gRPC AsyncIO channel object.
83 """
84
85 return grpc_helpers_async.create_channel(
86 host,
87 credentials=credentials,
88 credentials_file=credentials_file,
89 quota_project_id=quota_project_id,
90 default_scopes=cls.AUTH_SCOPES,
91 scopes=scopes,
92 default_host=cls.DEFAULT_HOST,
93 **kwargs,
94 )
95
96 def __init__(
97 self,
98 *,
99 host: str = "cloudresourcemanager.googleapis.com",
100 credentials: Optional[ga_credentials.Credentials] = None,
101 credentials_file: Optional[str] = None,
102 scopes: Optional[Sequence[str]] = None,
103 channel: Optional[aio.Channel] = None,
104 api_mtls_endpoint: Optional[str] = None,
105 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
106 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
107 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
108 quota_project_id: Optional[str] = None,
109 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
110 always_use_jwt_access: Optional[bool] = False,
111 api_audience: Optional[str] = None,
112 ) -> None:
113 """Instantiate the transport.
114
115 Args:
116 host (Optional[str]):
117 The hostname to connect to.
118 credentials (Optional[google.auth.credentials.Credentials]): The
119 authorization credentials to attach to requests. These
120 credentials identify the application to the service; if none
121 are specified, the client will attempt to ascertain the
122 credentials from the environment.
123 This argument is ignored if ``channel`` is provided.
124 credentials_file (Optional[str]): A file with credentials that can
125 be loaded with :func:`google.auth.load_credentials_from_file`.
126 This argument is ignored if ``channel`` is provided.
127 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
128 service. These are only used when credentials are not specified and
129 are passed to :func:`google.auth.default`.
130 channel (Optional[aio.Channel]): A ``Channel`` instance through
131 which to make calls.
132 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
133 If provided, it overrides the ``host`` argument and tries to create
134 a mutual TLS channel with client SSL credentials from
135 ``client_cert_source`` or application default SSL credentials.
136 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
137 Deprecated. A callback to provide client SSL certificate bytes and
138 private key bytes, both in PEM format. It is ignored if
139 ``api_mtls_endpoint`` is None.
140 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
141 for the grpc channel. It is ignored if ``channel`` is provided.
142 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
143 A callback to provide client certificate bytes and private key bytes,
144 both in PEM format. It is used to configure a mutual TLS channel. It is
145 ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
146 quota_project_id (Optional[str]): An optional project to use for billing
147 and quota.
148 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
149 The client info used to send a user-agent string along with
150 API requests. If ``None``, then default info will be used.
151 Generally, you only need to set this if you're developing
152 your own client library.
153 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
154 be used for service account credentials.
155
156 Raises:
157 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
158 creation failed for any reason.
159 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
160 and ``credentials_file`` are passed.
161 """
162 self._grpc_channel = None
163 self._ssl_channel_credentials = ssl_channel_credentials
164 self._stubs: Dict[str, Callable] = {}
165 self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None
166
167 if api_mtls_endpoint:
168 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
169 if client_cert_source:
170 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
171
172 if channel:
173 # Ignore credentials if a channel was passed.
174 credentials = False
175 # If a channel was explicitly provided, set it.
176 self._grpc_channel = channel
177 self._ssl_channel_credentials = None
178 else:
179 if api_mtls_endpoint:
180 host = api_mtls_endpoint
181
182 # Create SSL credentials with client_cert_source or application
183 # default SSL credentials.
184 if client_cert_source:
185 cert, key = client_cert_source()
186 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
187 certificate_chain=cert, private_key=key
188 )
189 else:
190 self._ssl_channel_credentials = SslCredentials().ssl_credentials
191
192 else:
193 if client_cert_source_for_mtls and not ssl_channel_credentials:
194 cert, key = client_cert_source_for_mtls()
195 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
196 certificate_chain=cert, private_key=key
197 )
198
199 # The base transport sets the host, credentials and scopes
200 super().__init__(
201 host=host,
202 credentials=credentials,
203 credentials_file=credentials_file,
204 scopes=scopes,
205 quota_project_id=quota_project_id,
206 client_info=client_info,
207 always_use_jwt_access=always_use_jwt_access,
208 api_audience=api_audience,
209 )
210
211 if not self._grpc_channel:
212 self._grpc_channel = type(self).create_channel(
213 self._host,
214 # use the credentials which are saved
215 credentials=self._credentials,
216 # Set ``credentials_file`` to ``None`` here as
217 # the credentials that we saved earlier should be used.
218 credentials_file=None,
219 scopes=self._scopes,
220 ssl_credentials=self._ssl_channel_credentials,
221 quota_project_id=quota_project_id,
222 options=[
223 ("grpc.max_send_message_length", -1),
224 ("grpc.max_receive_message_length", -1),
225 ],
226 )
227
228 # Wrap messages. This must be done after self._grpc_channel exists
229 self._prep_wrapped_messages(client_info)
230
231 @property
232 def grpc_channel(self) -> aio.Channel:
233 """Create the channel designed to connect to this service.
234
235 This property caches on the instance; repeated calls return
236 the same channel.
237 """
238 # Return the channel from cache.
239 return self._grpc_channel
240
241 @property
242 def operations_client(self) -> operations_v1.OperationsAsyncClient:
243 """Create the client designed to process long-running operations.
244
245 This property caches on the instance; repeated calls return the same
246 client.
247 """
248 # Quick check: Only create a new client if we do not already have one.
249 if self._operations_client is None:
250 self._operations_client = operations_v1.OperationsAsyncClient(
251 self.grpc_channel
252 )
253
254 # Return the client from cache.
255 return self._operations_client
256
257 @property
258 def create_tag_hold(
259 self,
260 ) -> Callable[
261 [tag_holds.CreateTagHoldRequest], Awaitable[operations_pb2.Operation]
262 ]:
263 r"""Return a callable for the create tag hold method over gRPC.
264
265 Creates a TagHold. Returns ALREADY_EXISTS if a TagHold with the
266 same resource and origin exists under the same TagValue.
267
268 Returns:
269 Callable[[~.CreateTagHoldRequest],
270 Awaitable[~.Operation]]:
271 A function that, when called, will call the underlying RPC
272 on the server.
273 """
274 # Generate a "stub function" on-the-fly which will actually make
275 # the request.
276 # gRPC handles serialization and deserialization, so we just need
277 # to pass in the functions for each.
278 if "create_tag_hold" not in self._stubs:
279 self._stubs["create_tag_hold"] = self.grpc_channel.unary_unary(
280 "/google.cloud.resourcemanager.v3.TagHolds/CreateTagHold",
281 request_serializer=tag_holds.CreateTagHoldRequest.serialize,
282 response_deserializer=operations_pb2.Operation.FromString,
283 )
284 return self._stubs["create_tag_hold"]
285
286 @property
287 def delete_tag_hold(
288 self,
289 ) -> Callable[
290 [tag_holds.DeleteTagHoldRequest], Awaitable[operations_pb2.Operation]
291 ]:
292 r"""Return a callable for the delete tag hold method over gRPC.
293
294 Deletes a TagHold.
295
296 Returns:
297 Callable[[~.DeleteTagHoldRequest],
298 Awaitable[~.Operation]]:
299 A function that, when called, will call the underlying RPC
300 on the server.
301 """
302 # Generate a "stub function" on-the-fly which will actually make
303 # the request.
304 # gRPC handles serialization and deserialization, so we just need
305 # to pass in the functions for each.
306 if "delete_tag_hold" not in self._stubs:
307 self._stubs["delete_tag_hold"] = self.grpc_channel.unary_unary(
308 "/google.cloud.resourcemanager.v3.TagHolds/DeleteTagHold",
309 request_serializer=tag_holds.DeleteTagHoldRequest.serialize,
310 response_deserializer=operations_pb2.Operation.FromString,
311 )
312 return self._stubs["delete_tag_hold"]
313
314 @property
315 def list_tag_holds(
316 self,
317 ) -> Callable[
318 [tag_holds.ListTagHoldsRequest], Awaitable[tag_holds.ListTagHoldsResponse]
319 ]:
320 r"""Return a callable for the list tag holds method over gRPC.
321
322 Lists TagHolds under a TagValue.
323
324 Returns:
325 Callable[[~.ListTagHoldsRequest],
326 Awaitable[~.ListTagHoldsResponse]]:
327 A function that, when called, will call the underlying RPC
328 on the server.
329 """
330 # Generate a "stub function" on-the-fly which will actually make
331 # the request.
332 # gRPC handles serialization and deserialization, so we just need
333 # to pass in the functions for each.
334 if "list_tag_holds" not in self._stubs:
335 self._stubs["list_tag_holds"] = self.grpc_channel.unary_unary(
336 "/google.cloud.resourcemanager.v3.TagHolds/ListTagHolds",
337 request_serializer=tag_holds.ListTagHoldsRequest.serialize,
338 response_deserializer=tag_holds.ListTagHoldsResponse.deserialize,
339 )
340 return self._stubs["list_tag_holds"]
341
342 def close(self):
343 return self.grpc_channel.close()
344
345 @property
346 def get_operation(
347 self,
348 ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
349 r"""Return a callable for the get_operation method over gRPC."""
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 "get_operation" not in self._stubs:
355 self._stubs["get_operation"] = self.grpc_channel.unary_unary(
356 "/google.longrunning.Operations/GetOperation",
357 request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
358 response_deserializer=operations_pb2.Operation.FromString,
359 )
360 return self._stubs["get_operation"]
361
362
363__all__ = ("TagHoldsGrpcAsyncIOTransport",)