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_values
29
30from .base import DEFAULT_CLIENT_INFO, TagValuesTransport
31
32
33class TagValuesGrpcTransport(TagValuesTransport):
34 """gRPC backend transport for TagValues.
35
36 Allow users to create and manage tag values.
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_values(
251 self,
252 ) -> Callable[[tag_values.ListTagValuesRequest], tag_values.ListTagValuesResponse]:
253 r"""Return a callable for the list tag values method over gRPC.
254
255 Lists all TagValues for a specific TagKey.
256
257 Returns:
258 Callable[[~.ListTagValuesRequest],
259 ~.ListTagValuesResponse]:
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_values" not in self._stubs:
268 self._stubs["list_tag_values"] = self.grpc_channel.unary_unary(
269 "/google.cloud.resourcemanager.v3.TagValues/ListTagValues",
270 request_serializer=tag_values.ListTagValuesRequest.serialize,
271 response_deserializer=tag_values.ListTagValuesResponse.deserialize,
272 )
273 return self._stubs["list_tag_values"]
274
275 @property
276 def get_tag_value(
277 self,
278 ) -> Callable[[tag_values.GetTagValueRequest], tag_values.TagValue]:
279 r"""Return a callable for the get tag value method over gRPC.
280
281 Retrieves a TagValue. This method will return
282 ``PERMISSION_DENIED`` if the value does not exist or the user
283 does not have permission to view it.
284
285 Returns:
286 Callable[[~.GetTagValueRequest],
287 ~.TagValue]:
288 A function that, when called, will call the underlying RPC
289 on the server.
290 """
291 # Generate a "stub function" on-the-fly which will actually make
292 # the request.
293 # gRPC handles serialization and deserialization, so we just need
294 # to pass in the functions for each.
295 if "get_tag_value" not in self._stubs:
296 self._stubs["get_tag_value"] = self.grpc_channel.unary_unary(
297 "/google.cloud.resourcemanager.v3.TagValues/GetTagValue",
298 request_serializer=tag_values.GetTagValueRequest.serialize,
299 response_deserializer=tag_values.TagValue.deserialize,
300 )
301 return self._stubs["get_tag_value"]
302
303 @property
304 def get_namespaced_tag_value(
305 self,
306 ) -> Callable[[tag_values.GetNamespacedTagValueRequest], tag_values.TagValue]:
307 r"""Return a callable for the get namespaced tag value method over gRPC.
308
309 Retrieves a TagValue by its namespaced name. This method will
310 return ``PERMISSION_DENIED`` if the value does not exist or the
311 user does not have permission to view it.
312
313 Returns:
314 Callable[[~.GetNamespacedTagValueRequest],
315 ~.TagValue]:
316 A function that, when called, will call the underlying RPC
317 on the server.
318 """
319 # Generate a "stub function" on-the-fly which will actually make
320 # the request.
321 # gRPC handles serialization and deserialization, so we just need
322 # to pass in the functions for each.
323 if "get_namespaced_tag_value" not in self._stubs:
324 self._stubs["get_namespaced_tag_value"] = self.grpc_channel.unary_unary(
325 "/google.cloud.resourcemanager.v3.TagValues/GetNamespacedTagValue",
326 request_serializer=tag_values.GetNamespacedTagValueRequest.serialize,
327 response_deserializer=tag_values.TagValue.deserialize,
328 )
329 return self._stubs["get_namespaced_tag_value"]
330
331 @property
332 def create_tag_value(
333 self,
334 ) -> Callable[[tag_values.CreateTagValueRequest], operations_pb2.Operation]:
335 r"""Return a callable for the create tag value method over gRPC.
336
337 Creates a TagValue as a child of the specified
338 TagKey. If a another request with the same parameters is
339 sent while the original request is in process the second
340 request will receive an error. A maximum of 1000
341 TagValues can exist under a TagKey at any given time.
342
343 Returns:
344 Callable[[~.CreateTagValueRequest],
345 ~.Operation]:
346 A function that, when called, will call the underlying RPC
347 on the server.
348 """
349 # Generate a "stub function" on-the-fly which will actually make
350 # the request.
351 # gRPC handles serialization and deserialization, so we just need
352 # to pass in the functions for each.
353 if "create_tag_value" not in self._stubs:
354 self._stubs["create_tag_value"] = self.grpc_channel.unary_unary(
355 "/google.cloud.resourcemanager.v3.TagValues/CreateTagValue",
356 request_serializer=tag_values.CreateTagValueRequest.serialize,
357 response_deserializer=operations_pb2.Operation.FromString,
358 )
359 return self._stubs["create_tag_value"]
360
361 @property
362 def update_tag_value(
363 self,
364 ) -> Callable[[tag_values.UpdateTagValueRequest], operations_pb2.Operation]:
365 r"""Return a callable for the update tag value method over gRPC.
366
367 Updates the attributes of the TagValue resource.
368
369 Returns:
370 Callable[[~.UpdateTagValueRequest],
371 ~.Operation]:
372 A function that, when called, will call the underlying RPC
373 on the server.
374 """
375 # Generate a "stub function" on-the-fly which will actually make
376 # the request.
377 # gRPC handles serialization and deserialization, so we just need
378 # to pass in the functions for each.
379 if "update_tag_value" not in self._stubs:
380 self._stubs["update_tag_value"] = self.grpc_channel.unary_unary(
381 "/google.cloud.resourcemanager.v3.TagValues/UpdateTagValue",
382 request_serializer=tag_values.UpdateTagValueRequest.serialize,
383 response_deserializer=operations_pb2.Operation.FromString,
384 )
385 return self._stubs["update_tag_value"]
386
387 @property
388 def delete_tag_value(
389 self,
390 ) -> Callable[[tag_values.DeleteTagValueRequest], operations_pb2.Operation]:
391 r"""Return a callable for the delete tag value method over gRPC.
392
393 Deletes a TagValue. The TagValue cannot have any
394 bindings when it is deleted.
395
396 Returns:
397 Callable[[~.DeleteTagValueRequest],
398 ~.Operation]:
399 A function that, when called, will call the underlying RPC
400 on the server.
401 """
402 # Generate a "stub function" on-the-fly which will actually make
403 # the request.
404 # gRPC handles serialization and deserialization, so we just need
405 # to pass in the functions for each.
406 if "delete_tag_value" not in self._stubs:
407 self._stubs["delete_tag_value"] = self.grpc_channel.unary_unary(
408 "/google.cloud.resourcemanager.v3.TagValues/DeleteTagValue",
409 request_serializer=tag_values.DeleteTagValueRequest.serialize,
410 response_deserializer=operations_pb2.Operation.FromString,
411 )
412 return self._stubs["delete_tag_value"]
413
414 @property
415 def get_iam_policy(
416 self,
417 ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
418 r"""Return a callable for the get iam policy method over gRPC.
419
420 Gets the access control policy for a TagValue. The returned
421 policy may be empty if no such policy or resource exists. The
422 ``resource`` field should be the TagValue's resource name. For
423 example: ``tagValues/1234``. The caller must have the
424 ``cloudresourcemanager.googleapis.com/tagValues.getIamPolicy``
425 permission on the identified TagValue to get the access control
426 policy.
427
428 Returns:
429 Callable[[~.GetIamPolicyRequest],
430 ~.Policy]:
431 A function that, when called, will call the underlying RPC
432 on the server.
433 """
434 # Generate a "stub function" on-the-fly which will actually make
435 # the request.
436 # gRPC handles serialization and deserialization, so we just need
437 # to pass in the functions for each.
438 if "get_iam_policy" not in self._stubs:
439 self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary(
440 "/google.cloud.resourcemanager.v3.TagValues/GetIamPolicy",
441 request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
442 response_deserializer=policy_pb2.Policy.FromString,
443 )
444 return self._stubs["get_iam_policy"]
445
446 @property
447 def set_iam_policy(
448 self,
449 ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
450 r"""Return a callable for the set iam policy method over gRPC.
451
452 Sets the access control policy on a TagValue, replacing any
453 existing policy. The ``resource`` field should be the TagValue's
454 resource name. For example: ``tagValues/1234``. The caller must
455 have ``resourcemanager.tagValues.setIamPolicy`` permission on
456 the identified tagValue.
457
458 Returns:
459 Callable[[~.SetIamPolicyRequest],
460 ~.Policy]:
461 A function that, when called, will call the underlying RPC
462 on the server.
463 """
464 # Generate a "stub function" on-the-fly which will actually make
465 # the request.
466 # gRPC handles serialization and deserialization, so we just need
467 # to pass in the functions for each.
468 if "set_iam_policy" not in self._stubs:
469 self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary(
470 "/google.cloud.resourcemanager.v3.TagValues/SetIamPolicy",
471 request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
472 response_deserializer=policy_pb2.Policy.FromString,
473 )
474 return self._stubs["set_iam_policy"]
475
476 @property
477 def test_iam_permissions(
478 self,
479 ) -> Callable[
480 [iam_policy_pb2.TestIamPermissionsRequest],
481 iam_policy_pb2.TestIamPermissionsResponse,
482 ]:
483 r"""Return a callable for the test iam permissions method over gRPC.
484
485 Returns permissions that a caller has on the specified TagValue.
486 The ``resource`` field should be the TagValue's resource name.
487 For example: ``tagValues/1234``.
488
489 There are no permissions required for making this API call.
490
491 Returns:
492 Callable[[~.TestIamPermissionsRequest],
493 ~.TestIamPermissionsResponse]:
494 A function that, when called, will call the underlying RPC
495 on the server.
496 """
497 # Generate a "stub function" on-the-fly which will actually make
498 # the request.
499 # gRPC handles serialization and deserialization, so we just need
500 # to pass in the functions for each.
501 if "test_iam_permissions" not in self._stubs:
502 self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary(
503 "/google.cloud.resourcemanager.v3.TagValues/TestIamPermissions",
504 request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
505 response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
506 )
507 return self._stubs["test_iam_permissions"]
508
509 def close(self):
510 self.grpc_channel.close()
511
512 @property
513 def get_operation(
514 self,
515 ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
516 r"""Return a callable for the get_operation method over gRPC."""
517 # Generate a "stub function" on-the-fly which will actually make
518 # the request.
519 # gRPC handles serialization and deserialization, so we just need
520 # to pass in the functions for each.
521 if "get_operation" not in self._stubs:
522 self._stubs["get_operation"] = self.grpc_channel.unary_unary(
523 "/google.longrunning.Operations/GetOperation",
524 request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
525 response_deserializer=operations_pb2.Operation.FromString,
526 )
527 return self._stubs["get_operation"]
528
529 @property
530 def kind(self) -> str:
531 return "grpc"
532
533
534__all__ = ("TagValuesGrpcTransport",)