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 Callable, Dict, Optional, Sequence, Tuple, Union
17import warnings
18
19from google.api_core import gapic_v1, grpc_helpers, operations_v1
20import google.auth # type: ignore
21from google.auth import credentials as ga_credentials # type: ignore
22from google.auth.transport.grpc import SslCredentials # type: ignore
23from google.iam.v1 import iam_policy_pb2 # type: ignore
24from google.iam.v1 import policy_pb2 # type: ignore
25from google.longrunning import operations_pb2 # type: ignore
26import grpc # type: ignore
27
28from google.cloud.resourcemanager_v3.types import tag_keys
29
30from .base import DEFAULT_CLIENT_INFO, TagKeysTransport
31
32
33class TagKeysGrpcTransport(TagKeysTransport):
34 """gRPC backend transport for TagKeys.
35
36 Allow users to create and manage tag keys.
37
38 This class defines the same methods as the primary client, so the
39 primary client can load the underlying transport implementation
40 and call it.
41
42 It sends protocol buffers over the wire using gRPC (which is built on
43 top of HTTP/2); the ``grpcio`` package must be installed.
44 """
45
46 _stubs: Dict[str, Callable]
47
48 def __init__(
49 self,
50 *,
51 host: str = "cloudresourcemanager.googleapis.com",
52 credentials: Optional[ga_credentials.Credentials] = None,
53 credentials_file: Optional[str] = None,
54 scopes: Optional[Sequence[str]] = None,
55 channel: Optional[grpc.Channel] = None,
56 api_mtls_endpoint: Optional[str] = None,
57 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
58 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
59 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
60 quota_project_id: Optional[str] = None,
61 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
62 always_use_jwt_access: Optional[bool] = False,
63 api_audience: Optional[str] = None,
64 ) -> None:
65 """Instantiate the transport.
66
67 Args:
68 host (Optional[str]):
69 The hostname to connect to.
70 credentials (Optional[google.auth.credentials.Credentials]): The
71 authorization credentials to attach to requests. These
72 credentials identify the application to the service; if none
73 are specified, the client will attempt to ascertain the
74 credentials from the environment.
75 This argument is ignored if ``channel`` is provided.
76 credentials_file (Optional[str]): A file with credentials that can
77 be loaded with :func:`google.auth.load_credentials_from_file`.
78 This argument is ignored if ``channel`` is provided.
79 scopes (Optional(Sequence[str])): A list of scopes. This argument is
80 ignored if ``channel`` is provided.
81 channel (Optional[grpc.Channel]): A ``Channel`` instance through
82 which to make calls.
83 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
84 If provided, it overrides the ``host`` argument and tries to create
85 a mutual TLS channel with client SSL credentials from
86 ``client_cert_source`` or application default SSL credentials.
87 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
88 Deprecated. A callback to provide client SSL certificate bytes and
89 private key bytes, both in PEM format. It is ignored if
90 ``api_mtls_endpoint`` is None.
91 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
92 for the grpc channel. It is ignored if ``channel`` is provided.
93 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
94 A callback to provide client certificate bytes and private key bytes,
95 both in PEM format. It is used to configure a mutual TLS channel. It is
96 ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
97 quota_project_id (Optional[str]): An optional project to use for billing
98 and quota.
99 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
100 The client info used to send a user-agent string along with
101 API requests. If ``None``, then default info will be used.
102 Generally, you only need to set this if you're developing
103 your own client library.
104 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
105 be used for service account credentials.
106
107 Raises:
108 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
109 creation failed for any reason.
110 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
111 and ``credentials_file`` are passed.
112 """
113 self._grpc_channel = None
114 self._ssl_channel_credentials = ssl_channel_credentials
115 self._stubs: Dict[str, Callable] = {}
116 self._operations_client: Optional[operations_v1.OperationsClient] = None
117
118 if api_mtls_endpoint:
119 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
120 if client_cert_source:
121 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
122
123 if channel:
124 # Ignore credentials if a channel was passed.
125 credentials = False
126 # If a channel was explicitly provided, set it.
127 self._grpc_channel = channel
128 self._ssl_channel_credentials = None
129
130 else:
131 if api_mtls_endpoint:
132 host = api_mtls_endpoint
133
134 # Create SSL credentials with client_cert_source or application
135 # default SSL credentials.
136 if client_cert_source:
137 cert, key = client_cert_source()
138 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
139 certificate_chain=cert, private_key=key
140 )
141 else:
142 self._ssl_channel_credentials = SslCredentials().ssl_credentials
143
144 else:
145 if client_cert_source_for_mtls and not ssl_channel_credentials:
146 cert, key = client_cert_source_for_mtls()
147 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
148 certificate_chain=cert, private_key=key
149 )
150
151 # The base transport sets the host, credentials and scopes
152 super().__init__(
153 host=host,
154 credentials=credentials,
155 credentials_file=credentials_file,
156 scopes=scopes,
157 quota_project_id=quota_project_id,
158 client_info=client_info,
159 always_use_jwt_access=always_use_jwt_access,
160 api_audience=api_audience,
161 )
162
163 if not self._grpc_channel:
164 self._grpc_channel = type(self).create_channel(
165 self._host,
166 # use the credentials which are saved
167 credentials=self._credentials,
168 # Set ``credentials_file`` to ``None`` here as
169 # the credentials that we saved earlier should be used.
170 credentials_file=None,
171 scopes=self._scopes,
172 ssl_credentials=self._ssl_channel_credentials,
173 quota_project_id=quota_project_id,
174 options=[
175 ("grpc.max_send_message_length", -1),
176 ("grpc.max_receive_message_length", -1),
177 ],
178 )
179
180 # Wrap messages. This must be done after self._grpc_channel exists
181 self._prep_wrapped_messages(client_info)
182
183 @classmethod
184 def create_channel(
185 cls,
186 host: str = "cloudresourcemanager.googleapis.com",
187 credentials: Optional[ga_credentials.Credentials] = None,
188 credentials_file: Optional[str] = None,
189 scopes: Optional[Sequence[str]] = None,
190 quota_project_id: Optional[str] = None,
191 **kwargs,
192 ) -> grpc.Channel:
193 """Create and return a gRPC channel object.
194 Args:
195 host (Optional[str]): The host for the channel to use.
196 credentials (Optional[~.Credentials]): The
197 authorization credentials to attach to requests. These
198 credentials identify this application to the service. If
199 none are specified, the client will attempt to ascertain
200 the credentials from the environment.
201 credentials_file (Optional[str]): A file with credentials that can
202 be loaded with :func:`google.auth.load_credentials_from_file`.
203 This argument is mutually exclusive with credentials.
204 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
205 service. These are only used when credentials are not specified and
206 are passed to :func:`google.auth.default`.
207 quota_project_id (Optional[str]): An optional project to use for billing
208 and quota.
209 kwargs (Optional[dict]): Keyword arguments, which are passed to the
210 channel creation.
211 Returns:
212 grpc.Channel: A gRPC channel object.
213
214 Raises:
215 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
216 and ``credentials_file`` are passed.
217 """
218
219 return grpc_helpers.create_channel(
220 host,
221 credentials=credentials,
222 credentials_file=credentials_file,
223 quota_project_id=quota_project_id,
224 default_scopes=cls.AUTH_SCOPES,
225 scopes=scopes,
226 default_host=cls.DEFAULT_HOST,
227 **kwargs,
228 )
229
230 @property
231 def grpc_channel(self) -> grpc.Channel:
232 """Return the channel designed to connect to this service."""
233 return self._grpc_channel
234
235 @property
236 def operations_client(self) -> operations_v1.OperationsClient:
237 """Create the client designed to process long-running operations.
238
239 This property caches on the instance; repeated calls return the same
240 client.
241 """
242 # Quick check: Only create a new client if we do not already have one.
243 if self._operations_client is None:
244 self._operations_client = operations_v1.OperationsClient(self.grpc_channel)
245
246 # Return the client from cache.
247 return self._operations_client
248
249 @property
250 def list_tag_keys(
251 self,
252 ) -> Callable[[tag_keys.ListTagKeysRequest], tag_keys.ListTagKeysResponse]:
253 r"""Return a callable for the list tag keys method over gRPC.
254
255 Lists all TagKeys for a parent resource.
256
257 Returns:
258 Callable[[~.ListTagKeysRequest],
259 ~.ListTagKeysResponse]:
260 A function that, when called, will call the underlying RPC
261 on the server.
262 """
263 # Generate a "stub function" on-the-fly which will actually make
264 # the request.
265 # gRPC handles serialization and deserialization, so we just need
266 # to pass in the functions for each.
267 if "list_tag_keys" not in self._stubs:
268 self._stubs["list_tag_keys"] = self.grpc_channel.unary_unary(
269 "/google.cloud.resourcemanager.v3.TagKeys/ListTagKeys",
270 request_serializer=tag_keys.ListTagKeysRequest.serialize,
271 response_deserializer=tag_keys.ListTagKeysResponse.deserialize,
272 )
273 return self._stubs["list_tag_keys"]
274
275 @property
276 def get_tag_key(self) -> Callable[[tag_keys.GetTagKeyRequest], tag_keys.TagKey]:
277 r"""Return a callable for the get tag key method over gRPC.
278
279 Retrieves a TagKey. This method will return
280 ``PERMISSION_DENIED`` if the key does not exist or the user does
281 not have permission to view it.
282
283 Returns:
284 Callable[[~.GetTagKeyRequest],
285 ~.TagKey]:
286 A function that, when called, will call the underlying RPC
287 on the server.
288 """
289 # Generate a "stub function" on-the-fly which will actually make
290 # the request.
291 # gRPC handles serialization and deserialization, so we just need
292 # to pass in the functions for each.
293 if "get_tag_key" not in self._stubs:
294 self._stubs["get_tag_key"] = self.grpc_channel.unary_unary(
295 "/google.cloud.resourcemanager.v3.TagKeys/GetTagKey",
296 request_serializer=tag_keys.GetTagKeyRequest.serialize,
297 response_deserializer=tag_keys.TagKey.deserialize,
298 )
299 return self._stubs["get_tag_key"]
300
301 @property
302 def get_namespaced_tag_key(
303 self,
304 ) -> Callable[[tag_keys.GetNamespacedTagKeyRequest], tag_keys.TagKey]:
305 r"""Return a callable for the get namespaced tag key method over gRPC.
306
307 Retrieves a TagKey by its namespaced name. This method will
308 return ``PERMISSION_DENIED`` if the key does not exist or the
309 user does not have permission to view it.
310
311 Returns:
312 Callable[[~.GetNamespacedTagKeyRequest],
313 ~.TagKey]:
314 A function that, when called, will call the underlying RPC
315 on the server.
316 """
317 # Generate a "stub function" on-the-fly which will actually make
318 # the request.
319 # gRPC handles serialization and deserialization, so we just need
320 # to pass in the functions for each.
321 if "get_namespaced_tag_key" not in self._stubs:
322 self._stubs["get_namespaced_tag_key"] = self.grpc_channel.unary_unary(
323 "/google.cloud.resourcemanager.v3.TagKeys/GetNamespacedTagKey",
324 request_serializer=tag_keys.GetNamespacedTagKeyRequest.serialize,
325 response_deserializer=tag_keys.TagKey.deserialize,
326 )
327 return self._stubs["get_namespaced_tag_key"]
328
329 @property
330 def create_tag_key(
331 self,
332 ) -> Callable[[tag_keys.CreateTagKeyRequest], operations_pb2.Operation]:
333 r"""Return a callable for the create tag key method over gRPC.
334
335 Creates a new TagKey. If another request with the
336 same parameters is sent while the original request is in
337 process, the second request will receive an error. A
338 maximum of 1000 TagKeys can exist under a parent at any
339 given time.
340
341 Returns:
342 Callable[[~.CreateTagKeyRequest],
343 ~.Operation]:
344 A function that, when called, will call the underlying RPC
345 on the server.
346 """
347 # Generate a "stub function" on-the-fly which will actually make
348 # the request.
349 # gRPC handles serialization and deserialization, so we just need
350 # to pass in the functions for each.
351 if "create_tag_key" not in self._stubs:
352 self._stubs["create_tag_key"] = self.grpc_channel.unary_unary(
353 "/google.cloud.resourcemanager.v3.TagKeys/CreateTagKey",
354 request_serializer=tag_keys.CreateTagKeyRequest.serialize,
355 response_deserializer=operations_pb2.Operation.FromString,
356 )
357 return self._stubs["create_tag_key"]
358
359 @property
360 def update_tag_key(
361 self,
362 ) -> Callable[[tag_keys.UpdateTagKeyRequest], operations_pb2.Operation]:
363 r"""Return a callable for the update tag key method over gRPC.
364
365 Updates the attributes of the TagKey resource.
366
367 Returns:
368 Callable[[~.UpdateTagKeyRequest],
369 ~.Operation]:
370 A function that, when called, will call the underlying RPC
371 on the server.
372 """
373 # Generate a "stub function" on-the-fly which will actually make
374 # the request.
375 # gRPC handles serialization and deserialization, so we just need
376 # to pass in the functions for each.
377 if "update_tag_key" not in self._stubs:
378 self._stubs["update_tag_key"] = self.grpc_channel.unary_unary(
379 "/google.cloud.resourcemanager.v3.TagKeys/UpdateTagKey",
380 request_serializer=tag_keys.UpdateTagKeyRequest.serialize,
381 response_deserializer=operations_pb2.Operation.FromString,
382 )
383 return self._stubs["update_tag_key"]
384
385 @property
386 def delete_tag_key(
387 self,
388 ) -> Callable[[tag_keys.DeleteTagKeyRequest], operations_pb2.Operation]:
389 r"""Return a callable for the delete tag key method over gRPC.
390
391 Deletes a TagKey. The TagKey cannot be deleted if it
392 has any child TagValues.
393
394 Returns:
395 Callable[[~.DeleteTagKeyRequest],
396 ~.Operation]:
397 A function that, when called, will call the underlying RPC
398 on the server.
399 """
400 # Generate a "stub function" on-the-fly which will actually make
401 # the request.
402 # gRPC handles serialization and deserialization, so we just need
403 # to pass in the functions for each.
404 if "delete_tag_key" not in self._stubs:
405 self._stubs["delete_tag_key"] = self.grpc_channel.unary_unary(
406 "/google.cloud.resourcemanager.v3.TagKeys/DeleteTagKey",
407 request_serializer=tag_keys.DeleteTagKeyRequest.serialize,
408 response_deserializer=operations_pb2.Operation.FromString,
409 )
410 return self._stubs["delete_tag_key"]
411
412 @property
413 def get_iam_policy(
414 self,
415 ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
416 r"""Return a callable for the get iam policy method over gRPC.
417
418 Gets the access control policy for a TagKey. The returned policy
419 may be empty if no such policy or resource exists. The
420 ``resource`` field should be the TagKey's resource name. For
421 example, "tagKeys/1234". The caller must have
422 ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy``
423 permission on the specified TagKey.
424
425 Returns:
426 Callable[[~.GetIamPolicyRequest],
427 ~.Policy]:
428 A function that, when called, will call the underlying RPC
429 on the server.
430 """
431 # Generate a "stub function" on-the-fly which will actually make
432 # the request.
433 # gRPC handles serialization and deserialization, so we just need
434 # to pass in the functions for each.
435 if "get_iam_policy" not in self._stubs:
436 self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary(
437 "/google.cloud.resourcemanager.v3.TagKeys/GetIamPolicy",
438 request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
439 response_deserializer=policy_pb2.Policy.FromString,
440 )
441 return self._stubs["get_iam_policy"]
442
443 @property
444 def set_iam_policy(
445 self,
446 ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
447 r"""Return a callable for the set iam policy method over gRPC.
448
449 Sets the access control policy on a TagKey, replacing any
450 existing policy. The ``resource`` field should be the TagKey's
451 resource name. For example, "tagKeys/1234". The caller must have
452 ``resourcemanager.tagKeys.setIamPolicy`` permission on the
453 identified tagValue.
454
455 Returns:
456 Callable[[~.SetIamPolicyRequest],
457 ~.Policy]:
458 A function that, when called, will call the underlying RPC
459 on the server.
460 """
461 # Generate a "stub function" on-the-fly which will actually make
462 # the request.
463 # gRPC handles serialization and deserialization, so we just need
464 # to pass in the functions for each.
465 if "set_iam_policy" not in self._stubs:
466 self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary(
467 "/google.cloud.resourcemanager.v3.TagKeys/SetIamPolicy",
468 request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
469 response_deserializer=policy_pb2.Policy.FromString,
470 )
471 return self._stubs["set_iam_policy"]
472
473 @property
474 def test_iam_permissions(
475 self,
476 ) -> Callable[
477 [iam_policy_pb2.TestIamPermissionsRequest],
478 iam_policy_pb2.TestIamPermissionsResponse,
479 ]:
480 r"""Return a callable for the test iam permissions method over gRPC.
481
482 Returns permissions that a caller has on the specified TagKey.
483 The ``resource`` field should be the TagKey's resource name. For
484 example, "tagKeys/1234".
485
486 There are no permissions required for making this API call.
487
488 Returns:
489 Callable[[~.TestIamPermissionsRequest],
490 ~.TestIamPermissionsResponse]:
491 A function that, when called, will call the underlying RPC
492 on the server.
493 """
494 # Generate a "stub function" on-the-fly which will actually make
495 # the request.
496 # gRPC handles serialization and deserialization, so we just need
497 # to pass in the functions for each.
498 if "test_iam_permissions" not in self._stubs:
499 self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary(
500 "/google.cloud.resourcemanager.v3.TagKeys/TestIamPermissions",
501 request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
502 response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
503 )
504 return self._stubs["test_iam_permissions"]
505
506 def close(self):
507 self.grpc_channel.close()
508
509 @property
510 def get_operation(
511 self,
512 ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
513 r"""Return a callable for the get_operation method over gRPC."""
514 # Generate a "stub function" on-the-fly which will actually make
515 # the request.
516 # gRPC handles serialization and deserialization, so we just need
517 # to pass in the functions for each.
518 if "get_operation" not in self._stubs:
519 self._stubs["get_operation"] = self.grpc_channel.unary_unary(
520 "/google.longrunning.Operations/GetOperation",
521 request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
522 response_deserializer=operations_pb2.Operation.FromString,
523 )
524 return self._stubs["get_operation"]
525
526 @property
527 def kind(self) -> str:
528 return "grpc"
529
530
531__all__ = ("TagKeysGrpcTransport",)