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