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 collections import OrderedDict
17import os
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Sequence,
26 Tuple,
27 Type,
28 Union,
29 cast,
30)
31
32from google.api_core import client_options as client_options_lib
33from google.api_core import exceptions as core_exceptions
34from google.api_core import gapic_v1
35from google.api_core import retry as retries
36from google.auth import credentials as ga_credentials # type: ignore
37from google.auth.exceptions import MutualTLSChannelError # type: ignore
38from google.auth.transport import mtls # type: ignore
39from google.auth.transport.grpc import SslCredentials # type: ignore
40from google.oauth2 import service_account # type: ignore
41
42from google.cloud.resourcemanager_v3 import gapic_version as package_version
43
44try:
45 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
46except AttributeError: # pragma: NO COVER
47 OptionalRetry = Union[retries.Retry, object] # type: ignore
48
49from google.api_core import operation # type: ignore
50from google.api_core import operation_async # type: ignore
51from google.longrunning import operations_pb2
52from google.protobuf import empty_pb2 # type: ignore
53
54from google.cloud.resourcemanager_v3.services.tag_bindings import pagers
55from google.cloud.resourcemanager_v3.types import tag_bindings
56
57from .transports.base import DEFAULT_CLIENT_INFO, TagBindingsTransport
58from .transports.grpc import TagBindingsGrpcTransport
59from .transports.grpc_asyncio import TagBindingsGrpcAsyncIOTransport
60from .transports.rest import TagBindingsRestTransport
61
62
63class TagBindingsClientMeta(type):
64 """Metaclass for the TagBindings client.
65
66 This provides class-level methods for building and retrieving
67 support objects (e.g. transport) without polluting the client instance
68 objects.
69 """
70
71 _transport_registry = OrderedDict() # type: Dict[str, Type[TagBindingsTransport]]
72 _transport_registry["grpc"] = TagBindingsGrpcTransport
73 _transport_registry["grpc_asyncio"] = TagBindingsGrpcAsyncIOTransport
74 _transport_registry["rest"] = TagBindingsRestTransport
75
76 def get_transport_class(
77 cls,
78 label: Optional[str] = None,
79 ) -> Type[TagBindingsTransport]:
80 """Returns an appropriate transport class.
81
82 Args:
83 label: The name of the desired transport. If none is
84 provided, then the first transport in the registry is used.
85
86 Returns:
87 The transport class to use.
88 """
89 # If a specific transport is requested, return that one.
90 if label:
91 return cls._transport_registry[label]
92
93 # No transport is requested; return the default (that is, the first one
94 # in the dictionary).
95 return next(iter(cls._transport_registry.values()))
96
97
98class TagBindingsClient(metaclass=TagBindingsClientMeta):
99 """Allow users to create and manage TagBindings between
100 TagValues and different Google Cloud resources throughout the
101 GCP resource hierarchy.
102 """
103
104 @staticmethod
105 def _get_default_mtls_endpoint(api_endpoint):
106 """Converts api endpoint to mTLS endpoint.
107
108 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
109 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
110 Args:
111 api_endpoint (Optional[str]): the api endpoint to convert.
112 Returns:
113 str: converted mTLS api endpoint.
114 """
115 if not api_endpoint:
116 return api_endpoint
117
118 mtls_endpoint_re = re.compile(
119 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
120 )
121
122 m = mtls_endpoint_re.match(api_endpoint)
123 name, mtls, sandbox, googledomain = m.groups()
124 if mtls or not googledomain:
125 return api_endpoint
126
127 if sandbox:
128 return api_endpoint.replace(
129 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
130 )
131
132 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
133
134 DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com"
135 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
136 DEFAULT_ENDPOINT
137 )
138
139 @classmethod
140 def from_service_account_info(cls, info: dict, *args, **kwargs):
141 """Creates an instance of this client using the provided credentials
142 info.
143
144 Args:
145 info (dict): The service account private key info.
146 args: Additional arguments to pass to the constructor.
147 kwargs: Additional arguments to pass to the constructor.
148
149 Returns:
150 TagBindingsClient: The constructed client.
151 """
152 credentials = service_account.Credentials.from_service_account_info(info)
153 kwargs["credentials"] = credentials
154 return cls(*args, **kwargs)
155
156 @classmethod
157 def from_service_account_file(cls, filename: str, *args, **kwargs):
158 """Creates an instance of this client using the provided credentials
159 file.
160
161 Args:
162 filename (str): The path to the service account private key json
163 file.
164 args: Additional arguments to pass to the constructor.
165 kwargs: Additional arguments to pass to the constructor.
166
167 Returns:
168 TagBindingsClient: The constructed client.
169 """
170 credentials = service_account.Credentials.from_service_account_file(filename)
171 kwargs["credentials"] = credentials
172 return cls(*args, **kwargs)
173
174 from_service_account_json = from_service_account_file
175
176 @property
177 def transport(self) -> TagBindingsTransport:
178 """Returns the transport used by the client instance.
179
180 Returns:
181 TagBindingsTransport: The transport used by the client
182 instance.
183 """
184 return self._transport
185
186 @staticmethod
187 def tag_binding_path(
188 tag_binding: str,
189 ) -> str:
190 """Returns a fully-qualified tag_binding string."""
191 return "tagBindings/{tag_binding}".format(
192 tag_binding=tag_binding,
193 )
194
195 @staticmethod
196 def parse_tag_binding_path(path: str) -> Dict[str, str]:
197 """Parses a tag_binding path into its component segments."""
198 m = re.match(r"^tagBindings/(?P<tag_binding>.+?)$", path)
199 return m.groupdict() if m else {}
200
201 @staticmethod
202 def tag_key_path(
203 tag_key: str,
204 ) -> str:
205 """Returns a fully-qualified tag_key string."""
206 return "tagKeys/{tag_key}".format(
207 tag_key=tag_key,
208 )
209
210 @staticmethod
211 def parse_tag_key_path(path: str) -> Dict[str, str]:
212 """Parses a tag_key path into its component segments."""
213 m = re.match(r"^tagKeys/(?P<tag_key>.+?)$", path)
214 return m.groupdict() if m else {}
215
216 @staticmethod
217 def tag_value_path(
218 tag_value: str,
219 ) -> str:
220 """Returns a fully-qualified tag_value string."""
221 return "tagValues/{tag_value}".format(
222 tag_value=tag_value,
223 )
224
225 @staticmethod
226 def parse_tag_value_path(path: str) -> Dict[str, str]:
227 """Parses a tag_value path into its component segments."""
228 m = re.match(r"^tagValues/(?P<tag_value>.+?)$", path)
229 return m.groupdict() if m else {}
230
231 @staticmethod
232 def common_billing_account_path(
233 billing_account: str,
234 ) -> str:
235 """Returns a fully-qualified billing_account string."""
236 return "billingAccounts/{billing_account}".format(
237 billing_account=billing_account,
238 )
239
240 @staticmethod
241 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
242 """Parse a billing_account path into its component segments."""
243 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
244 return m.groupdict() if m else {}
245
246 @staticmethod
247 def common_folder_path(
248 folder: str,
249 ) -> str:
250 """Returns a fully-qualified folder string."""
251 return "folders/{folder}".format(
252 folder=folder,
253 )
254
255 @staticmethod
256 def parse_common_folder_path(path: str) -> Dict[str, str]:
257 """Parse a folder path into its component segments."""
258 m = re.match(r"^folders/(?P<folder>.+?)$", path)
259 return m.groupdict() if m else {}
260
261 @staticmethod
262 def common_organization_path(
263 organization: str,
264 ) -> str:
265 """Returns a fully-qualified organization string."""
266 return "organizations/{organization}".format(
267 organization=organization,
268 )
269
270 @staticmethod
271 def parse_common_organization_path(path: str) -> Dict[str, str]:
272 """Parse a organization path into its component segments."""
273 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
274 return m.groupdict() if m else {}
275
276 @staticmethod
277 def common_project_path(
278 project: str,
279 ) -> str:
280 """Returns a fully-qualified project string."""
281 return "projects/{project}".format(
282 project=project,
283 )
284
285 @staticmethod
286 def parse_common_project_path(path: str) -> Dict[str, str]:
287 """Parse a project path into its component segments."""
288 m = re.match(r"^projects/(?P<project>.+?)$", path)
289 return m.groupdict() if m else {}
290
291 @staticmethod
292 def common_location_path(
293 project: str,
294 location: str,
295 ) -> str:
296 """Returns a fully-qualified location string."""
297 return "projects/{project}/locations/{location}".format(
298 project=project,
299 location=location,
300 )
301
302 @staticmethod
303 def parse_common_location_path(path: str) -> Dict[str, str]:
304 """Parse a location path into its component segments."""
305 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
306 return m.groupdict() if m else {}
307
308 @classmethod
309 def get_mtls_endpoint_and_cert_source(
310 cls, client_options: Optional[client_options_lib.ClientOptions] = None
311 ):
312 """Return the API endpoint and client cert source for mutual TLS.
313
314 The client cert source is determined in the following order:
315 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
316 client cert source is None.
317 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
318 default client cert source exists, use the default one; otherwise the client cert
319 source is None.
320
321 The API endpoint is determined in the following order:
322 (1) if `client_options.api_endpoint` if provided, use the provided one.
323 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
324 default mTLS endpoint; if the environment variable is "never", use the default API
325 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
326 use the default API endpoint.
327
328 More details can be found at https://google.aip.dev/auth/4114.
329
330 Args:
331 client_options (google.api_core.client_options.ClientOptions): Custom options for the
332 client. Only the `api_endpoint` and `client_cert_source` properties may be used
333 in this method.
334
335 Returns:
336 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
337 client cert source to use.
338
339 Raises:
340 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
341 """
342 if client_options is None:
343 client_options = client_options_lib.ClientOptions()
344 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
345 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
346 if use_client_cert not in ("true", "false"):
347 raise ValueError(
348 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
349 )
350 if use_mtls_endpoint not in ("auto", "never", "always"):
351 raise MutualTLSChannelError(
352 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
353 )
354
355 # Figure out the client cert source to use.
356 client_cert_source = None
357 if use_client_cert == "true":
358 if client_options.client_cert_source:
359 client_cert_source = client_options.client_cert_source
360 elif mtls.has_default_client_cert_source():
361 client_cert_source = mtls.default_client_cert_source()
362
363 # Figure out which api endpoint to use.
364 if client_options.api_endpoint is not None:
365 api_endpoint = client_options.api_endpoint
366 elif use_mtls_endpoint == "always" or (
367 use_mtls_endpoint == "auto" and client_cert_source
368 ):
369 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
370 else:
371 api_endpoint = cls.DEFAULT_ENDPOINT
372
373 return api_endpoint, client_cert_source
374
375 def __init__(
376 self,
377 *,
378 credentials: Optional[ga_credentials.Credentials] = None,
379 transport: Optional[Union[str, TagBindingsTransport]] = None,
380 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
381 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
382 ) -> None:
383 """Instantiates the tag bindings client.
384
385 Args:
386 credentials (Optional[google.auth.credentials.Credentials]): The
387 authorization credentials to attach to requests. These
388 credentials identify the application to the service; if none
389 are specified, the client will attempt to ascertain the
390 credentials from the environment.
391 transport (Union[str, TagBindingsTransport]): The
392 transport to use. If set to None, a transport is chosen
393 automatically.
394 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
395 client. It won't take effect if a ``transport`` instance is provided.
396 (1) The ``api_endpoint`` property can be used to override the
397 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
398 environment variable can also be used to override the endpoint:
399 "always" (always use the default mTLS endpoint), "never" (always
400 use the default regular endpoint) and "auto" (auto switch to the
401 default mTLS endpoint if client certificate is present, this is
402 the default value). However, the ``api_endpoint`` property takes
403 precedence if provided.
404 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
405 is "true", then the ``client_cert_source`` property can be used
406 to provide client certificate for mutual TLS transport. If
407 not provided, the default SSL client certificate will be used if
408 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
409 set, no client certificate will be used.
410 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
411 The client info used to send a user-agent string along with
412 API requests. If ``None``, then default info will be used.
413 Generally, you only need to set this if you're developing
414 your own client library.
415
416 Raises:
417 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
418 creation failed for any reason.
419 """
420 if isinstance(client_options, dict):
421 client_options = client_options_lib.from_dict(client_options)
422 if client_options is None:
423 client_options = client_options_lib.ClientOptions()
424 client_options = cast(client_options_lib.ClientOptions, client_options)
425
426 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
427 client_options
428 )
429
430 api_key_value = getattr(client_options, "api_key", None)
431 if api_key_value and credentials:
432 raise ValueError(
433 "client_options.api_key and credentials are mutually exclusive"
434 )
435
436 # Save or instantiate the transport.
437 # Ordinarily, we provide the transport, but allowing a custom transport
438 # instance provides an extensibility point for unusual situations.
439 if isinstance(transport, TagBindingsTransport):
440 # transport is a TagBindingsTransport instance.
441 if credentials or client_options.credentials_file or api_key_value:
442 raise ValueError(
443 "When providing a transport instance, "
444 "provide its credentials directly."
445 )
446 if client_options.scopes:
447 raise ValueError(
448 "When providing a transport instance, provide its scopes "
449 "directly."
450 )
451 self._transport = transport
452 else:
453 import google.auth._default # type: ignore
454
455 if api_key_value and hasattr(
456 google.auth._default, "get_api_key_credentials"
457 ):
458 credentials = google.auth._default.get_api_key_credentials(
459 api_key_value
460 )
461
462 Transport = type(self).get_transport_class(transport)
463 self._transport = Transport(
464 credentials=credentials,
465 credentials_file=client_options.credentials_file,
466 host=api_endpoint,
467 scopes=client_options.scopes,
468 client_cert_source_for_mtls=client_cert_source_func,
469 quota_project_id=client_options.quota_project_id,
470 client_info=client_info,
471 always_use_jwt_access=True,
472 api_audience=client_options.api_audience,
473 )
474
475 def list_tag_bindings(
476 self,
477 request: Optional[Union[tag_bindings.ListTagBindingsRequest, dict]] = None,
478 *,
479 parent: Optional[str] = None,
480 retry: OptionalRetry = gapic_v1.method.DEFAULT,
481 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
482 metadata: Sequence[Tuple[str, str]] = (),
483 ) -> pagers.ListTagBindingsPager:
484 r"""Lists the TagBindings for the given Google Cloud resource, as
485 specified with ``parent``.
486
487 NOTE: The ``parent`` field is expected to be a full resource
488 name:
489 https://cloud.google.com/apis/design/resource_names#full_resource_name
490
491 .. code-block:: python
492
493 # This snippet has been automatically generated and should be regarded as a
494 # code template only.
495 # It will require modifications to work:
496 # - It may require correct/in-range values for request initialization.
497 # - It may require specifying regional endpoints when creating the service
498 # client as shown in:
499 # https://googleapis.dev/python/google-api-core/latest/client_options.html
500 from google.cloud import resourcemanager_v3
501
502 def sample_list_tag_bindings():
503 # Create a client
504 client = resourcemanager_v3.TagBindingsClient()
505
506 # Initialize request argument(s)
507 request = resourcemanager_v3.ListTagBindingsRequest(
508 parent="parent_value",
509 )
510
511 # Make the request
512 page_result = client.list_tag_bindings(request=request)
513
514 # Handle the response
515 for response in page_result:
516 print(response)
517
518 Args:
519 request (Union[google.cloud.resourcemanager_v3.types.ListTagBindingsRequest, dict]):
520 The request object. The request message to list all
521 TagBindings for a parent.
522 parent (str):
523 Required. The full resource name of a
524 resource for which you want to list
525 existing TagBindings. E.g.
526 "//cloudresourcemanager.googleapis.com/projects/123"
527
528 This corresponds to the ``parent`` field
529 on the ``request`` instance; if ``request`` is provided, this
530 should not be set.
531 retry (google.api_core.retry.Retry): Designation of what errors, if any,
532 should be retried.
533 timeout (float): The timeout for this request.
534 metadata (Sequence[Tuple[str, str]]): Strings which should be
535 sent along with the request as metadata.
536
537 Returns:
538 google.cloud.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsPager:
539 The ListTagBindings response.
540 Iterating over this object will yield
541 results and resolve additional pages
542 automatically.
543
544 """
545 # Create or coerce a protobuf request object.
546 # Quick check: If we got a request object, we should *not* have
547 # gotten any keyword arguments that map to the request.
548 has_flattened_params = any([parent])
549 if request is not None and has_flattened_params:
550 raise ValueError(
551 "If the `request` argument is set, then none of "
552 "the individual field arguments should be set."
553 )
554
555 # Minor optimization to avoid making a copy if the user passes
556 # in a tag_bindings.ListTagBindingsRequest.
557 # There's no risk of modifying the input as we've already verified
558 # there are no flattened fields.
559 if not isinstance(request, tag_bindings.ListTagBindingsRequest):
560 request = tag_bindings.ListTagBindingsRequest(request)
561 # If we have keyword arguments corresponding to fields on the
562 # request, apply these.
563 if parent is not None:
564 request.parent = parent
565
566 # Wrap the RPC method; this adds retry and timeout information,
567 # and friendly error handling.
568 rpc = self._transport._wrapped_methods[self._transport.list_tag_bindings]
569
570 # Send the request.
571 response = rpc(
572 request,
573 retry=retry,
574 timeout=timeout,
575 metadata=metadata,
576 )
577
578 # This method is paged; wrap the response in a pager, which provides
579 # an `__iter__` convenience method.
580 response = pagers.ListTagBindingsPager(
581 method=rpc,
582 request=request,
583 response=response,
584 metadata=metadata,
585 )
586
587 # Done; return the response.
588 return response
589
590 def create_tag_binding(
591 self,
592 request: Optional[Union[tag_bindings.CreateTagBindingRequest, dict]] = None,
593 *,
594 tag_binding: Optional[tag_bindings.TagBinding] = None,
595 retry: OptionalRetry = gapic_v1.method.DEFAULT,
596 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
597 metadata: Sequence[Tuple[str, str]] = (),
598 ) -> operation.Operation:
599 r"""Creates a TagBinding between a TagValue and a Google
600 Cloud resource.
601
602 .. code-block:: python
603
604 # This snippet has been automatically generated and should be regarded as a
605 # code template only.
606 # It will require modifications to work:
607 # - It may require correct/in-range values for request initialization.
608 # - It may require specifying regional endpoints when creating the service
609 # client as shown in:
610 # https://googleapis.dev/python/google-api-core/latest/client_options.html
611 from google.cloud import resourcemanager_v3
612
613 def sample_create_tag_binding():
614 # Create a client
615 client = resourcemanager_v3.TagBindingsClient()
616
617 # Initialize request argument(s)
618 request = resourcemanager_v3.CreateTagBindingRequest(
619 )
620
621 # Make the request
622 operation = client.create_tag_binding(request=request)
623
624 print("Waiting for operation to complete...")
625
626 response = operation.result()
627
628 # Handle the response
629 print(response)
630
631 Args:
632 request (Union[google.cloud.resourcemanager_v3.types.CreateTagBindingRequest, dict]):
633 The request object. The request message to create a
634 TagBinding.
635 tag_binding (google.cloud.resourcemanager_v3.types.TagBinding):
636 Required. The TagBinding to be
637 created.
638
639 This corresponds to the ``tag_binding`` field
640 on the ``request`` instance; if ``request`` is provided, this
641 should not be set.
642 retry (google.api_core.retry.Retry): Designation of what errors, if any,
643 should be retried.
644 timeout (float): The timeout for this request.
645 metadata (Sequence[Tuple[str, str]]): Strings which should be
646 sent along with the request as metadata.
647
648 Returns:
649 google.api_core.operation.Operation:
650 An object representing a long-running operation.
651
652 The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagBinding` A TagBinding represents a connection between a TagValue and a cloud
653 resource Once a TagBinding is created, the TagValue
654 is applied to all the descendants of the Google Cloud
655 resource.
656
657 """
658 # Create or coerce a protobuf request object.
659 # Quick check: If we got a request object, we should *not* have
660 # gotten any keyword arguments that map to the request.
661 has_flattened_params = any([tag_binding])
662 if request is not None and has_flattened_params:
663 raise ValueError(
664 "If the `request` argument is set, then none of "
665 "the individual field arguments should be set."
666 )
667
668 # Minor optimization to avoid making a copy if the user passes
669 # in a tag_bindings.CreateTagBindingRequest.
670 # There's no risk of modifying the input as we've already verified
671 # there are no flattened fields.
672 if not isinstance(request, tag_bindings.CreateTagBindingRequest):
673 request = tag_bindings.CreateTagBindingRequest(request)
674 # If we have keyword arguments corresponding to fields on the
675 # request, apply these.
676 if tag_binding is not None:
677 request.tag_binding = tag_binding
678
679 # Wrap the RPC method; this adds retry and timeout information,
680 # and friendly error handling.
681 rpc = self._transport._wrapped_methods[self._transport.create_tag_binding]
682
683 # Send the request.
684 response = rpc(
685 request,
686 retry=retry,
687 timeout=timeout,
688 metadata=metadata,
689 )
690
691 # Wrap the response in an operation future.
692 response = operation.from_gapic(
693 response,
694 self._transport.operations_client,
695 tag_bindings.TagBinding,
696 metadata_type=tag_bindings.CreateTagBindingMetadata,
697 )
698
699 # Done; return the response.
700 return response
701
702 def delete_tag_binding(
703 self,
704 request: Optional[Union[tag_bindings.DeleteTagBindingRequest, dict]] = None,
705 *,
706 name: Optional[str] = None,
707 retry: OptionalRetry = gapic_v1.method.DEFAULT,
708 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
709 metadata: Sequence[Tuple[str, str]] = (),
710 ) -> operation.Operation:
711 r"""Deletes a TagBinding.
712
713 .. code-block:: python
714
715 # This snippet has been automatically generated and should be regarded as a
716 # code template only.
717 # It will require modifications to work:
718 # - It may require correct/in-range values for request initialization.
719 # - It may require specifying regional endpoints when creating the service
720 # client as shown in:
721 # https://googleapis.dev/python/google-api-core/latest/client_options.html
722 from google.cloud import resourcemanager_v3
723
724 def sample_delete_tag_binding():
725 # Create a client
726 client = resourcemanager_v3.TagBindingsClient()
727
728 # Initialize request argument(s)
729 request = resourcemanager_v3.DeleteTagBindingRequest(
730 name="name_value",
731 )
732
733 # Make the request
734 operation = client.delete_tag_binding(request=request)
735
736 print("Waiting for operation to complete...")
737
738 response = operation.result()
739
740 # Handle the response
741 print(response)
742
743 Args:
744 request (Union[google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest, dict]):
745 The request object. The request message to delete a
746 TagBinding.
747 name (str):
748 Required. The name of the TagBinding. This is a String
749 of the form: ``tagBindings/{id}`` (e.g.
750 ``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``).
751
752 This corresponds to the ``name`` field
753 on the ``request`` instance; if ``request`` is provided, this
754 should not be set.
755 retry (google.api_core.retry.Retry): Designation of what errors, if any,
756 should be retried.
757 timeout (float): The timeout for this request.
758 metadata (Sequence[Tuple[str, str]]): Strings which should be
759 sent along with the request as metadata.
760
761 Returns:
762 google.api_core.operation.Operation:
763 An object representing a long-running operation.
764
765 The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated
766 empty messages in your APIs. A typical example is to
767 use it as the request or the response type of an API
768 method. For instance:
769
770 service Foo {
771 rpc Bar(google.protobuf.Empty) returns
772 (google.protobuf.Empty);
773
774 }
775
776 """
777 # Create or coerce a protobuf request object.
778 # Quick check: If we got a request object, we should *not* have
779 # gotten any keyword arguments that map to the request.
780 has_flattened_params = any([name])
781 if request is not None and has_flattened_params:
782 raise ValueError(
783 "If the `request` argument is set, then none of "
784 "the individual field arguments should be set."
785 )
786
787 # Minor optimization to avoid making a copy if the user passes
788 # in a tag_bindings.DeleteTagBindingRequest.
789 # There's no risk of modifying the input as we've already verified
790 # there are no flattened fields.
791 if not isinstance(request, tag_bindings.DeleteTagBindingRequest):
792 request = tag_bindings.DeleteTagBindingRequest(request)
793 # If we have keyword arguments corresponding to fields on the
794 # request, apply these.
795 if name is not None:
796 request.name = name
797
798 # Wrap the RPC method; this adds retry and timeout information,
799 # and friendly error handling.
800 rpc = self._transport._wrapped_methods[self._transport.delete_tag_binding]
801
802 # Certain fields should be provided within the metadata header;
803 # add these here.
804 metadata = tuple(metadata) + (
805 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
806 )
807
808 # Send the request.
809 response = rpc(
810 request,
811 retry=retry,
812 timeout=timeout,
813 metadata=metadata,
814 )
815
816 # Wrap the response in an operation future.
817 response = operation.from_gapic(
818 response,
819 self._transport.operations_client,
820 empty_pb2.Empty,
821 metadata_type=tag_bindings.DeleteTagBindingMetadata,
822 )
823
824 # Done; return the response.
825 return response
826
827 def list_effective_tags(
828 self,
829 request: Optional[Union[tag_bindings.ListEffectiveTagsRequest, dict]] = None,
830 *,
831 parent: Optional[str] = None,
832 retry: OptionalRetry = gapic_v1.method.DEFAULT,
833 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
834 metadata: Sequence[Tuple[str, str]] = (),
835 ) -> pagers.ListEffectiveTagsPager:
836 r"""Return a list of effective tags for the given Google Cloud
837 resource, as specified in ``parent``.
838
839 .. code-block:: python
840
841 # This snippet has been automatically generated and should be regarded as a
842 # code template only.
843 # It will require modifications to work:
844 # - It may require correct/in-range values for request initialization.
845 # - It may require specifying regional endpoints when creating the service
846 # client as shown in:
847 # https://googleapis.dev/python/google-api-core/latest/client_options.html
848 from google.cloud import resourcemanager_v3
849
850 def sample_list_effective_tags():
851 # Create a client
852 client = resourcemanager_v3.TagBindingsClient()
853
854 # Initialize request argument(s)
855 request = resourcemanager_v3.ListEffectiveTagsRequest(
856 parent="parent_value",
857 )
858
859 # Make the request
860 page_result = client.list_effective_tags(request=request)
861
862 # Handle the response
863 for response in page_result:
864 print(response)
865
866 Args:
867 request (Union[google.cloud.resourcemanager_v3.types.ListEffectiveTagsRequest, dict]):
868 The request object. The request message to
869 ListEffectiveTags
870 parent (str):
871 Required. The full resource name of a
872 resource for which you want to list the
873 effective tags. E.g.
874 "//cloudresourcemanager.googleapis.com/projects/123"
875
876 This corresponds to the ``parent`` field
877 on the ``request`` instance; if ``request`` is provided, this
878 should not be set.
879 retry (google.api_core.retry.Retry): Designation of what errors, if any,
880 should be retried.
881 timeout (float): The timeout for this request.
882 metadata (Sequence[Tuple[str, str]]): Strings which should be
883 sent along with the request as metadata.
884
885 Returns:
886 google.cloud.resourcemanager_v3.services.tag_bindings.pagers.ListEffectiveTagsPager:
887 The response of ListEffectiveTags.
888 Iterating over this object will yield
889 results and resolve additional pages
890 automatically.
891
892 """
893 # Create or coerce a protobuf request object.
894 # Quick check: If we got a request object, we should *not* have
895 # gotten any keyword arguments that map to the request.
896 has_flattened_params = any([parent])
897 if request is not None and has_flattened_params:
898 raise ValueError(
899 "If the `request` argument is set, then none of "
900 "the individual field arguments should be set."
901 )
902
903 # Minor optimization to avoid making a copy if the user passes
904 # in a tag_bindings.ListEffectiveTagsRequest.
905 # There's no risk of modifying the input as we've already verified
906 # there are no flattened fields.
907 if not isinstance(request, tag_bindings.ListEffectiveTagsRequest):
908 request = tag_bindings.ListEffectiveTagsRequest(request)
909 # If we have keyword arguments corresponding to fields on the
910 # request, apply these.
911 if parent is not None:
912 request.parent = parent
913
914 # Wrap the RPC method; this adds retry and timeout information,
915 # and friendly error handling.
916 rpc = self._transport._wrapped_methods[self._transport.list_effective_tags]
917
918 # Send the request.
919 response = rpc(
920 request,
921 retry=retry,
922 timeout=timeout,
923 metadata=metadata,
924 )
925
926 # This method is paged; wrap the response in a pager, which provides
927 # an `__iter__` convenience method.
928 response = pagers.ListEffectiveTagsPager(
929 method=rpc,
930 request=request,
931 response=response,
932 metadata=metadata,
933 )
934
935 # Done; return the response.
936 return response
937
938 def __enter__(self) -> "TagBindingsClient":
939 return self
940
941 def __exit__(self, type, value, traceback):
942 """Releases underlying transport's resources.
943
944 .. warning::
945 ONLY use as a context manager if the transport is NOT shared
946 with other clients! Exiting the with block will CLOSE the transport
947 and may cause errors in other clients!
948 """
949 self.transport.close()
950
951 def get_operation(
952 self,
953 request: Optional[operations_pb2.GetOperationRequest] = None,
954 *,
955 retry: OptionalRetry = gapic_v1.method.DEFAULT,
956 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
957 metadata: Sequence[Tuple[str, str]] = (),
958 ) -> operations_pb2.Operation:
959 r"""Gets the latest state of a long-running operation.
960
961 Args:
962 request (:class:`~.operations_pb2.GetOperationRequest`):
963 The request object. Request message for
964 `GetOperation` method.
965 retry (google.api_core.retry.Retry): Designation of what errors,
966 if any, should be retried.
967 timeout (float): The timeout for this request.
968 metadata (Sequence[Tuple[str, str]]): Strings which should be
969 sent along with the request as metadata.
970 Returns:
971 ~.operations_pb2.Operation:
972 An ``Operation`` object.
973 """
974 # Create or coerce a protobuf request object.
975 # The request isn't a proto-plus wrapped type,
976 # so it must be constructed via keyword expansion.
977 if isinstance(request, dict):
978 request = operations_pb2.GetOperationRequest(**request)
979
980 # Wrap the RPC method; this adds retry and timeout information,
981 # and friendly error handling.
982 rpc = gapic_v1.method.wrap_method(
983 self._transport.get_operation,
984 default_timeout=None,
985 client_info=DEFAULT_CLIENT_INFO,
986 )
987
988 # Certain fields should be provided within the metadata header;
989 # add these here.
990 metadata = tuple(metadata) + (
991 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
992 )
993
994 # Send the request.
995 response = rpc(
996 request,
997 retry=retry,
998 timeout=timeout,
999 metadata=metadata,
1000 )
1001
1002 # Done; return the response.
1003 return response
1004
1005
1006DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1007 gapic_version=package_version.__version__
1008)
1009
1010
1011__all__ = ("TagBindingsClient",)