structure saas with tools
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
Binary file not shown.
@@ -0,0 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from .async_client import FoldersAsyncClient
|
||||
from .client import FoldersClient
|
||||
|
||||
__all__ = (
|
||||
"FoldersClient",
|
||||
"FoldersAsyncClient",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,353 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Iterator,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
|
||||
from google.api_core import gapic_v1
|
||||
from google.api_core import retry as retries
|
||||
from google.api_core import retry_async as retries_async
|
||||
|
||||
try:
|
||||
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
||||
OptionalAsyncRetry = Union[
|
||||
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
|
||||
]
|
||||
except AttributeError: # pragma: NO COVER
|
||||
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
||||
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import folders
|
||||
|
||||
|
||||
class ListFoldersPager:
|
||||
"""A pager for iterating through ``list_folders`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` object, and
|
||||
provides an ``__iter__`` method to iterate through its
|
||||
``folders`` field.
|
||||
|
||||
If there are more pages, the ``__iter__`` method will make additional
|
||||
``ListFolders`` requests and continue to iterate
|
||||
through the ``folders`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., folders.ListFoldersResponse],
|
||||
request: folders.ListFoldersRequest,
|
||||
response: folders.ListFoldersResponse,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiate the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListFoldersRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListFoldersResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.Retry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = folders.ListFoldersRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
def pages(self) -> Iterator[folders.ListFoldersResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __iter__(self) -> Iterator[folders.Folder]:
|
||||
for page in self.pages:
|
||||
yield from page.folders
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class ListFoldersAsyncPager:
|
||||
"""A pager for iterating through ``list_folders`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse` object, and
|
||||
provides an ``__aiter__`` method to iterate through its
|
||||
``folders`` field.
|
||||
|
||||
If there are more pages, the ``__aiter__`` method will make additional
|
||||
``ListFolders`` requests and continue to iterate
|
||||
through the ``folders`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListFoldersResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., Awaitable[folders.ListFoldersResponse]],
|
||||
request: folders.ListFoldersRequest,
|
||||
response: folders.ListFoldersResponse,
|
||||
*,
|
||||
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiates the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListFoldersRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListFoldersResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = folders.ListFoldersRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
async def pages(self) -> AsyncIterator[folders.ListFoldersResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = await self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __aiter__(self) -> AsyncIterator[folders.Folder]:
|
||||
async def async_generator():
|
||||
async for page in self.pages:
|
||||
for response in page.folders:
|
||||
yield response
|
||||
|
||||
return async_generator()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class SearchFoldersPager:
|
||||
"""A pager for iterating through ``search_folders`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` object, and
|
||||
provides an ``__iter__`` method to iterate through its
|
||||
``folders`` field.
|
||||
|
||||
If there are more pages, the ``__iter__`` method will make additional
|
||||
``SearchFolders`` requests and continue to iterate
|
||||
through the ``folders`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., folders.SearchFoldersResponse],
|
||||
request: folders.SearchFoldersRequest,
|
||||
response: folders.SearchFoldersResponse,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiate the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.SearchFoldersRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.SearchFoldersResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.Retry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = folders.SearchFoldersRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
def pages(self) -> Iterator[folders.SearchFoldersResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __iter__(self) -> Iterator[folders.Folder]:
|
||||
for page in self.pages:
|
||||
yield from page.folders
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class SearchFoldersAsyncPager:
|
||||
"""A pager for iterating through ``search_folders`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse` object, and
|
||||
provides an ``__aiter__`` method to iterate through its
|
||||
``folders`` field.
|
||||
|
||||
If there are more pages, the ``__aiter__`` method will make additional
|
||||
``SearchFolders`` requests and continue to iterate
|
||||
through the ``folders`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.SearchFoldersResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., Awaitable[folders.SearchFoldersResponse]],
|
||||
request: folders.SearchFoldersRequest,
|
||||
response: folders.SearchFoldersResponse,
|
||||
*,
|
||||
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiates the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.SearchFoldersRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.SearchFoldersResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = folders.SearchFoldersRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
async def pages(self) -> AsyncIterator[folders.SearchFoldersResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = await self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __aiter__(self) -> AsyncIterator[folders.Folder]:
|
||||
async def async_generator():
|
||||
async for page in self.pages:
|
||||
for response in page.folders:
|
||||
yield response
|
||||
|
||||
return async_generator()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from collections import OrderedDict
|
||||
from typing import Dict, Type
|
||||
|
||||
from .base import FoldersTransport
|
||||
from .grpc import FoldersGrpcTransport
|
||||
from .grpc_asyncio import FoldersGrpcAsyncIOTransport
|
||||
from .rest import FoldersRestInterceptor, FoldersRestTransport
|
||||
|
||||
# Compile a registry of transports.
|
||||
_transport_registry = OrderedDict() # type: Dict[str, Type[FoldersTransport]]
|
||||
_transport_registry["grpc"] = FoldersGrpcTransport
|
||||
_transport_registry["grpc_asyncio"] = FoldersGrpcAsyncIOTransport
|
||||
_transport_registry["rest"] = FoldersRestTransport
|
||||
|
||||
__all__ = (
|
||||
"FoldersTransport",
|
||||
"FoldersGrpcTransport",
|
||||
"FoldersGrpcAsyncIOTransport",
|
||||
"FoldersRestTransport",
|
||||
"FoldersRestInterceptor",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,355 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import abc
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
|
||||
|
||||
import google.api_core
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, operations_v1
|
||||
from google.api_core import retry as retries
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.oauth2 import service_account # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3 import gapic_version as package_version
|
||||
from google.cloud.resourcemanager_v3.types import folders
|
||||
|
||||
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
||||
gapic_version=package_version.__version__
|
||||
)
|
||||
|
||||
|
||||
class FoldersTransport(abc.ABC):
|
||||
"""Abstract transport class for Folders."""
|
||||
|
||||
AUTH_SCOPES = (
|
||||
"https://www.googleapis.com/auth/cloud-platform",
|
||||
"https://www.googleapis.com/auth/cloud-platform.read-only",
|
||||
)
|
||||
|
||||
DEFAULT_HOST: str = "cloudresourcemanager.googleapis.com"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = DEFAULT_HOST,
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A list of scopes.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
"""
|
||||
|
||||
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
|
||||
|
||||
# Save the scopes.
|
||||
self._scopes = scopes
|
||||
if not hasattr(self, "_ignore_credentials"):
|
||||
self._ignore_credentials: bool = False
|
||||
|
||||
# If no credentials are provided, then determine the appropriate
|
||||
# defaults.
|
||||
if credentials and credentials_file:
|
||||
raise core_exceptions.DuplicateCredentialArgs(
|
||||
"'credentials_file' and 'credentials' are mutually exclusive"
|
||||
)
|
||||
|
||||
if credentials_file is not None:
|
||||
credentials, _ = google.auth.load_credentials_from_file(
|
||||
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
elif credentials is None and not self._ignore_credentials:
|
||||
credentials, _ = google.auth.default(
|
||||
**scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
# Don't apply audience if the credentials file passed from user.
|
||||
if hasattr(credentials, "with_gdch_audience"):
|
||||
credentials = credentials.with_gdch_audience(
|
||||
api_audience if api_audience else host
|
||||
)
|
||||
|
||||
# If the credentials are service account credentials, then always try to use self signed JWT.
|
||||
if (
|
||||
always_use_jwt_access
|
||||
and isinstance(credentials, service_account.Credentials)
|
||||
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
|
||||
):
|
||||
credentials = credentials.with_always_use_jwt_access(True)
|
||||
|
||||
# Save the credentials.
|
||||
self._credentials = credentials
|
||||
|
||||
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
|
||||
if ":" not in host:
|
||||
host += ":443"
|
||||
self._host = host
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
return self._host
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
# Precompute the wrapped methods.
|
||||
self._wrapped_methods = {
|
||||
self.get_folder: gapic_v1.method.wrap_method(
|
||||
self.get_folder,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.list_folders: gapic_v1.method.wrap_method(
|
||||
self.list_folders,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.search_folders: gapic_v1.method.wrap_method(
|
||||
self.search_folders,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.create_folder: gapic_v1.method.wrap_method(
|
||||
self.create_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.update_folder: gapic_v1.method.wrap_method(
|
||||
self.update_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.move_folder: gapic_v1.method.wrap_method(
|
||||
self.move_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.delete_folder: gapic_v1.method.wrap_method(
|
||||
self.delete_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.undelete_folder: gapic_v1.method.wrap_method(
|
||||
self.undelete_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_iam_policy: gapic_v1.method.wrap_method(
|
||||
self.get_iam_policy,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.set_iam_policy: gapic_v1.method.wrap_method(
|
||||
self.set_iam_policy,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.test_iam_permissions: gapic_v1.method.wrap_method(
|
||||
self.test_iam_permissions,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: gapic_v1.method.wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def close(self):
|
||||
"""Closes resources associated with the transport.
|
||||
|
||||
.. warning::
|
||||
Only call this method if the transport is NOT shared
|
||||
with other clients - this may cause errors in other clients!
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def operations_client(self):
|
||||
"""Return the client designed to process long-running operations."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_folder(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.GetFolderRequest], Union[folders.Folder, Awaitable[folders.Folder]]
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def list_folders(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.ListFoldersRequest],
|
||||
Union[folders.ListFoldersResponse, Awaitable[folders.ListFoldersResponse]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def search_folders(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.SearchFoldersRequest],
|
||||
Union[folders.SearchFoldersResponse, Awaitable[folders.SearchFoldersResponse]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def create_folder(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.CreateFolderRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def update_folder(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.UpdateFolderRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def move_folder(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.MoveFolderRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def delete_folder(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.DeleteFolderRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def undelete_folder(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.UndeleteFolderRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.GetIamPolicyRequest],
|
||||
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.SetIamPolicyRequest],
|
||||
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
Union[
|
||||
iam_policy_pb2.TestIamPermissionsResponse,
|
||||
Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
|
||||
],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[
|
||||
[operations_pb2.GetOperationRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
__all__ = ("FoldersTransport",)
|
||||
@@ -0,0 +1,772 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import gapic_v1, grpc_helpers, operations_v1
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import folders
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, FoldersTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
|
||||
def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Folders",
|
||||
"rpcName": client_call_details.method,
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
|
||||
response = continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = response.result()
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response for {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Folders",
|
||||
"rpcName": client_call_details.method,
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class FoldersGrpcTransport(FoldersTransport):
|
||||
"""gRPC backend transport for Folders.
|
||||
|
||||
Manages Cloud Platform folder resources.
|
||||
Folders can be used to organize the resources under an
|
||||
organization and to control the policies applied to groups of
|
||||
resources.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_stubs: Dict[str, Callable]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
||||
ignored if a ``channel`` instance is provided.
|
||||
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
self._operations_client: Optional[operations_v1.OperationsClient] = None
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, grpc.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientInterceptor()
|
||||
self._logged_channel = grpc.intercept_channel(
|
||||
self._grpc_channel, self._interceptor
|
||||
)
|
||||
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> grpc.Channel:
|
||||
"""Create and return a gRPC channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
grpc.Channel: A gRPC channel object.
|
||||
|
||||
Raises:
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
|
||||
return grpc_helpers.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> grpc.Channel:
|
||||
"""Return the channel designed to connect to this service."""
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def operations_client(self) -> operations_v1.OperationsClient:
|
||||
"""Create the client designed to process long-running operations.
|
||||
|
||||
This property caches on the instance; repeated calls return the same
|
||||
client.
|
||||
"""
|
||||
# Quick check: Only create a new client if we do not already have one.
|
||||
if self._operations_client is None:
|
||||
self._operations_client = operations_v1.OperationsClient(
|
||||
self._logged_channel
|
||||
)
|
||||
|
||||
# Return the client from cache.
|
||||
return self._operations_client
|
||||
|
||||
@property
|
||||
def get_folder(self) -> Callable[[folders.GetFolderRequest], folders.Folder]:
|
||||
r"""Return a callable for the get folder method over gRPC.
|
||||
|
||||
Retrieves a folder identified by the supplied resource name.
|
||||
Valid folder resource names have the format
|
||||
``folders/{folder_id}`` (for example, ``folders/1234``). The
|
||||
caller must have ``resourcemanager.folders.get`` permission on
|
||||
the identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetFolderRequest],
|
||||
~.Folder]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_folder" not in self._stubs:
|
||||
self._stubs["get_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/GetFolder",
|
||||
request_serializer=folders.GetFolderRequest.serialize,
|
||||
response_deserializer=folders.Folder.deserialize,
|
||||
)
|
||||
return self._stubs["get_folder"]
|
||||
|
||||
@property
|
||||
def list_folders(
|
||||
self,
|
||||
) -> Callable[[folders.ListFoldersRequest], folders.ListFoldersResponse]:
|
||||
r"""Return a callable for the list folders method over gRPC.
|
||||
|
||||
Lists the folders that are direct descendants of supplied parent
|
||||
resource. ``list()`` provides a strongly consistent view of the
|
||||
folders underneath the specified parent resource. ``list()``
|
||||
returns folders sorted based upon the (ascending) lexical
|
||||
ordering of their display_name. The caller must have
|
||||
``resourcemanager.folders.list`` permission on the identified
|
||||
parent.
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListFoldersRequest],
|
||||
~.ListFoldersResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_folders" not in self._stubs:
|
||||
self._stubs["list_folders"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/ListFolders",
|
||||
request_serializer=folders.ListFoldersRequest.serialize,
|
||||
response_deserializer=folders.ListFoldersResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_folders"]
|
||||
|
||||
@property
|
||||
def search_folders(
|
||||
self,
|
||||
) -> Callable[[folders.SearchFoldersRequest], folders.SearchFoldersResponse]:
|
||||
r"""Return a callable for the search folders method over gRPC.
|
||||
|
||||
Search for folders that match specific filter criteria.
|
||||
``search()`` provides an eventually consistent view of the
|
||||
folders a user has access to which meet the specified filter
|
||||
criteria.
|
||||
|
||||
This will only return folders on which the caller has the
|
||||
permission ``resourcemanager.folders.get``.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SearchFoldersRequest],
|
||||
~.SearchFoldersResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "search_folders" not in self._stubs:
|
||||
self._stubs["search_folders"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/SearchFolders",
|
||||
request_serializer=folders.SearchFoldersRequest.serialize,
|
||||
response_deserializer=folders.SearchFoldersResponse.deserialize,
|
||||
)
|
||||
return self._stubs["search_folders"]
|
||||
|
||||
@property
|
||||
def create_folder(
|
||||
self,
|
||||
) -> Callable[[folders.CreateFolderRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the create folder method over gRPC.
|
||||
|
||||
Creates a folder in the resource hierarchy. Returns an
|
||||
``Operation`` which can be used to track the progress of the
|
||||
folder creation workflow. Upon success, the
|
||||
``Operation.response`` field will be populated with the created
|
||||
Folder.
|
||||
|
||||
In order to succeed, the addition of this new folder must not
|
||||
violate the folder naming, height, or fanout constraints.
|
||||
|
||||
- The folder's ``display_name`` must be distinct from all other
|
||||
folders that share its parent.
|
||||
- The addition of the folder must not cause the active folder
|
||||
hierarchy to exceed a height of 10. Note, the full active +
|
||||
deleted folder hierarchy is allowed to reach a height of 20;
|
||||
this provides additional headroom when moving folders that
|
||||
contain deleted folders.
|
||||
- The addition of the folder must not cause the total number of
|
||||
folders under its parent to exceed 300.
|
||||
|
||||
If the operation fails due to a folder constraint violation,
|
||||
some errors may be returned by the ``CreateFolder`` request,
|
||||
with status code ``FAILED_PRECONDITION`` and an error
|
||||
description. Other folder constraint violations will be
|
||||
communicated in the ``Operation``, with the specific
|
||||
``PreconditionFailure`` returned in the details list in the
|
||||
``Operation.error`` field.
|
||||
|
||||
The caller must have ``resourcemanager.folders.create``
|
||||
permission on the identified parent.
|
||||
|
||||
Returns:
|
||||
Callable[[~.CreateFolderRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "create_folder" not in self._stubs:
|
||||
self._stubs["create_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/CreateFolder",
|
||||
request_serializer=folders.CreateFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["create_folder"]
|
||||
|
||||
@property
|
||||
def update_folder(
|
||||
self,
|
||||
) -> Callable[[folders.UpdateFolderRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the update folder method over gRPC.
|
||||
|
||||
Updates a folder, changing its ``display_name``. Changes to the
|
||||
folder ``display_name`` will be rejected if they violate either
|
||||
the ``display_name`` formatting rules or the naming constraints
|
||||
described in the
|
||||
[CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder]
|
||||
documentation.
|
||||
|
||||
The folder's ``display_name`` must start and end with a letter
|
||||
or digit, may contain letters, digits, spaces, hyphens and
|
||||
underscores and can be between 3 and 30 characters. This is
|
||||
captured by the regular expression:
|
||||
``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller
|
||||
must have ``resourcemanager.folders.update`` permission on the
|
||||
identified folder.
|
||||
|
||||
If the update fails due to the unique name constraint then a
|
||||
``PreconditionFailure`` explaining this violation will be
|
||||
returned in the Status.details field.
|
||||
|
||||
Returns:
|
||||
Callable[[~.UpdateFolderRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "update_folder" not in self._stubs:
|
||||
self._stubs["update_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/UpdateFolder",
|
||||
request_serializer=folders.UpdateFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["update_folder"]
|
||||
|
||||
@property
|
||||
def move_folder(
|
||||
self,
|
||||
) -> Callable[[folders.MoveFolderRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the move folder method over gRPC.
|
||||
|
||||
Moves a folder under a new resource parent. Returns an
|
||||
``Operation`` which can be used to track the progress of the
|
||||
folder move workflow. Upon success, the ``Operation.response``
|
||||
field will be populated with the moved folder. Upon failure, a
|
||||
``FolderOperationError`` categorizing the failure cause will be
|
||||
returned - if the failure occurs synchronously then the
|
||||
``FolderOperationError`` will be returned in the
|
||||
``Status.details`` field. If it occurs asynchronously, then the
|
||||
FolderOperation will be returned in the ``Operation.error``
|
||||
field. In addition, the ``Operation.metadata`` field will be
|
||||
populated with a ``FolderOperation`` message as an aid to
|
||||
stateless clients. Folder moves will be rejected if they violate
|
||||
either the naming, height, or fanout constraints described in
|
||||
the
|
||||
[CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder]
|
||||
documentation. The caller must have
|
||||
``resourcemanager.folders.move`` permission on the folder's
|
||||
current and proposed new parent.
|
||||
|
||||
Returns:
|
||||
Callable[[~.MoveFolderRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "move_folder" not in self._stubs:
|
||||
self._stubs["move_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/MoveFolder",
|
||||
request_serializer=folders.MoveFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["move_folder"]
|
||||
|
||||
@property
|
||||
def delete_folder(
|
||||
self,
|
||||
) -> Callable[[folders.DeleteFolderRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the delete folder method over gRPC.
|
||||
|
||||
Requests deletion of a folder. The folder is moved into the
|
||||
[DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED]
|
||||
state immediately, and is deleted approximately 30 days later.
|
||||
This method may only be called on an empty folder, where a
|
||||
folder is empty if it doesn't contain any folders or projects in
|
||||
the
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE]
|
||||
state. If called on a folder in
|
||||
[DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED]
|
||||
state the operation will result in a no-op success. The caller
|
||||
must have ``resourcemanager.folders.delete`` permission on the
|
||||
identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.DeleteFolderRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "delete_folder" not in self._stubs:
|
||||
self._stubs["delete_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/DeleteFolder",
|
||||
request_serializer=folders.DeleteFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["delete_folder"]
|
||||
|
||||
@property
|
||||
def undelete_folder(
|
||||
self,
|
||||
) -> Callable[[folders.UndeleteFolderRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the undelete folder method over gRPC.
|
||||
|
||||
Cancels the deletion request for a folder. This method may be
|
||||
called on a folder in any state. If the folder is in the
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE]
|
||||
state the result will be a no-op success. In order to succeed,
|
||||
the folder's parent must be in the
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE]
|
||||
state. In addition, reintroducing the folder into the tree must
|
||||
not violate folder naming, height, and fanout constraints
|
||||
described in the
|
||||
[CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder]
|
||||
documentation. The caller must have
|
||||
``resourcemanager.folders.undelete`` permission on the
|
||||
identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.UndeleteFolderRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "undelete_folder" not in self._stubs:
|
||||
self._stubs["undelete_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/UndeleteFolder",
|
||||
request_serializer=folders.UndeleteFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["undelete_folder"]
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
|
||||
r"""Return a callable for the get iam policy method over gRPC.
|
||||
|
||||
Gets the access control policy for a folder. The returned policy
|
||||
may be empty if no such policy or resource exists. The
|
||||
``resource`` field should be the folder's resource name, for
|
||||
example: "folders/1234". The caller must have
|
||||
``resourcemanager.folders.getIamPolicy`` permission on the
|
||||
identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetIamPolicyRequest],
|
||||
~.Policy]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_iam_policy" not in self._stubs:
|
||||
self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/GetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["get_iam_policy"]
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
|
||||
r"""Return a callable for the set iam policy method over gRPC.
|
||||
|
||||
Sets the access control policy on a folder, replacing any
|
||||
existing policy. The ``resource`` field should be the folder's
|
||||
resource name, for example: "folders/1234". The caller must have
|
||||
``resourcemanager.folders.setIamPolicy`` permission on the
|
||||
identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SetIamPolicyRequest],
|
||||
~.Policy]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "set_iam_policy" not in self._stubs:
|
||||
self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/SetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["set_iam_policy"]
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
iam_policy_pb2.TestIamPermissionsResponse,
|
||||
]:
|
||||
r"""Return a callable for the test iam permissions method over gRPC.
|
||||
|
||||
Returns permissions that a caller has on the specified folder.
|
||||
The ``resource`` field should be the folder's resource name, for
|
||||
example: "folders/1234".
|
||||
|
||||
There are no permissions required for making this API call.
|
||||
|
||||
Returns:
|
||||
Callable[[~.TestIamPermissionsRequest],
|
||||
~.TestIamPermissionsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "test_iam_permissions" not in self._stubs:
|
||||
self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/TestIamPermissions",
|
||||
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
|
||||
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
|
||||
)
|
||||
return self._stubs["test_iam_permissions"]
|
||||
|
||||
def close(self):
|
||||
self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc"
|
||||
|
||||
|
||||
__all__ = ("FoldersGrpcTransport",)
|
||||
@@ -0,0 +1,880 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import inspect
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, grpc_helpers_async, operations_v1
|
||||
from google.api_core import retry_async as retries
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
from grpc.experimental import aio # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import folders
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, FoldersTransport
|
||||
from .grpc import FoldersGrpcTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientAIOInterceptor(
|
||||
grpc.aio.UnaryUnaryClientInterceptor
|
||||
): # pragma: NO COVER
|
||||
async def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Folders",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
response = await continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = await response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = await response
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response to rpc {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Folders",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class FoldersGrpcAsyncIOTransport(FoldersTransport):
|
||||
"""gRPC AsyncIO backend transport for Folders.
|
||||
|
||||
Manages Cloud Platform folder resources.
|
||||
Folders can be used to organize the resources under an
|
||||
organization and to control the policies applied to groups of
|
||||
resources.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_grpc_channel: aio.Channel
|
||||
_stubs: Dict[str, Callable] = {}
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> aio.Channel:
|
||||
"""Create and return a gRPC AsyncIO channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
aio.Channel: A gRPC AsyncIO channel object.
|
||||
"""
|
||||
|
||||
return grpc_helpers_async.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, aio.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientAIOInterceptor()
|
||||
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
|
||||
self._logged_channel = self._grpc_channel
|
||||
self._wrap_with_kind = (
|
||||
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
|
||||
)
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> aio.Channel:
|
||||
"""Create the channel designed to connect to this service.
|
||||
|
||||
This property caches on the instance; repeated calls return
|
||||
the same channel.
|
||||
"""
|
||||
# Return the channel from cache.
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def operations_client(self) -> operations_v1.OperationsAsyncClient:
|
||||
"""Create the client designed to process long-running operations.
|
||||
|
||||
This property caches on the instance; repeated calls return the same
|
||||
client.
|
||||
"""
|
||||
# Quick check: Only create a new client if we do not already have one.
|
||||
if self._operations_client is None:
|
||||
self._operations_client = operations_v1.OperationsAsyncClient(
|
||||
self._logged_channel
|
||||
)
|
||||
|
||||
# Return the client from cache.
|
||||
return self._operations_client
|
||||
|
||||
@property
|
||||
def get_folder(
|
||||
self,
|
||||
) -> Callable[[folders.GetFolderRequest], Awaitable[folders.Folder]]:
|
||||
r"""Return a callable for the get folder method over gRPC.
|
||||
|
||||
Retrieves a folder identified by the supplied resource name.
|
||||
Valid folder resource names have the format
|
||||
``folders/{folder_id}`` (for example, ``folders/1234``). The
|
||||
caller must have ``resourcemanager.folders.get`` permission on
|
||||
the identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetFolderRequest],
|
||||
Awaitable[~.Folder]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_folder" not in self._stubs:
|
||||
self._stubs["get_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/GetFolder",
|
||||
request_serializer=folders.GetFolderRequest.serialize,
|
||||
response_deserializer=folders.Folder.deserialize,
|
||||
)
|
||||
return self._stubs["get_folder"]
|
||||
|
||||
@property
|
||||
def list_folders(
|
||||
self,
|
||||
) -> Callable[[folders.ListFoldersRequest], Awaitable[folders.ListFoldersResponse]]:
|
||||
r"""Return a callable for the list folders method over gRPC.
|
||||
|
||||
Lists the folders that are direct descendants of supplied parent
|
||||
resource. ``list()`` provides a strongly consistent view of the
|
||||
folders underneath the specified parent resource. ``list()``
|
||||
returns folders sorted based upon the (ascending) lexical
|
||||
ordering of their display_name. The caller must have
|
||||
``resourcemanager.folders.list`` permission on the identified
|
||||
parent.
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListFoldersRequest],
|
||||
Awaitable[~.ListFoldersResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_folders" not in self._stubs:
|
||||
self._stubs["list_folders"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/ListFolders",
|
||||
request_serializer=folders.ListFoldersRequest.serialize,
|
||||
response_deserializer=folders.ListFoldersResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_folders"]
|
||||
|
||||
@property
|
||||
def search_folders(
|
||||
self,
|
||||
) -> Callable[
|
||||
[folders.SearchFoldersRequest], Awaitable[folders.SearchFoldersResponse]
|
||||
]:
|
||||
r"""Return a callable for the search folders method over gRPC.
|
||||
|
||||
Search for folders that match specific filter criteria.
|
||||
``search()`` provides an eventually consistent view of the
|
||||
folders a user has access to which meet the specified filter
|
||||
criteria.
|
||||
|
||||
This will only return folders on which the caller has the
|
||||
permission ``resourcemanager.folders.get``.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SearchFoldersRequest],
|
||||
Awaitable[~.SearchFoldersResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "search_folders" not in self._stubs:
|
||||
self._stubs["search_folders"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/SearchFolders",
|
||||
request_serializer=folders.SearchFoldersRequest.serialize,
|
||||
response_deserializer=folders.SearchFoldersResponse.deserialize,
|
||||
)
|
||||
return self._stubs["search_folders"]
|
||||
|
||||
@property
|
||||
def create_folder(
|
||||
self,
|
||||
) -> Callable[[folders.CreateFolderRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the create folder method over gRPC.
|
||||
|
||||
Creates a folder in the resource hierarchy. Returns an
|
||||
``Operation`` which can be used to track the progress of the
|
||||
folder creation workflow. Upon success, the
|
||||
``Operation.response`` field will be populated with the created
|
||||
Folder.
|
||||
|
||||
In order to succeed, the addition of this new folder must not
|
||||
violate the folder naming, height, or fanout constraints.
|
||||
|
||||
- The folder's ``display_name`` must be distinct from all other
|
||||
folders that share its parent.
|
||||
- The addition of the folder must not cause the active folder
|
||||
hierarchy to exceed a height of 10. Note, the full active +
|
||||
deleted folder hierarchy is allowed to reach a height of 20;
|
||||
this provides additional headroom when moving folders that
|
||||
contain deleted folders.
|
||||
- The addition of the folder must not cause the total number of
|
||||
folders under its parent to exceed 300.
|
||||
|
||||
If the operation fails due to a folder constraint violation,
|
||||
some errors may be returned by the ``CreateFolder`` request,
|
||||
with status code ``FAILED_PRECONDITION`` and an error
|
||||
description. Other folder constraint violations will be
|
||||
communicated in the ``Operation``, with the specific
|
||||
``PreconditionFailure`` returned in the details list in the
|
||||
``Operation.error`` field.
|
||||
|
||||
The caller must have ``resourcemanager.folders.create``
|
||||
permission on the identified parent.
|
||||
|
||||
Returns:
|
||||
Callable[[~.CreateFolderRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "create_folder" not in self._stubs:
|
||||
self._stubs["create_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/CreateFolder",
|
||||
request_serializer=folders.CreateFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["create_folder"]
|
||||
|
||||
@property
|
||||
def update_folder(
|
||||
self,
|
||||
) -> Callable[[folders.UpdateFolderRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the update folder method over gRPC.
|
||||
|
||||
Updates a folder, changing its ``display_name``. Changes to the
|
||||
folder ``display_name`` will be rejected if they violate either
|
||||
the ``display_name`` formatting rules or the naming constraints
|
||||
described in the
|
||||
[CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder]
|
||||
documentation.
|
||||
|
||||
The folder's ``display_name`` must start and end with a letter
|
||||
or digit, may contain letters, digits, spaces, hyphens and
|
||||
underscores and can be between 3 and 30 characters. This is
|
||||
captured by the regular expression:
|
||||
``[\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]``. The caller
|
||||
must have ``resourcemanager.folders.update`` permission on the
|
||||
identified folder.
|
||||
|
||||
If the update fails due to the unique name constraint then a
|
||||
``PreconditionFailure`` explaining this violation will be
|
||||
returned in the Status.details field.
|
||||
|
||||
Returns:
|
||||
Callable[[~.UpdateFolderRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "update_folder" not in self._stubs:
|
||||
self._stubs["update_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/UpdateFolder",
|
||||
request_serializer=folders.UpdateFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["update_folder"]
|
||||
|
||||
@property
|
||||
def move_folder(
|
||||
self,
|
||||
) -> Callable[[folders.MoveFolderRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the move folder method over gRPC.
|
||||
|
||||
Moves a folder under a new resource parent. Returns an
|
||||
``Operation`` which can be used to track the progress of the
|
||||
folder move workflow. Upon success, the ``Operation.response``
|
||||
field will be populated with the moved folder. Upon failure, a
|
||||
``FolderOperationError`` categorizing the failure cause will be
|
||||
returned - if the failure occurs synchronously then the
|
||||
``FolderOperationError`` will be returned in the
|
||||
``Status.details`` field. If it occurs asynchronously, then the
|
||||
FolderOperation will be returned in the ``Operation.error``
|
||||
field. In addition, the ``Operation.metadata`` field will be
|
||||
populated with a ``FolderOperation`` message as an aid to
|
||||
stateless clients. Folder moves will be rejected if they violate
|
||||
either the naming, height, or fanout constraints described in
|
||||
the
|
||||
[CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder]
|
||||
documentation. The caller must have
|
||||
``resourcemanager.folders.move`` permission on the folder's
|
||||
current and proposed new parent.
|
||||
|
||||
Returns:
|
||||
Callable[[~.MoveFolderRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "move_folder" not in self._stubs:
|
||||
self._stubs["move_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/MoveFolder",
|
||||
request_serializer=folders.MoveFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["move_folder"]
|
||||
|
||||
@property
|
||||
def delete_folder(
|
||||
self,
|
||||
) -> Callable[[folders.DeleteFolderRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the delete folder method over gRPC.
|
||||
|
||||
Requests deletion of a folder. The folder is moved into the
|
||||
[DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED]
|
||||
state immediately, and is deleted approximately 30 days later.
|
||||
This method may only be called on an empty folder, where a
|
||||
folder is empty if it doesn't contain any folders or projects in
|
||||
the
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE]
|
||||
state. If called on a folder in
|
||||
[DELETE_REQUESTED][google.cloud.resourcemanager.v3.Folder.State.DELETE_REQUESTED]
|
||||
state the operation will result in a no-op success. The caller
|
||||
must have ``resourcemanager.folders.delete`` permission on the
|
||||
identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.DeleteFolderRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "delete_folder" not in self._stubs:
|
||||
self._stubs["delete_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/DeleteFolder",
|
||||
request_serializer=folders.DeleteFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["delete_folder"]
|
||||
|
||||
@property
|
||||
def undelete_folder(
|
||||
self,
|
||||
) -> Callable[[folders.UndeleteFolderRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the undelete folder method over gRPC.
|
||||
|
||||
Cancels the deletion request for a folder. This method may be
|
||||
called on a folder in any state. If the folder is in the
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE]
|
||||
state the result will be a no-op success. In order to succeed,
|
||||
the folder's parent must be in the
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE]
|
||||
state. In addition, reintroducing the folder into the tree must
|
||||
not violate folder naming, height, and fanout constraints
|
||||
described in the
|
||||
[CreateFolder][google.cloud.resourcemanager.v3.Folders.CreateFolder]
|
||||
documentation. The caller must have
|
||||
``resourcemanager.folders.undelete`` permission on the
|
||||
identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.UndeleteFolderRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "undelete_folder" not in self._stubs:
|
||||
self._stubs["undelete_folder"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/UndeleteFolder",
|
||||
request_serializer=folders.UndeleteFolderRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["undelete_folder"]
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
|
||||
r"""Return a callable for the get iam policy method over gRPC.
|
||||
|
||||
Gets the access control policy for a folder. The returned policy
|
||||
may be empty if no such policy or resource exists. The
|
||||
``resource`` field should be the folder's resource name, for
|
||||
example: "folders/1234". The caller must have
|
||||
``resourcemanager.folders.getIamPolicy`` permission on the
|
||||
identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetIamPolicyRequest],
|
||||
Awaitable[~.Policy]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_iam_policy" not in self._stubs:
|
||||
self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/GetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["get_iam_policy"]
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
|
||||
r"""Return a callable for the set iam policy method over gRPC.
|
||||
|
||||
Sets the access control policy on a folder, replacing any
|
||||
existing policy. The ``resource`` field should be the folder's
|
||||
resource name, for example: "folders/1234". The caller must have
|
||||
``resourcemanager.folders.setIamPolicy`` permission on the
|
||||
identified folder.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SetIamPolicyRequest],
|
||||
Awaitable[~.Policy]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "set_iam_policy" not in self._stubs:
|
||||
self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/SetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["set_iam_policy"]
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
|
||||
]:
|
||||
r"""Return a callable for the test iam permissions method over gRPC.
|
||||
|
||||
Returns permissions that a caller has on the specified folder.
|
||||
The ``resource`` field should be the folder's resource name, for
|
||||
example: "folders/1234".
|
||||
|
||||
There are no permissions required for making this API call.
|
||||
|
||||
Returns:
|
||||
Callable[[~.TestIamPermissionsRequest],
|
||||
Awaitable[~.TestIamPermissionsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "test_iam_permissions" not in self._stubs:
|
||||
self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Folders/TestIamPermissions",
|
||||
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
|
||||
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
|
||||
)
|
||||
return self._stubs["test_iam_permissions"]
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
|
||||
self._wrapped_methods = {
|
||||
self.get_folder: self._wrap_method(
|
||||
self.get_folder,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.list_folders: self._wrap_method(
|
||||
self.list_folders,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.search_folders: self._wrap_method(
|
||||
self.search_folders,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.create_folder: self._wrap_method(
|
||||
self.create_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.update_folder: self._wrap_method(
|
||||
self.update_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.move_folder: self._wrap_method(
|
||||
self.move_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.delete_folder: self._wrap_method(
|
||||
self.delete_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.undelete_folder: self._wrap_method(
|
||||
self.undelete_folder,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_iam_policy: self._wrap_method(
|
||||
self.get_iam_policy,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.set_iam_policy: self._wrap_method(
|
||||
self.set_iam_policy,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.test_iam_permissions: self._wrap_method(
|
||||
self.test_iam_permissions,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: self._wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def _wrap_method(self, func, *args, **kwargs):
|
||||
if self._wrap_with_kind: # pragma: NO COVER
|
||||
kwargs["kind"] = self.kind
|
||||
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
|
||||
|
||||
def close(self):
|
||||
return self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc_asyncio"
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
|
||||
__all__ = ("FoldersGrpcAsyncIOTransport",)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,695 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json # type: ignore
|
||||
import re
|
||||
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
||||
|
||||
from google.api_core import gapic_v1, path_template
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf import json_format
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import folders
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, FoldersTransport
|
||||
|
||||
|
||||
class _BaseFoldersRestTransport(FoldersTransport):
|
||||
"""Base REST backend transport for Folders.
|
||||
|
||||
Note: This class is not meant to be used directly. Use its sync and
|
||||
async sub-classes instead.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends JSON representations of protocol buffers over HTTP/1.1
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[Any] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
url_scheme: str = "https",
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[Any]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you are developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
url_scheme: the protocol scheme for the API endpoint. Normally
|
||||
"https", but for testing or local servers,
|
||||
"http" can be specified.
|
||||
"""
|
||||
# Run the base constructor
|
||||
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
|
||||
if maybe_url_match is None:
|
||||
raise ValueError(
|
||||
f"Unexpected hostname structure: {host}"
|
||||
) # pragma: NO COVER
|
||||
|
||||
url_match_items = maybe_url_match.groupdict()
|
||||
|
||||
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
|
||||
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
class _BaseCreateFolder:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/folders",
|
||||
"body": "folder",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = folders.CreateFolderRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseCreateFolder._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseDeleteFolder:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "delete",
|
||||
"uri": "/v3/{name=folders/*}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = folders.DeleteFolderRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseDeleteFolder._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetFolder:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/{name=folders/*}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = folders.GetFolderRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseGetFolder._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetIamPolicy:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=folders/*}:getIamPolicy",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseGetIamPolicy._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseListFolders:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
|
||||
"parent": "",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/folders",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = folders.ListFoldersRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseListFolders._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseMoveFolder:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{name=folders/*}:move",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = folders.MoveFolderRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseMoveFolder._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseSearchFolders:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/folders:search",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = folders.SearchFoldersRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseSetIamPolicy:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=folders/*}:setIamPolicy",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseSetIamPolicy._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseTestIamPermissions:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=folders/*}:testIamPermissions",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseTestIamPermissions._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseUndeleteFolder:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{name=folders/*}:undelete",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = folders.UndeleteFolderRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseUndeleteFolder._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseUpdateFolder:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
|
||||
"updateMask": {},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "patch",
|
||||
"uri": "/v3/{folder.name=folders/*}",
|
||||
"body": "folder",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = folders.UpdateFolderRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseFoldersRestTransport._BaseUpdateFolder._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetOperation:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/{name=operations/**}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
request_kwargs = json_format.MessageToDict(request)
|
||||
transcoded_request = path_template.transcode(http_options, **request_kwargs)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
|
||||
return query_params
|
||||
|
||||
|
||||
__all__ = ("_BaseFoldersRestTransport",)
|
||||
@@ -0,0 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from .async_client import OrganizationsAsyncClient
|
||||
from .client import OrganizationsClient
|
||||
|
||||
__all__ = (
|
||||
"OrganizationsClient",
|
||||
"OrganizationsAsyncClient",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,197 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Iterator,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
|
||||
from google.api_core import gapic_v1
|
||||
from google.api_core import retry as retries
|
||||
from google.api_core import retry_async as retries_async
|
||||
|
||||
try:
|
||||
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
||||
OptionalAsyncRetry = Union[
|
||||
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
|
||||
]
|
||||
except AttributeError: # pragma: NO COVER
|
||||
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
||||
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import organizations
|
||||
|
||||
|
||||
class SearchOrganizationsPager:
|
||||
"""A pager for iterating through ``search_organizations`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` object, and
|
||||
provides an ``__iter__`` method to iterate through its
|
||||
``organizations`` field.
|
||||
|
||||
If there are more pages, the ``__iter__`` method will make additional
|
||||
``SearchOrganizations`` requests and continue to iterate
|
||||
through the ``organizations`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., organizations.SearchOrganizationsResponse],
|
||||
request: organizations.SearchOrganizationsRequest,
|
||||
response: organizations.SearchOrganizationsResponse,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiate the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.Retry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = organizations.SearchOrganizationsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
def pages(self) -> Iterator[organizations.SearchOrganizationsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __iter__(self) -> Iterator[organizations.Organization]:
|
||||
for page in self.pages:
|
||||
yield from page.organizations
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class SearchOrganizationsAsyncPager:
|
||||
"""A pager for iterating through ``search_organizations`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse` object, and
|
||||
provides an ``__aiter__`` method to iterate through its
|
||||
``organizations`` field.
|
||||
|
||||
If there are more pages, the ``__aiter__`` method will make additional
|
||||
``SearchOrganizations`` requests and continue to iterate
|
||||
through the ``organizations`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., Awaitable[organizations.SearchOrganizationsResponse]],
|
||||
request: organizations.SearchOrganizationsRequest,
|
||||
response: organizations.SearchOrganizationsResponse,
|
||||
*,
|
||||
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiates the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.SearchOrganizationsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = organizations.SearchOrganizationsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
async def pages(self) -> AsyncIterator[organizations.SearchOrganizationsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = await self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __aiter__(self) -> AsyncIterator[organizations.Organization]:
|
||||
async def async_generator():
|
||||
async for page in self.pages:
|
||||
for response in page.organizations:
|
||||
yield response
|
||||
|
||||
return async_generator()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from collections import OrderedDict
|
||||
from typing import Dict, Type
|
||||
|
||||
from .base import OrganizationsTransport
|
||||
from .grpc import OrganizationsGrpcTransport
|
||||
from .grpc_asyncio import OrganizationsGrpcAsyncIOTransport
|
||||
from .rest import OrganizationsRestInterceptor, OrganizationsRestTransport
|
||||
|
||||
# Compile a registry of transports.
|
||||
_transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationsTransport]]
|
||||
_transport_registry["grpc"] = OrganizationsGrpcTransport
|
||||
_transport_registry["grpc_asyncio"] = OrganizationsGrpcAsyncIOTransport
|
||||
_transport_registry["rest"] = OrganizationsRestTransport
|
||||
|
||||
__all__ = (
|
||||
"OrganizationsTransport",
|
||||
"OrganizationsGrpcTransport",
|
||||
"OrganizationsGrpcAsyncIOTransport",
|
||||
"OrganizationsRestTransport",
|
||||
"OrganizationsRestInterceptor",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,261 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import abc
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
|
||||
|
||||
import google.api_core
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1
|
||||
from google.api_core import retry as retries
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.oauth2 import service_account # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3 import gapic_version as package_version
|
||||
from google.cloud.resourcemanager_v3.types import organizations
|
||||
|
||||
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
||||
gapic_version=package_version.__version__
|
||||
)
|
||||
|
||||
|
||||
class OrganizationsTransport(abc.ABC):
|
||||
"""Abstract transport class for Organizations."""
|
||||
|
||||
AUTH_SCOPES = (
|
||||
"https://www.googleapis.com/auth/cloud-platform",
|
||||
"https://www.googleapis.com/auth/cloud-platform.read-only",
|
||||
)
|
||||
|
||||
DEFAULT_HOST: str = "cloudresourcemanager.googleapis.com"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = DEFAULT_HOST,
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A list of scopes.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
"""
|
||||
|
||||
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
|
||||
|
||||
# Save the scopes.
|
||||
self._scopes = scopes
|
||||
if not hasattr(self, "_ignore_credentials"):
|
||||
self._ignore_credentials: bool = False
|
||||
|
||||
# If no credentials are provided, then determine the appropriate
|
||||
# defaults.
|
||||
if credentials and credentials_file:
|
||||
raise core_exceptions.DuplicateCredentialArgs(
|
||||
"'credentials_file' and 'credentials' are mutually exclusive"
|
||||
)
|
||||
|
||||
if credentials_file is not None:
|
||||
credentials, _ = google.auth.load_credentials_from_file(
|
||||
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
elif credentials is None and not self._ignore_credentials:
|
||||
credentials, _ = google.auth.default(
|
||||
**scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
# Don't apply audience if the credentials file passed from user.
|
||||
if hasattr(credentials, "with_gdch_audience"):
|
||||
credentials = credentials.with_gdch_audience(
|
||||
api_audience if api_audience else host
|
||||
)
|
||||
|
||||
# If the credentials are service account credentials, then always try to use self signed JWT.
|
||||
if (
|
||||
always_use_jwt_access
|
||||
and isinstance(credentials, service_account.Credentials)
|
||||
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
|
||||
):
|
||||
credentials = credentials.with_always_use_jwt_access(True)
|
||||
|
||||
# Save the credentials.
|
||||
self._credentials = credentials
|
||||
|
||||
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
|
||||
if ":" not in host:
|
||||
host += ":443"
|
||||
self._host = host
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
return self._host
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
# Precompute the wrapped methods.
|
||||
self._wrapped_methods = {
|
||||
self.get_organization: gapic_v1.method.wrap_method(
|
||||
self.get_organization,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.search_organizations: gapic_v1.method.wrap_method(
|
||||
self.search_organizations,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_iam_policy: gapic_v1.method.wrap_method(
|
||||
self.get_iam_policy,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.set_iam_policy: gapic_v1.method.wrap_method(
|
||||
self.set_iam_policy,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.test_iam_permissions: gapic_v1.method.wrap_method(
|
||||
self.test_iam_permissions,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: gapic_v1.method.wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def close(self):
|
||||
"""Closes resources associated with the transport.
|
||||
|
||||
.. warning::
|
||||
Only call this method if the transport is NOT shared
|
||||
with other clients - this may cause errors in other clients!
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_organization(
|
||||
self,
|
||||
) -> Callable[
|
||||
[organizations.GetOrganizationRequest],
|
||||
Union[organizations.Organization, Awaitable[organizations.Organization]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def search_organizations(
|
||||
self,
|
||||
) -> Callable[
|
||||
[organizations.SearchOrganizationsRequest],
|
||||
Union[
|
||||
organizations.SearchOrganizationsResponse,
|
||||
Awaitable[organizations.SearchOrganizationsResponse],
|
||||
],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.GetIamPolicyRequest],
|
||||
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.SetIamPolicyRequest],
|
||||
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
Union[
|
||||
iam_policy_pb2.TestIamPermissionsResponse,
|
||||
Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
|
||||
],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[
|
||||
[operations_pb2.GetOperationRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
__all__ = ("OrganizationsTransport",)
|
||||
@@ -0,0 +1,513 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import gapic_v1, grpc_helpers
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import organizations
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, OrganizationsTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
|
||||
def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Organizations",
|
||||
"rpcName": client_call_details.method,
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
|
||||
response = continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = response.result()
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response for {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Organizations",
|
||||
"rpcName": client_call_details.method,
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class OrganizationsGrpcTransport(OrganizationsTransport):
|
||||
"""gRPC backend transport for Organizations.
|
||||
|
||||
Allows users to manage their organization resources.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_stubs: Dict[str, Callable]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
||||
ignored if a ``channel`` instance is provided.
|
||||
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, grpc.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientInterceptor()
|
||||
self._logged_channel = grpc.intercept_channel(
|
||||
self._grpc_channel, self._interceptor
|
||||
)
|
||||
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> grpc.Channel:
|
||||
"""Create and return a gRPC channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
grpc.Channel: A gRPC channel object.
|
||||
|
||||
Raises:
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
|
||||
return grpc_helpers.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> grpc.Channel:
|
||||
"""Return the channel designed to connect to this service."""
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def get_organization(
|
||||
self,
|
||||
) -> Callable[[organizations.GetOrganizationRequest], organizations.Organization]:
|
||||
r"""Return a callable for the get organization method over gRPC.
|
||||
|
||||
Fetches an organization resource identified by the
|
||||
specified resource name.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetOrganizationRequest],
|
||||
~.Organization]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_organization" not in self._stubs:
|
||||
self._stubs["get_organization"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/GetOrganization",
|
||||
request_serializer=organizations.GetOrganizationRequest.serialize,
|
||||
response_deserializer=organizations.Organization.deserialize,
|
||||
)
|
||||
return self._stubs["get_organization"]
|
||||
|
||||
@property
|
||||
def search_organizations(
|
||||
self,
|
||||
) -> Callable[
|
||||
[organizations.SearchOrganizationsRequest],
|
||||
organizations.SearchOrganizationsResponse,
|
||||
]:
|
||||
r"""Return a callable for the search organizations method over gRPC.
|
||||
|
||||
Searches organization resources that are visible to the user and
|
||||
satisfy the specified filter. This method returns organizations
|
||||
in an unspecified order. New organizations do not necessarily
|
||||
appear at the end of the results, and may take a small amount of
|
||||
time to appear.
|
||||
|
||||
Search will only return organizations on which the user has the
|
||||
permission ``resourcemanager.organizations.get``
|
||||
|
||||
Returns:
|
||||
Callable[[~.SearchOrganizationsRequest],
|
||||
~.SearchOrganizationsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "search_organizations" not in self._stubs:
|
||||
self._stubs["search_organizations"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/SearchOrganizations",
|
||||
request_serializer=organizations.SearchOrganizationsRequest.serialize,
|
||||
response_deserializer=organizations.SearchOrganizationsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["search_organizations"]
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
|
||||
r"""Return a callable for the get iam policy method over gRPC.
|
||||
|
||||
Gets the access control policy for an organization resource. The
|
||||
policy may be empty if no such policy or resource exists. The
|
||||
``resource`` field should be the organization's resource name,
|
||||
for example: "organizations/123".
|
||||
|
||||
Authorization requires the IAM permission
|
||||
``resourcemanager.organizations.getIamPolicy`` on the specified
|
||||
organization.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetIamPolicyRequest],
|
||||
~.Policy]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_iam_policy" not in self._stubs:
|
||||
self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/GetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["get_iam_policy"]
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
|
||||
r"""Return a callable for the set iam policy method over gRPC.
|
||||
|
||||
Sets the access control policy on an organization resource.
|
||||
Replaces any existing policy. The ``resource`` field should be
|
||||
the organization's resource name, for example:
|
||||
"organizations/123".
|
||||
|
||||
Authorization requires the IAM permission
|
||||
``resourcemanager.organizations.setIamPolicy`` on the specified
|
||||
organization.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SetIamPolicyRequest],
|
||||
~.Policy]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "set_iam_policy" not in self._stubs:
|
||||
self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/SetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["set_iam_policy"]
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
iam_policy_pb2.TestIamPermissionsResponse,
|
||||
]:
|
||||
r"""Return a callable for the test iam permissions method over gRPC.
|
||||
|
||||
Returns the permissions that a caller has on the specified
|
||||
organization. The ``resource`` field should be the
|
||||
organization's resource name, for example: "organizations/123".
|
||||
|
||||
There are no permissions required for making this API call.
|
||||
|
||||
Returns:
|
||||
Callable[[~.TestIamPermissionsRequest],
|
||||
~.TestIamPermissionsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "test_iam_permissions" not in self._stubs:
|
||||
self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/TestIamPermissions",
|
||||
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
|
||||
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
|
||||
)
|
||||
return self._stubs["test_iam_permissions"]
|
||||
|
||||
def close(self):
|
||||
self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc"
|
||||
|
||||
|
||||
__all__ = ("OrganizationsGrpcTransport",)
|
||||
@@ -0,0 +1,580 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import inspect
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, grpc_helpers_async
|
||||
from google.api_core import retry_async as retries
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
from grpc.experimental import aio # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import organizations
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, OrganizationsTransport
|
||||
from .grpc import OrganizationsGrpcTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientAIOInterceptor(
|
||||
grpc.aio.UnaryUnaryClientInterceptor
|
||||
): # pragma: NO COVER
|
||||
async def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Organizations",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
response = await continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = await response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = await response
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response to rpc {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Organizations",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class OrganizationsGrpcAsyncIOTransport(OrganizationsTransport):
|
||||
"""gRPC AsyncIO backend transport for Organizations.
|
||||
|
||||
Allows users to manage their organization resources.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_grpc_channel: aio.Channel
|
||||
_stubs: Dict[str, Callable] = {}
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> aio.Channel:
|
||||
"""Create and return a gRPC AsyncIO channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
aio.Channel: A gRPC AsyncIO channel object.
|
||||
"""
|
||||
|
||||
return grpc_helpers_async.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, aio.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientAIOInterceptor()
|
||||
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
|
||||
self._logged_channel = self._grpc_channel
|
||||
self._wrap_with_kind = (
|
||||
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
|
||||
)
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> aio.Channel:
|
||||
"""Create the channel designed to connect to this service.
|
||||
|
||||
This property caches on the instance; repeated calls return
|
||||
the same channel.
|
||||
"""
|
||||
# Return the channel from cache.
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def get_organization(
|
||||
self,
|
||||
) -> Callable[
|
||||
[organizations.GetOrganizationRequest], Awaitable[organizations.Organization]
|
||||
]:
|
||||
r"""Return a callable for the get organization method over gRPC.
|
||||
|
||||
Fetches an organization resource identified by the
|
||||
specified resource name.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetOrganizationRequest],
|
||||
Awaitable[~.Organization]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_organization" not in self._stubs:
|
||||
self._stubs["get_organization"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/GetOrganization",
|
||||
request_serializer=organizations.GetOrganizationRequest.serialize,
|
||||
response_deserializer=organizations.Organization.deserialize,
|
||||
)
|
||||
return self._stubs["get_organization"]
|
||||
|
||||
@property
|
||||
def search_organizations(
|
||||
self,
|
||||
) -> Callable[
|
||||
[organizations.SearchOrganizationsRequest],
|
||||
Awaitable[organizations.SearchOrganizationsResponse],
|
||||
]:
|
||||
r"""Return a callable for the search organizations method over gRPC.
|
||||
|
||||
Searches organization resources that are visible to the user and
|
||||
satisfy the specified filter. This method returns organizations
|
||||
in an unspecified order. New organizations do not necessarily
|
||||
appear at the end of the results, and may take a small amount of
|
||||
time to appear.
|
||||
|
||||
Search will only return organizations on which the user has the
|
||||
permission ``resourcemanager.organizations.get``
|
||||
|
||||
Returns:
|
||||
Callable[[~.SearchOrganizationsRequest],
|
||||
Awaitable[~.SearchOrganizationsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "search_organizations" not in self._stubs:
|
||||
self._stubs["search_organizations"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/SearchOrganizations",
|
||||
request_serializer=organizations.SearchOrganizationsRequest.serialize,
|
||||
response_deserializer=organizations.SearchOrganizationsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["search_organizations"]
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
|
||||
r"""Return a callable for the get iam policy method over gRPC.
|
||||
|
||||
Gets the access control policy for an organization resource. The
|
||||
policy may be empty if no such policy or resource exists. The
|
||||
``resource`` field should be the organization's resource name,
|
||||
for example: "organizations/123".
|
||||
|
||||
Authorization requires the IAM permission
|
||||
``resourcemanager.organizations.getIamPolicy`` on the specified
|
||||
organization.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetIamPolicyRequest],
|
||||
Awaitable[~.Policy]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_iam_policy" not in self._stubs:
|
||||
self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/GetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["get_iam_policy"]
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
|
||||
r"""Return a callable for the set iam policy method over gRPC.
|
||||
|
||||
Sets the access control policy on an organization resource.
|
||||
Replaces any existing policy. The ``resource`` field should be
|
||||
the organization's resource name, for example:
|
||||
"organizations/123".
|
||||
|
||||
Authorization requires the IAM permission
|
||||
``resourcemanager.organizations.setIamPolicy`` on the specified
|
||||
organization.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SetIamPolicyRequest],
|
||||
Awaitable[~.Policy]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "set_iam_policy" not in self._stubs:
|
||||
self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/SetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["set_iam_policy"]
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
|
||||
]:
|
||||
r"""Return a callable for the test iam permissions method over gRPC.
|
||||
|
||||
Returns the permissions that a caller has on the specified
|
||||
organization. The ``resource`` field should be the
|
||||
organization's resource name, for example: "organizations/123".
|
||||
|
||||
There are no permissions required for making this API call.
|
||||
|
||||
Returns:
|
||||
Callable[[~.TestIamPermissionsRequest],
|
||||
Awaitable[~.TestIamPermissionsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "test_iam_permissions" not in self._stubs:
|
||||
self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Organizations/TestIamPermissions",
|
||||
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
|
||||
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
|
||||
)
|
||||
return self._stubs["test_iam_permissions"]
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
|
||||
self._wrapped_methods = {
|
||||
self.get_organization: self._wrap_method(
|
||||
self.get_organization,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.search_organizations: self._wrap_method(
|
||||
self.search_organizations,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_iam_policy: self._wrap_method(
|
||||
self.get_iam_policy,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.set_iam_policy: self._wrap_method(
|
||||
self.set_iam_policy,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.test_iam_permissions: self._wrap_method(
|
||||
self.test_iam_permissions,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: self._wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def _wrap_method(self, func, *args, **kwargs):
|
||||
if self._wrap_with_kind: # pragma: NO COVER
|
||||
kwargs["kind"] = self.kind
|
||||
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
|
||||
|
||||
def close(self):
|
||||
return self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc_asyncio"
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
|
||||
__all__ = ("OrganizationsGrpcAsyncIOTransport",)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,369 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json # type: ignore
|
||||
import re
|
||||
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
||||
|
||||
from google.api_core import gapic_v1, path_template
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf import json_format
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import organizations
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, OrganizationsTransport
|
||||
|
||||
|
||||
class _BaseOrganizationsRestTransport(OrganizationsTransport):
|
||||
"""Base REST backend transport for Organizations.
|
||||
|
||||
Note: This class is not meant to be used directly. Use its sync and
|
||||
async sub-classes instead.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends JSON representations of protocol buffers over HTTP/1.1
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[Any] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
url_scheme: str = "https",
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[Any]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you are developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
url_scheme: the protocol scheme for the API endpoint. Normally
|
||||
"https", but for testing or local servers,
|
||||
"http" can be specified.
|
||||
"""
|
||||
# Run the base constructor
|
||||
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
|
||||
if maybe_url_match is None:
|
||||
raise ValueError(
|
||||
f"Unexpected hostname structure: {host}"
|
||||
) # pragma: NO COVER
|
||||
|
||||
url_match_items = maybe_url_match.groupdict()
|
||||
|
||||
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
|
||||
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
class _BaseGetIamPolicy:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=organizations/*}:getIamPolicy",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseOrganizationsRestTransport._BaseGetIamPolicy._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetOrganization:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/{name=organizations/*}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = organizations.GetOrganizationRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseOrganizationsRestTransport._BaseGetOrganization._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseSearchOrganizations:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/organizations:search",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = organizations.SearchOrganizationsRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseSetIamPolicy:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=organizations/*}:setIamPolicy",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseOrganizationsRestTransport._BaseSetIamPolicy._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseTestIamPermissions:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=organizations/*}:testIamPermissions",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseOrganizationsRestTransport._BaseTestIamPermissions._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetOperation:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/{name=operations/**}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
request_kwargs = json_format.MessageToDict(request)
|
||||
transcoded_request = path_template.transcode(http_options, **request_kwargs)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
|
||||
return query_params
|
||||
|
||||
|
||||
__all__ = ("_BaseOrganizationsRestTransport",)
|
||||
@@ -0,0 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from .async_client import ProjectsAsyncClient
|
||||
from .client import ProjectsClient
|
||||
|
||||
__all__ = (
|
||||
"ProjectsClient",
|
||||
"ProjectsAsyncClient",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,353 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Iterator,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
|
||||
from google.api_core import gapic_v1
|
||||
from google.api_core import retry as retries
|
||||
from google.api_core import retry_async as retries_async
|
||||
|
||||
try:
|
||||
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
||||
OptionalAsyncRetry = Union[
|
||||
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
|
||||
]
|
||||
except AttributeError: # pragma: NO COVER
|
||||
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
||||
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import projects
|
||||
|
||||
|
||||
class ListProjectsPager:
|
||||
"""A pager for iterating through ``list_projects`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` object, and
|
||||
provides an ``__iter__`` method to iterate through its
|
||||
``projects`` field.
|
||||
|
||||
If there are more pages, the ``__iter__`` method will make additional
|
||||
``ListProjects`` requests and continue to iterate
|
||||
through the ``projects`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., projects.ListProjectsResponse],
|
||||
request: projects.ListProjectsRequest,
|
||||
response: projects.ListProjectsResponse,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiate the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListProjectsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListProjectsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.Retry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = projects.ListProjectsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
def pages(self) -> Iterator[projects.ListProjectsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __iter__(self) -> Iterator[projects.Project]:
|
||||
for page in self.pages:
|
||||
yield from page.projects
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class ListProjectsAsyncPager:
|
||||
"""A pager for iterating through ``list_projects`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse` object, and
|
||||
provides an ``__aiter__`` method to iterate through its
|
||||
``projects`` field.
|
||||
|
||||
If there are more pages, the ``__aiter__`` method will make additional
|
||||
``ListProjects`` requests and continue to iterate
|
||||
through the ``projects`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListProjectsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., Awaitable[projects.ListProjectsResponse]],
|
||||
request: projects.ListProjectsRequest,
|
||||
response: projects.ListProjectsResponse,
|
||||
*,
|
||||
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiates the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListProjectsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListProjectsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = projects.ListProjectsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
async def pages(self) -> AsyncIterator[projects.ListProjectsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = await self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __aiter__(self) -> AsyncIterator[projects.Project]:
|
||||
async def async_generator():
|
||||
async for page in self.pages:
|
||||
for response in page.projects:
|
||||
yield response
|
||||
|
||||
return async_generator()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class SearchProjectsPager:
|
||||
"""A pager for iterating through ``search_projects`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` object, and
|
||||
provides an ``__iter__`` method to iterate through its
|
||||
``projects`` field.
|
||||
|
||||
If there are more pages, the ``__iter__`` method will make additional
|
||||
``SearchProjects`` requests and continue to iterate
|
||||
through the ``projects`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., projects.SearchProjectsResponse],
|
||||
request: projects.SearchProjectsRequest,
|
||||
response: projects.SearchProjectsResponse,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiate the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.SearchProjectsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.SearchProjectsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.Retry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = projects.SearchProjectsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
def pages(self) -> Iterator[projects.SearchProjectsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __iter__(self) -> Iterator[projects.Project]:
|
||||
for page in self.pages:
|
||||
yield from page.projects
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class SearchProjectsAsyncPager:
|
||||
"""A pager for iterating through ``search_projects`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse` object, and
|
||||
provides an ``__aiter__`` method to iterate through its
|
||||
``projects`` field.
|
||||
|
||||
If there are more pages, the ``__aiter__`` method will make additional
|
||||
``SearchProjects`` requests and continue to iterate
|
||||
through the ``projects`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.SearchProjectsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., Awaitable[projects.SearchProjectsResponse]],
|
||||
request: projects.SearchProjectsRequest,
|
||||
response: projects.SearchProjectsResponse,
|
||||
*,
|
||||
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiates the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.SearchProjectsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.SearchProjectsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = projects.SearchProjectsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
async def pages(self) -> AsyncIterator[projects.SearchProjectsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = await self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __aiter__(self) -> AsyncIterator[projects.Project]:
|
||||
async def async_generator():
|
||||
async for page in self.pages:
|
||||
for response in page.projects:
|
||||
yield response
|
||||
|
||||
return async_generator()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from collections import OrderedDict
|
||||
from typing import Dict, Type
|
||||
|
||||
from .base import ProjectsTransport
|
||||
from .grpc import ProjectsGrpcTransport
|
||||
from .grpc_asyncio import ProjectsGrpcAsyncIOTransport
|
||||
from .rest import ProjectsRestInterceptor, ProjectsRestTransport
|
||||
|
||||
# Compile a registry of transports.
|
||||
_transport_registry = OrderedDict() # type: Dict[str, Type[ProjectsTransport]]
|
||||
_transport_registry["grpc"] = ProjectsGrpcTransport
|
||||
_transport_registry["grpc_asyncio"] = ProjectsGrpcAsyncIOTransport
|
||||
_transport_registry["rest"] = ProjectsRestTransport
|
||||
|
||||
__all__ = (
|
||||
"ProjectsTransport",
|
||||
"ProjectsGrpcTransport",
|
||||
"ProjectsGrpcAsyncIOTransport",
|
||||
"ProjectsRestTransport",
|
||||
"ProjectsRestInterceptor",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,358 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import abc
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
|
||||
|
||||
import google.api_core
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, operations_v1
|
||||
from google.api_core import retry as retries
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.oauth2 import service_account # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3 import gapic_version as package_version
|
||||
from google.cloud.resourcemanager_v3.types import projects
|
||||
|
||||
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
||||
gapic_version=package_version.__version__
|
||||
)
|
||||
|
||||
|
||||
class ProjectsTransport(abc.ABC):
|
||||
"""Abstract transport class for Projects."""
|
||||
|
||||
AUTH_SCOPES = (
|
||||
"https://www.googleapis.com/auth/cloud-platform",
|
||||
"https://www.googleapis.com/auth/cloud-platform.read-only",
|
||||
)
|
||||
|
||||
DEFAULT_HOST: str = "cloudresourcemanager.googleapis.com"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = DEFAULT_HOST,
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A list of scopes.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
"""
|
||||
|
||||
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
|
||||
|
||||
# Save the scopes.
|
||||
self._scopes = scopes
|
||||
if not hasattr(self, "_ignore_credentials"):
|
||||
self._ignore_credentials: bool = False
|
||||
|
||||
# If no credentials are provided, then determine the appropriate
|
||||
# defaults.
|
||||
if credentials and credentials_file:
|
||||
raise core_exceptions.DuplicateCredentialArgs(
|
||||
"'credentials_file' and 'credentials' are mutually exclusive"
|
||||
)
|
||||
|
||||
if credentials_file is not None:
|
||||
credentials, _ = google.auth.load_credentials_from_file(
|
||||
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
elif credentials is None and not self._ignore_credentials:
|
||||
credentials, _ = google.auth.default(
|
||||
**scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
# Don't apply audience if the credentials file passed from user.
|
||||
if hasattr(credentials, "with_gdch_audience"):
|
||||
credentials = credentials.with_gdch_audience(
|
||||
api_audience if api_audience else host
|
||||
)
|
||||
|
||||
# If the credentials are service account credentials, then always try to use self signed JWT.
|
||||
if (
|
||||
always_use_jwt_access
|
||||
and isinstance(credentials, service_account.Credentials)
|
||||
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
|
||||
):
|
||||
credentials = credentials.with_always_use_jwt_access(True)
|
||||
|
||||
# Save the credentials.
|
||||
self._credentials = credentials
|
||||
|
||||
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
|
||||
if ":" not in host:
|
||||
host += ":443"
|
||||
self._host = host
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
return self._host
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
# Precompute the wrapped methods.
|
||||
self._wrapped_methods = {
|
||||
self.get_project: gapic_v1.method.wrap_method(
|
||||
self.get_project,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.list_projects: gapic_v1.method.wrap_method(
|
||||
self.list_projects,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.search_projects: gapic_v1.method.wrap_method(
|
||||
self.search_projects,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.create_project: gapic_v1.method.wrap_method(
|
||||
self.create_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.update_project: gapic_v1.method.wrap_method(
|
||||
self.update_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.move_project: gapic_v1.method.wrap_method(
|
||||
self.move_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.delete_project: gapic_v1.method.wrap_method(
|
||||
self.delete_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.undelete_project: gapic_v1.method.wrap_method(
|
||||
self.undelete_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_iam_policy: gapic_v1.method.wrap_method(
|
||||
self.get_iam_policy,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.set_iam_policy: gapic_v1.method.wrap_method(
|
||||
self.set_iam_policy,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.test_iam_permissions: gapic_v1.method.wrap_method(
|
||||
self.test_iam_permissions,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: gapic_v1.method.wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def close(self):
|
||||
"""Closes resources associated with the transport.
|
||||
|
||||
.. warning::
|
||||
Only call this method if the transport is NOT shared
|
||||
with other clients - this may cause errors in other clients!
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def operations_client(self):
|
||||
"""Return the client designed to process long-running operations."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_project(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.GetProjectRequest],
|
||||
Union[projects.Project, Awaitable[projects.Project]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def list_projects(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.ListProjectsRequest],
|
||||
Union[projects.ListProjectsResponse, Awaitable[projects.ListProjectsResponse]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def search_projects(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.SearchProjectsRequest],
|
||||
Union[
|
||||
projects.SearchProjectsResponse, Awaitable[projects.SearchProjectsResponse]
|
||||
],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def create_project(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.CreateProjectRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def update_project(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.UpdateProjectRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def move_project(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.MoveProjectRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def delete_project(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.DeleteProjectRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def undelete_project(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.UndeleteProjectRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.GetIamPolicyRequest],
|
||||
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.SetIamPolicyRequest],
|
||||
Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
Union[
|
||||
iam_policy_pb2.TestIamPermissionsResponse,
|
||||
Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
|
||||
],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[
|
||||
[operations_pb2.GetOperationRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
__all__ = ("ProjectsTransport",)
|
||||
@@ -0,0 +1,796 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import gapic_v1, grpc_helpers, operations_v1
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import projects
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, ProjectsTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
|
||||
def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Projects",
|
||||
"rpcName": client_call_details.method,
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
|
||||
response = continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = response.result()
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response for {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Projects",
|
||||
"rpcName": client_call_details.method,
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class ProjectsGrpcTransport(ProjectsTransport):
|
||||
"""gRPC backend transport for Projects.
|
||||
|
||||
Manages Google Cloud Projects.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_stubs: Dict[str, Callable]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
||||
ignored if a ``channel`` instance is provided.
|
||||
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
self._operations_client: Optional[operations_v1.OperationsClient] = None
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, grpc.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientInterceptor()
|
||||
self._logged_channel = grpc.intercept_channel(
|
||||
self._grpc_channel, self._interceptor
|
||||
)
|
||||
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> grpc.Channel:
|
||||
"""Create and return a gRPC channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
grpc.Channel: A gRPC channel object.
|
||||
|
||||
Raises:
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
|
||||
return grpc_helpers.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> grpc.Channel:
|
||||
"""Return the channel designed to connect to this service."""
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def operations_client(self) -> operations_v1.OperationsClient:
|
||||
"""Create the client designed to process long-running operations.
|
||||
|
||||
This property caches on the instance; repeated calls return the same
|
||||
client.
|
||||
"""
|
||||
# Quick check: Only create a new client if we do not already have one.
|
||||
if self._operations_client is None:
|
||||
self._operations_client = operations_v1.OperationsClient(
|
||||
self._logged_channel
|
||||
)
|
||||
|
||||
# Return the client from cache.
|
||||
return self._operations_client
|
||||
|
||||
@property
|
||||
def get_project(self) -> Callable[[projects.GetProjectRequest], projects.Project]:
|
||||
r"""Return a callable for the get project method over gRPC.
|
||||
|
||||
Retrieves the project identified by the specified ``name`` (for
|
||||
example, ``projects/415104041262``).
|
||||
|
||||
The caller must have ``resourcemanager.projects.get`` permission
|
||||
for this project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetProjectRequest],
|
||||
~.Project]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_project" not in self._stubs:
|
||||
self._stubs["get_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/GetProject",
|
||||
request_serializer=projects.GetProjectRequest.serialize,
|
||||
response_deserializer=projects.Project.deserialize,
|
||||
)
|
||||
return self._stubs["get_project"]
|
||||
|
||||
@property
|
||||
def list_projects(
|
||||
self,
|
||||
) -> Callable[[projects.ListProjectsRequest], projects.ListProjectsResponse]:
|
||||
r"""Return a callable for the list projects method over gRPC.
|
||||
|
||||
Lists projects that are direct children of the specified folder
|
||||
or organization resource. ``list()`` provides a strongly
|
||||
consistent view of the projects underneath the specified parent
|
||||
resource. ``list()`` returns projects sorted based upon the
|
||||
(ascending) lexical ordering of their ``display_name``. The
|
||||
caller must have ``resourcemanager.projects.list`` permission on
|
||||
the identified parent.
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListProjectsRequest],
|
||||
~.ListProjectsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_projects" not in self._stubs:
|
||||
self._stubs["list_projects"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/ListProjects",
|
||||
request_serializer=projects.ListProjectsRequest.serialize,
|
||||
response_deserializer=projects.ListProjectsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_projects"]
|
||||
|
||||
@property
|
||||
def search_projects(
|
||||
self,
|
||||
) -> Callable[[projects.SearchProjectsRequest], projects.SearchProjectsResponse]:
|
||||
r"""Return a callable for the search projects method over gRPC.
|
||||
|
||||
Search for projects that the caller has both
|
||||
``resourcemanager.projects.get`` permission on, and also satisfy
|
||||
the specified query.
|
||||
|
||||
This method returns projects in an unspecified order.
|
||||
|
||||
This method is eventually consistent with project mutations;
|
||||
this means that a newly created project may not appear in the
|
||||
results or recent updates to an existing project may not be
|
||||
reflected in the results. To retrieve the latest state of a
|
||||
project, use the
|
||||
[GetProject][google.cloud.resourcemanager.v3.Projects.GetProject]
|
||||
method.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SearchProjectsRequest],
|
||||
~.SearchProjectsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "search_projects" not in self._stubs:
|
||||
self._stubs["search_projects"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/SearchProjects",
|
||||
request_serializer=projects.SearchProjectsRequest.serialize,
|
||||
response_deserializer=projects.SearchProjectsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["search_projects"]
|
||||
|
||||
@property
|
||||
def create_project(
|
||||
self,
|
||||
) -> Callable[[projects.CreateProjectRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the create project method over gRPC.
|
||||
|
||||
Request that a new project be created. The result is an
|
||||
``Operation`` which can be used to track the creation process.
|
||||
This process usually takes a few seconds, but can sometimes take
|
||||
much longer. The tracking ``Operation`` is automatically deleted
|
||||
after a few hours, so there is no need to call
|
||||
``DeleteOperation``.
|
||||
|
||||
Returns:
|
||||
Callable[[~.CreateProjectRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "create_project" not in self._stubs:
|
||||
self._stubs["create_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/CreateProject",
|
||||
request_serializer=projects.CreateProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["create_project"]
|
||||
|
||||
@property
|
||||
def update_project(
|
||||
self,
|
||||
) -> Callable[[projects.UpdateProjectRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the update project method over gRPC.
|
||||
|
||||
Updates the ``display_name`` and labels of the project
|
||||
identified by the specified ``name`` (for example,
|
||||
``projects/415104041262``). Deleting all labels requires an
|
||||
update mask for labels field.
|
||||
|
||||
The caller must have ``resourcemanager.projects.update``
|
||||
permission for this project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.UpdateProjectRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "update_project" not in self._stubs:
|
||||
self._stubs["update_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/UpdateProject",
|
||||
request_serializer=projects.UpdateProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["update_project"]
|
||||
|
||||
@property
|
||||
def move_project(
|
||||
self,
|
||||
) -> Callable[[projects.MoveProjectRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the move project method over gRPC.
|
||||
|
||||
Move a project to another place in your resource hierarchy,
|
||||
under a new resource parent.
|
||||
|
||||
Returns an operation which can be used to track the process of
|
||||
the project move workflow. Upon success, the
|
||||
``Operation.response`` field will be populated with the moved
|
||||
project.
|
||||
|
||||
The caller must have ``resourcemanager.projects.move``
|
||||
permission on the project, on the project's current and proposed
|
||||
new parent.
|
||||
|
||||
If project has no current parent, or it currently does not have
|
||||
an associated organization resource, you will also need the
|
||||
``resourcemanager.projects.setIamPolicy`` permission in the
|
||||
project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.MoveProjectRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "move_project" not in self._stubs:
|
||||
self._stubs["move_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/MoveProject",
|
||||
request_serializer=projects.MoveProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["move_project"]
|
||||
|
||||
@property
|
||||
def delete_project(
|
||||
self,
|
||||
) -> Callable[[projects.DeleteProjectRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the delete project method over gRPC.
|
||||
|
||||
Marks the project identified by the specified ``name`` (for
|
||||
example, ``projects/415104041262``) for deletion.
|
||||
|
||||
This method will only affect the project if it has a lifecycle
|
||||
state of
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE].
|
||||
|
||||
This method changes the Project's lifecycle state from
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]
|
||||
to
|
||||
[DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED].
|
||||
The deletion starts at an unspecified time, at which point the
|
||||
Project is no longer accessible.
|
||||
|
||||
Until the deletion completes, you can check the lifecycle state
|
||||
checked by retrieving the project with [GetProject]
|
||||
[google.cloud.resourcemanager.v3.Projects.GetProject], and the
|
||||
project remains visible to [ListProjects]
|
||||
[google.cloud.resourcemanager.v3.Projects.ListProjects].
|
||||
However, you cannot update the project.
|
||||
|
||||
After the deletion completes, the project is not retrievable by
|
||||
the [GetProject]
|
||||
[google.cloud.resourcemanager.v3.Projects.GetProject],
|
||||
[ListProjects]
|
||||
[google.cloud.resourcemanager.v3.Projects.ListProjects], and
|
||||
[SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]
|
||||
methods.
|
||||
|
||||
This method behaves idempotently, such that deleting a
|
||||
``DELETE_REQUESTED`` project will not cause an error, but also
|
||||
won't do anything.
|
||||
|
||||
The caller must have ``resourcemanager.projects.delete``
|
||||
permissions for this project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.DeleteProjectRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "delete_project" not in self._stubs:
|
||||
self._stubs["delete_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/DeleteProject",
|
||||
request_serializer=projects.DeleteProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["delete_project"]
|
||||
|
||||
@property
|
||||
def undelete_project(
|
||||
self,
|
||||
) -> Callable[[projects.UndeleteProjectRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the undelete project method over gRPC.
|
||||
|
||||
Restores the project identified by the specified ``name`` (for
|
||||
example, ``projects/415104041262``). You can only use this
|
||||
method for a project that has a lifecycle state of
|
||||
[DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After
|
||||
deletion starts, the project cannot be restored.
|
||||
|
||||
The caller must have ``resourcemanager.projects.undelete``
|
||||
permission for this project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.UndeleteProjectRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "undelete_project" not in self._stubs:
|
||||
self._stubs["undelete_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/UndeleteProject",
|
||||
request_serializer=projects.UndeleteProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["undelete_project"]
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
|
||||
r"""Return a callable for the get iam policy method over gRPC.
|
||||
|
||||
Returns the IAM access control policy for the specified project,
|
||||
in the format ``projects/{ProjectIdOrNumber}`` e.g.
|
||||
projects/123. Permission is denied if the policy or the resource
|
||||
do not exist.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetIamPolicyRequest],
|
||||
~.Policy]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_iam_policy" not in self._stubs:
|
||||
self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/GetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["get_iam_policy"]
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
|
||||
r"""Return a callable for the set iam policy method over gRPC.
|
||||
|
||||
Sets the IAM access control policy for the specified project, in
|
||||
the format ``projects/{ProjectIdOrNumber}`` e.g. projects/123.
|
||||
|
||||
CAUTION: This method will replace the existing policy, and
|
||||
cannot be used to append additional IAM settings.
|
||||
|
||||
Note: Removing service accounts from policies or changing their
|
||||
roles can render services completely inoperable. It is important
|
||||
to understand how the service account is being used before
|
||||
removing or updating its roles.
|
||||
|
||||
The following constraints apply when using ``setIamPolicy()``:
|
||||
|
||||
- Project does not support ``allUsers`` and
|
||||
``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of
|
||||
a ``Policy``.
|
||||
|
||||
- The owner role can be granted to a ``user``,
|
||||
``serviceAccount``, or a group that is part of an
|
||||
organization. For example, group@myownpersonaldomain.com
|
||||
could be added as an owner to a project in the
|
||||
myownpersonaldomain.com organization, but not the
|
||||
examplepetstore.com organization.
|
||||
|
||||
- Service accounts can be made owners of a project directly
|
||||
without any restrictions. However, to be added as an owner, a
|
||||
user must be invited using the Cloud Platform console and
|
||||
must accept the invitation.
|
||||
|
||||
- A user cannot be granted the owner role using
|
||||
``setIamPolicy()``. The user must be granted the owner role
|
||||
using the Cloud Platform Console and must explicitly accept
|
||||
the invitation.
|
||||
|
||||
- Invitations to grant the owner role cannot be sent using
|
||||
``setIamPolicy()``; they must be sent only using the Cloud
|
||||
Platform Console.
|
||||
|
||||
- If the project is not part of an organization, there must be
|
||||
at least one owner who has accepted the Terms of Service
|
||||
(ToS) agreement in the policy. Calling ``setIamPolicy()`` to
|
||||
remove the last ToS-accepted owner from the policy will fail.
|
||||
This restriction also applies to legacy projects that no
|
||||
longer have owners who have accepted the ToS. Edits to IAM
|
||||
policies will be rejected until the lack of a ToS-accepting
|
||||
owner is rectified. If the project is part of an
|
||||
organization, you can remove all owners, potentially making
|
||||
the organization inaccessible.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SetIamPolicyRequest],
|
||||
~.Policy]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "set_iam_policy" not in self._stubs:
|
||||
self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/SetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["set_iam_policy"]
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
iam_policy_pb2.TestIamPermissionsResponse,
|
||||
]:
|
||||
r"""Return a callable for the test iam permissions method over gRPC.
|
||||
|
||||
Returns permissions that a caller has on the specified project,
|
||||
in the format ``projects/{ProjectIdOrNumber}`` e.g.
|
||||
projects/123..
|
||||
|
||||
Returns:
|
||||
Callable[[~.TestIamPermissionsRequest],
|
||||
~.TestIamPermissionsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "test_iam_permissions" not in self._stubs:
|
||||
self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/TestIamPermissions",
|
||||
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
|
||||
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
|
||||
)
|
||||
return self._stubs["test_iam_permissions"]
|
||||
|
||||
def close(self):
|
||||
self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc"
|
||||
|
||||
|
||||
__all__ = ("ProjectsGrpcTransport",)
|
||||
@@ -0,0 +1,908 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import inspect
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, grpc_helpers_async, operations_v1
|
||||
from google.api_core import retry_async as retries
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
from grpc.experimental import aio # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import projects
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, ProjectsTransport
|
||||
from .grpc import ProjectsGrpcTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientAIOInterceptor(
|
||||
grpc.aio.UnaryUnaryClientInterceptor
|
||||
): # pragma: NO COVER
|
||||
async def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Projects",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
response = await continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = await response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = await response
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response to rpc {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.Projects",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class ProjectsGrpcAsyncIOTransport(ProjectsTransport):
|
||||
"""gRPC AsyncIO backend transport for Projects.
|
||||
|
||||
Manages Google Cloud Projects.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_grpc_channel: aio.Channel
|
||||
_stubs: Dict[str, Callable] = {}
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> aio.Channel:
|
||||
"""Create and return a gRPC AsyncIO channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
aio.Channel: A gRPC AsyncIO channel object.
|
||||
"""
|
||||
|
||||
return grpc_helpers_async.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, aio.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientAIOInterceptor()
|
||||
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
|
||||
self._logged_channel = self._grpc_channel
|
||||
self._wrap_with_kind = (
|
||||
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
|
||||
)
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> aio.Channel:
|
||||
"""Create the channel designed to connect to this service.
|
||||
|
||||
This property caches on the instance; repeated calls return
|
||||
the same channel.
|
||||
"""
|
||||
# Return the channel from cache.
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def operations_client(self) -> operations_v1.OperationsAsyncClient:
|
||||
"""Create the client designed to process long-running operations.
|
||||
|
||||
This property caches on the instance; repeated calls return the same
|
||||
client.
|
||||
"""
|
||||
# Quick check: Only create a new client if we do not already have one.
|
||||
if self._operations_client is None:
|
||||
self._operations_client = operations_v1.OperationsAsyncClient(
|
||||
self._logged_channel
|
||||
)
|
||||
|
||||
# Return the client from cache.
|
||||
return self._operations_client
|
||||
|
||||
@property
|
||||
def get_project(
|
||||
self,
|
||||
) -> Callable[[projects.GetProjectRequest], Awaitable[projects.Project]]:
|
||||
r"""Return a callable for the get project method over gRPC.
|
||||
|
||||
Retrieves the project identified by the specified ``name`` (for
|
||||
example, ``projects/415104041262``).
|
||||
|
||||
The caller must have ``resourcemanager.projects.get`` permission
|
||||
for this project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetProjectRequest],
|
||||
Awaitable[~.Project]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_project" not in self._stubs:
|
||||
self._stubs["get_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/GetProject",
|
||||
request_serializer=projects.GetProjectRequest.serialize,
|
||||
response_deserializer=projects.Project.deserialize,
|
||||
)
|
||||
return self._stubs["get_project"]
|
||||
|
||||
@property
|
||||
def list_projects(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.ListProjectsRequest], Awaitable[projects.ListProjectsResponse]
|
||||
]:
|
||||
r"""Return a callable for the list projects method over gRPC.
|
||||
|
||||
Lists projects that are direct children of the specified folder
|
||||
or organization resource. ``list()`` provides a strongly
|
||||
consistent view of the projects underneath the specified parent
|
||||
resource. ``list()`` returns projects sorted based upon the
|
||||
(ascending) lexical ordering of their ``display_name``. The
|
||||
caller must have ``resourcemanager.projects.list`` permission on
|
||||
the identified parent.
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListProjectsRequest],
|
||||
Awaitable[~.ListProjectsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_projects" not in self._stubs:
|
||||
self._stubs["list_projects"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/ListProjects",
|
||||
request_serializer=projects.ListProjectsRequest.serialize,
|
||||
response_deserializer=projects.ListProjectsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_projects"]
|
||||
|
||||
@property
|
||||
def search_projects(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.SearchProjectsRequest], Awaitable[projects.SearchProjectsResponse]
|
||||
]:
|
||||
r"""Return a callable for the search projects method over gRPC.
|
||||
|
||||
Search for projects that the caller has both
|
||||
``resourcemanager.projects.get`` permission on, and also satisfy
|
||||
the specified query.
|
||||
|
||||
This method returns projects in an unspecified order.
|
||||
|
||||
This method is eventually consistent with project mutations;
|
||||
this means that a newly created project may not appear in the
|
||||
results or recent updates to an existing project may not be
|
||||
reflected in the results. To retrieve the latest state of a
|
||||
project, use the
|
||||
[GetProject][google.cloud.resourcemanager.v3.Projects.GetProject]
|
||||
method.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SearchProjectsRequest],
|
||||
Awaitable[~.SearchProjectsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "search_projects" not in self._stubs:
|
||||
self._stubs["search_projects"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/SearchProjects",
|
||||
request_serializer=projects.SearchProjectsRequest.serialize,
|
||||
response_deserializer=projects.SearchProjectsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["search_projects"]
|
||||
|
||||
@property
|
||||
def create_project(
|
||||
self,
|
||||
) -> Callable[[projects.CreateProjectRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the create project method over gRPC.
|
||||
|
||||
Request that a new project be created. The result is an
|
||||
``Operation`` which can be used to track the creation process.
|
||||
This process usually takes a few seconds, but can sometimes take
|
||||
much longer. The tracking ``Operation`` is automatically deleted
|
||||
after a few hours, so there is no need to call
|
||||
``DeleteOperation``.
|
||||
|
||||
Returns:
|
||||
Callable[[~.CreateProjectRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "create_project" not in self._stubs:
|
||||
self._stubs["create_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/CreateProject",
|
||||
request_serializer=projects.CreateProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["create_project"]
|
||||
|
||||
@property
|
||||
def update_project(
|
||||
self,
|
||||
) -> Callable[[projects.UpdateProjectRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the update project method over gRPC.
|
||||
|
||||
Updates the ``display_name`` and labels of the project
|
||||
identified by the specified ``name`` (for example,
|
||||
``projects/415104041262``). Deleting all labels requires an
|
||||
update mask for labels field.
|
||||
|
||||
The caller must have ``resourcemanager.projects.update``
|
||||
permission for this project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.UpdateProjectRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "update_project" not in self._stubs:
|
||||
self._stubs["update_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/UpdateProject",
|
||||
request_serializer=projects.UpdateProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["update_project"]
|
||||
|
||||
@property
|
||||
def move_project(
|
||||
self,
|
||||
) -> Callable[[projects.MoveProjectRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the move project method over gRPC.
|
||||
|
||||
Move a project to another place in your resource hierarchy,
|
||||
under a new resource parent.
|
||||
|
||||
Returns an operation which can be used to track the process of
|
||||
the project move workflow. Upon success, the
|
||||
``Operation.response`` field will be populated with the moved
|
||||
project.
|
||||
|
||||
The caller must have ``resourcemanager.projects.move``
|
||||
permission on the project, on the project's current and proposed
|
||||
new parent.
|
||||
|
||||
If project has no current parent, or it currently does not have
|
||||
an associated organization resource, you will also need the
|
||||
``resourcemanager.projects.setIamPolicy`` permission in the
|
||||
project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.MoveProjectRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "move_project" not in self._stubs:
|
||||
self._stubs["move_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/MoveProject",
|
||||
request_serializer=projects.MoveProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["move_project"]
|
||||
|
||||
@property
|
||||
def delete_project(
|
||||
self,
|
||||
) -> Callable[[projects.DeleteProjectRequest], Awaitable[operations_pb2.Operation]]:
|
||||
r"""Return a callable for the delete project method over gRPC.
|
||||
|
||||
Marks the project identified by the specified ``name`` (for
|
||||
example, ``projects/415104041262``) for deletion.
|
||||
|
||||
This method will only affect the project if it has a lifecycle
|
||||
state of
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE].
|
||||
|
||||
This method changes the Project's lifecycle state from
|
||||
[ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]
|
||||
to
|
||||
[DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED].
|
||||
The deletion starts at an unspecified time, at which point the
|
||||
Project is no longer accessible.
|
||||
|
||||
Until the deletion completes, you can check the lifecycle state
|
||||
checked by retrieving the project with [GetProject]
|
||||
[google.cloud.resourcemanager.v3.Projects.GetProject], and the
|
||||
project remains visible to [ListProjects]
|
||||
[google.cloud.resourcemanager.v3.Projects.ListProjects].
|
||||
However, you cannot update the project.
|
||||
|
||||
After the deletion completes, the project is not retrievable by
|
||||
the [GetProject]
|
||||
[google.cloud.resourcemanager.v3.Projects.GetProject],
|
||||
[ListProjects]
|
||||
[google.cloud.resourcemanager.v3.Projects.ListProjects], and
|
||||
[SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]
|
||||
methods.
|
||||
|
||||
This method behaves idempotently, such that deleting a
|
||||
``DELETE_REQUESTED`` project will not cause an error, but also
|
||||
won't do anything.
|
||||
|
||||
The caller must have ``resourcemanager.projects.delete``
|
||||
permissions for this project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.DeleteProjectRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "delete_project" not in self._stubs:
|
||||
self._stubs["delete_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/DeleteProject",
|
||||
request_serializer=projects.DeleteProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["delete_project"]
|
||||
|
||||
@property
|
||||
def undelete_project(
|
||||
self,
|
||||
) -> Callable[
|
||||
[projects.UndeleteProjectRequest], Awaitable[operations_pb2.Operation]
|
||||
]:
|
||||
r"""Return a callable for the undelete project method over gRPC.
|
||||
|
||||
Restores the project identified by the specified ``name`` (for
|
||||
example, ``projects/415104041262``). You can only use this
|
||||
method for a project that has a lifecycle state of
|
||||
[DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After
|
||||
deletion starts, the project cannot be restored.
|
||||
|
||||
The caller must have ``resourcemanager.projects.undelete``
|
||||
permission for this project.
|
||||
|
||||
Returns:
|
||||
Callable[[~.UndeleteProjectRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "undelete_project" not in self._stubs:
|
||||
self._stubs["undelete_project"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/UndeleteProject",
|
||||
request_serializer=projects.UndeleteProjectRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["undelete_project"]
|
||||
|
||||
@property
|
||||
def get_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
|
||||
r"""Return a callable for the get iam policy method over gRPC.
|
||||
|
||||
Returns the IAM access control policy for the specified project,
|
||||
in the format ``projects/{ProjectIdOrNumber}`` e.g.
|
||||
projects/123. Permission is denied if the policy or the resource
|
||||
do not exist.
|
||||
|
||||
Returns:
|
||||
Callable[[~.GetIamPolicyRequest],
|
||||
Awaitable[~.Policy]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_iam_policy" not in self._stubs:
|
||||
self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/GetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["get_iam_policy"]
|
||||
|
||||
@property
|
||||
def set_iam_policy(
|
||||
self,
|
||||
) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
|
||||
r"""Return a callable for the set iam policy method over gRPC.
|
||||
|
||||
Sets the IAM access control policy for the specified project, in
|
||||
the format ``projects/{ProjectIdOrNumber}`` e.g. projects/123.
|
||||
|
||||
CAUTION: This method will replace the existing policy, and
|
||||
cannot be used to append additional IAM settings.
|
||||
|
||||
Note: Removing service accounts from policies or changing their
|
||||
roles can render services completely inoperable. It is important
|
||||
to understand how the service account is being used before
|
||||
removing or updating its roles.
|
||||
|
||||
The following constraints apply when using ``setIamPolicy()``:
|
||||
|
||||
- Project does not support ``allUsers`` and
|
||||
``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of
|
||||
a ``Policy``.
|
||||
|
||||
- The owner role can be granted to a ``user``,
|
||||
``serviceAccount``, or a group that is part of an
|
||||
organization. For example, group@myownpersonaldomain.com
|
||||
could be added as an owner to a project in the
|
||||
myownpersonaldomain.com organization, but not the
|
||||
examplepetstore.com organization.
|
||||
|
||||
- Service accounts can be made owners of a project directly
|
||||
without any restrictions. However, to be added as an owner, a
|
||||
user must be invited using the Cloud Platform console and
|
||||
must accept the invitation.
|
||||
|
||||
- A user cannot be granted the owner role using
|
||||
``setIamPolicy()``. The user must be granted the owner role
|
||||
using the Cloud Platform Console and must explicitly accept
|
||||
the invitation.
|
||||
|
||||
- Invitations to grant the owner role cannot be sent using
|
||||
``setIamPolicy()``; they must be sent only using the Cloud
|
||||
Platform Console.
|
||||
|
||||
- If the project is not part of an organization, there must be
|
||||
at least one owner who has accepted the Terms of Service
|
||||
(ToS) agreement in the policy. Calling ``setIamPolicy()`` to
|
||||
remove the last ToS-accepted owner from the policy will fail.
|
||||
This restriction also applies to legacy projects that no
|
||||
longer have owners who have accepted the ToS. Edits to IAM
|
||||
policies will be rejected until the lack of a ToS-accepting
|
||||
owner is rectified. If the project is part of an
|
||||
organization, you can remove all owners, potentially making
|
||||
the organization inaccessible.
|
||||
|
||||
Returns:
|
||||
Callable[[~.SetIamPolicyRequest],
|
||||
Awaitable[~.Policy]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "set_iam_policy" not in self._stubs:
|
||||
self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/SetIamPolicy",
|
||||
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
|
||||
response_deserializer=policy_pb2.Policy.FromString,
|
||||
)
|
||||
return self._stubs["set_iam_policy"]
|
||||
|
||||
@property
|
||||
def test_iam_permissions(
|
||||
self,
|
||||
) -> Callable[
|
||||
[iam_policy_pb2.TestIamPermissionsRequest],
|
||||
Awaitable[iam_policy_pb2.TestIamPermissionsResponse],
|
||||
]:
|
||||
r"""Return a callable for the test iam permissions method over gRPC.
|
||||
|
||||
Returns permissions that a caller has on the specified project,
|
||||
in the format ``projects/{ProjectIdOrNumber}`` e.g.
|
||||
projects/123..
|
||||
|
||||
Returns:
|
||||
Callable[[~.TestIamPermissionsRequest],
|
||||
Awaitable[~.TestIamPermissionsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "test_iam_permissions" not in self._stubs:
|
||||
self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.Projects/TestIamPermissions",
|
||||
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
|
||||
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
|
||||
)
|
||||
return self._stubs["test_iam_permissions"]
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
|
||||
self._wrapped_methods = {
|
||||
self.get_project: self._wrap_method(
|
||||
self.get_project,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.list_projects: self._wrap_method(
|
||||
self.list_projects,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.search_projects: self._wrap_method(
|
||||
self.search_projects,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.create_project: self._wrap_method(
|
||||
self.create_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.update_project: self._wrap_method(
|
||||
self.update_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.move_project: self._wrap_method(
|
||||
self.move_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.delete_project: self._wrap_method(
|
||||
self.delete_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.undelete_project: self._wrap_method(
|
||||
self.undelete_project,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_iam_policy: self._wrap_method(
|
||||
self.get_iam_policy,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.set_iam_policy: self._wrap_method(
|
||||
self.set_iam_policy,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.test_iam_permissions: self._wrap_method(
|
||||
self.test_iam_permissions,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: self._wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def _wrap_method(self, func, *args, **kwargs):
|
||||
if self._wrap_with_kind: # pragma: NO COVER
|
||||
kwargs["kind"] = self.kind
|
||||
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
|
||||
|
||||
def close(self):
|
||||
return self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc_asyncio"
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
|
||||
__all__ = ("ProjectsGrpcAsyncIOTransport",)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,693 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json # type: ignore
|
||||
import re
|
||||
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
||||
|
||||
from google.api_core import gapic_v1, path_template
|
||||
from google.iam.v1 import iam_policy_pb2 # type: ignore
|
||||
from google.iam.v1 import policy_pb2 # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf import json_format
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import projects
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, ProjectsTransport
|
||||
|
||||
|
||||
class _BaseProjectsRestTransport(ProjectsTransport):
|
||||
"""Base REST backend transport for Projects.
|
||||
|
||||
Note: This class is not meant to be used directly. Use its sync and
|
||||
async sub-classes instead.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends JSON representations of protocol buffers over HTTP/1.1
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[Any] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
url_scheme: str = "https",
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[Any]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you are developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
url_scheme: the protocol scheme for the API endpoint. Normally
|
||||
"https", but for testing or local servers,
|
||||
"http" can be specified.
|
||||
"""
|
||||
# Run the base constructor
|
||||
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
|
||||
if maybe_url_match is None:
|
||||
raise ValueError(
|
||||
f"Unexpected hostname structure: {host}"
|
||||
) # pragma: NO COVER
|
||||
|
||||
url_match_items = maybe_url_match.groupdict()
|
||||
|
||||
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
|
||||
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
class _BaseCreateProject:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/projects",
|
||||
"body": "project",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = projects.CreateProjectRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseCreateProject._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseDeleteProject:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "delete",
|
||||
"uri": "/v3/{name=projects/*}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = projects.DeleteProjectRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseDeleteProject._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetIamPolicy:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=projects/*}:getIamPolicy",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseGetIamPolicy._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetProject:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/{name=projects/*}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = projects.GetProjectRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseGetProject._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseListProjects:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
|
||||
"parent": "",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/projects",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = projects.ListProjectsRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseListProjects._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseMoveProject:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{name=projects/*}:move",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = projects.MoveProjectRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseMoveProject._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseSearchProjects:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/projects:search",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = projects.SearchProjectsRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseSetIamPolicy:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=projects/*}:setIamPolicy",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseSetIamPolicy._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseTestIamPermissions:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{resource=projects/*}:testIamPermissions",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = request
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseTestIamPermissions._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseUndeleteProject:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/{name=projects/*}:undelete",
|
||||
"body": "*",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = projects.UndeleteProjectRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseUndeleteProject._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseUpdateProject:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "patch",
|
||||
"uri": "/v3/{project.name=projects/*}",
|
||||
"body": "project",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = projects.UpdateProjectRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseProjectsRestTransport._BaseUpdateProject._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetOperation:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/{name=operations/**}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
request_kwargs = json_format.MessageToDict(request)
|
||||
transcoded_request = path_template.transcode(http_options, **request_kwargs)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
|
||||
return query_params
|
||||
|
||||
|
||||
__all__ = ("_BaseProjectsRestTransport",)
|
||||
@@ -0,0 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from .async_client import TagBindingsAsyncClient
|
||||
from .client import TagBindingsClient
|
||||
|
||||
__all__ = (
|
||||
"TagBindingsClient",
|
||||
"TagBindingsAsyncClient",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,869 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from collections import OrderedDict
|
||||
import logging as std_logging
|
||||
import re
|
||||
from typing import (
|
||||
Callable,
|
||||
Dict,
|
||||
Mapping,
|
||||
MutableMapping,
|
||||
MutableSequence,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
Type,
|
||||
Union,
|
||||
)
|
||||
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1
|
||||
from google.api_core import retry_async as retries
|
||||
from google.api_core.client_options import ClientOptions
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.oauth2 import service_account # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3 import gapic_version as package_version
|
||||
|
||||
try:
|
||||
OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
|
||||
except AttributeError: # pragma: NO COVER
|
||||
OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
|
||||
|
||||
from google.api_core import operation # type: ignore
|
||||
from google.api_core import operation_async # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf import empty_pb2 # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.services.tag_bindings import pagers
|
||||
from google.cloud.resourcemanager_v3.types import tag_bindings
|
||||
|
||||
from .client import TagBindingsClient
|
||||
from .transports.base import DEFAULT_CLIENT_INFO, TagBindingsTransport
|
||||
from .transports.grpc_asyncio import TagBindingsGrpcAsyncIOTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TagBindingsAsyncClient:
|
||||
"""Allow users to create and manage TagBindings between
|
||||
TagValues and different Google Cloud resources throughout the
|
||||
GCP resource hierarchy.
|
||||
"""
|
||||
|
||||
_client: TagBindingsClient
|
||||
|
||||
# Copy defaults from the synchronous client for use here.
|
||||
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
|
||||
DEFAULT_ENDPOINT = TagBindingsClient.DEFAULT_ENDPOINT
|
||||
DEFAULT_MTLS_ENDPOINT = TagBindingsClient.DEFAULT_MTLS_ENDPOINT
|
||||
_DEFAULT_ENDPOINT_TEMPLATE = TagBindingsClient._DEFAULT_ENDPOINT_TEMPLATE
|
||||
_DEFAULT_UNIVERSE = TagBindingsClient._DEFAULT_UNIVERSE
|
||||
|
||||
tag_binding_path = staticmethod(TagBindingsClient.tag_binding_path)
|
||||
parse_tag_binding_path = staticmethod(TagBindingsClient.parse_tag_binding_path)
|
||||
tag_key_path = staticmethod(TagBindingsClient.tag_key_path)
|
||||
parse_tag_key_path = staticmethod(TagBindingsClient.parse_tag_key_path)
|
||||
tag_value_path = staticmethod(TagBindingsClient.tag_value_path)
|
||||
parse_tag_value_path = staticmethod(TagBindingsClient.parse_tag_value_path)
|
||||
common_billing_account_path = staticmethod(
|
||||
TagBindingsClient.common_billing_account_path
|
||||
)
|
||||
parse_common_billing_account_path = staticmethod(
|
||||
TagBindingsClient.parse_common_billing_account_path
|
||||
)
|
||||
common_folder_path = staticmethod(TagBindingsClient.common_folder_path)
|
||||
parse_common_folder_path = staticmethod(TagBindingsClient.parse_common_folder_path)
|
||||
common_organization_path = staticmethod(TagBindingsClient.common_organization_path)
|
||||
parse_common_organization_path = staticmethod(
|
||||
TagBindingsClient.parse_common_organization_path
|
||||
)
|
||||
common_project_path = staticmethod(TagBindingsClient.common_project_path)
|
||||
parse_common_project_path = staticmethod(
|
||||
TagBindingsClient.parse_common_project_path
|
||||
)
|
||||
common_location_path = staticmethod(TagBindingsClient.common_location_path)
|
||||
parse_common_location_path = staticmethod(
|
||||
TagBindingsClient.parse_common_location_path
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_service_account_info(cls, info: dict, *args, **kwargs):
|
||||
"""Creates an instance of this client using the provided credentials
|
||||
info.
|
||||
|
||||
Args:
|
||||
info (dict): The service account private key info.
|
||||
args: Additional arguments to pass to the constructor.
|
||||
kwargs: Additional arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
TagBindingsAsyncClient: The constructed client.
|
||||
"""
|
||||
return TagBindingsClient.from_service_account_info.__func__(TagBindingsAsyncClient, info, *args, **kwargs) # type: ignore
|
||||
|
||||
@classmethod
|
||||
def from_service_account_file(cls, filename: str, *args, **kwargs):
|
||||
"""Creates an instance of this client using the provided credentials
|
||||
file.
|
||||
|
||||
Args:
|
||||
filename (str): The path to the service account private key json
|
||||
file.
|
||||
args: Additional arguments to pass to the constructor.
|
||||
kwargs: Additional arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
TagBindingsAsyncClient: The constructed client.
|
||||
"""
|
||||
return TagBindingsClient.from_service_account_file.__func__(TagBindingsAsyncClient, filename, *args, **kwargs) # type: ignore
|
||||
|
||||
from_service_account_json = from_service_account_file
|
||||
|
||||
@classmethod
|
||||
def get_mtls_endpoint_and_cert_source(
|
||||
cls, client_options: Optional[ClientOptions] = None
|
||||
):
|
||||
"""Return the API endpoint and client cert source for mutual TLS.
|
||||
|
||||
The client cert source is determined in the following order:
|
||||
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
|
||||
client cert source is None.
|
||||
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
|
||||
default client cert source exists, use the default one; otherwise the client cert
|
||||
source is None.
|
||||
|
||||
The API endpoint is determined in the following order:
|
||||
(1) if `client_options.api_endpoint` if provided, use the provided one.
|
||||
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
|
||||
default mTLS endpoint; if the environment variable is "never", use the default API
|
||||
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
|
||||
use the default API endpoint.
|
||||
|
||||
More details can be found at https://google.aip.dev/auth/4114.
|
||||
|
||||
Args:
|
||||
client_options (google.api_core.client_options.ClientOptions): Custom options for the
|
||||
client. Only the `api_endpoint` and `client_cert_source` properties may be used
|
||||
in this method.
|
||||
|
||||
Returns:
|
||||
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
|
||||
client cert source to use.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
|
||||
"""
|
||||
return TagBindingsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
|
||||
|
||||
@property
|
||||
def transport(self) -> TagBindingsTransport:
|
||||
"""Returns the transport used by the client instance.
|
||||
|
||||
Returns:
|
||||
TagBindingsTransport: The transport used by the client instance.
|
||||
"""
|
||||
return self._client.transport
|
||||
|
||||
@property
|
||||
def api_endpoint(self):
|
||||
"""Return the API endpoint used by the client instance.
|
||||
|
||||
Returns:
|
||||
str: The API endpoint used by the client instance.
|
||||
"""
|
||||
return self._client._api_endpoint
|
||||
|
||||
@property
|
||||
def universe_domain(self) -> str:
|
||||
"""Return the universe domain used by the client instance.
|
||||
|
||||
Returns:
|
||||
str: The universe domain used
|
||||
by the client instance.
|
||||
"""
|
||||
return self._client._universe_domain
|
||||
|
||||
get_transport_class = TagBindingsClient.get_transport_class
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
transport: Optional[
|
||||
Union[str, TagBindingsTransport, Callable[..., TagBindingsTransport]]
|
||||
] = "grpc_asyncio",
|
||||
client_options: Optional[ClientOptions] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
) -> None:
|
||||
"""Instantiates the tag bindings async client.
|
||||
|
||||
Args:
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
transport (Optional[Union[str,TagBindingsTransport,Callable[..., TagBindingsTransport]]]):
|
||||
The transport to use, or a Callable that constructs and returns a new transport to use.
|
||||
If a Callable is given, it will be called with the same set of initialization
|
||||
arguments as used in the TagBindingsTransport constructor.
|
||||
If set to None, a transport is chosen automatically.
|
||||
client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
|
||||
Custom options for the client.
|
||||
|
||||
1. The ``api_endpoint`` property can be used to override the
|
||||
default endpoint provided by the client when ``transport`` is
|
||||
not explicitly provided. Only if this property is not set and
|
||||
``transport`` was not explicitly provided, the endpoint is
|
||||
determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
|
||||
variable, which have one of the following values:
|
||||
"always" (always use the default mTLS endpoint), "never" (always
|
||||
use the default regular endpoint) and "auto" (auto-switch to the
|
||||
default mTLS endpoint if client certificate is present; this is
|
||||
the default value).
|
||||
|
||||
2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
|
||||
is "true", then the ``client_cert_source`` property can be used
|
||||
to provide a client certificate for mTLS transport. If
|
||||
not provided, the default SSL client certificate will be used if
|
||||
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
|
||||
set, no client certificate will be used.
|
||||
|
||||
3. The ``universe_domain`` property can be used to override the
|
||||
default "googleapis.com" universe. Note that ``api_endpoint``
|
||||
property still takes precedence; and ``universe_domain`` is
|
||||
currently not supported for mTLS.
|
||||
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
"""
|
||||
self._client = TagBindingsClient(
|
||||
credentials=credentials,
|
||||
transport=transport,
|
||||
client_options=client_options,
|
||||
client_info=client_info,
|
||||
)
|
||||
|
||||
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
): # pragma: NO COVER
|
||||
_LOGGER.debug(
|
||||
"Created client `google.cloud.resourcemanager_v3.TagBindingsAsyncClient`.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagBindings",
|
||||
"universeDomain": getattr(
|
||||
self._client._transport._credentials, "universe_domain", ""
|
||||
),
|
||||
"credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
|
||||
"credentialsInfo": getattr(
|
||||
self.transport._credentials, "get_cred_info", lambda: None
|
||||
)(),
|
||||
}
|
||||
if hasattr(self._client._transport, "_credentials")
|
||||
else {
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagBindings",
|
||||
"credentialsType": None,
|
||||
},
|
||||
)
|
||||
|
||||
async def list_tag_bindings(
|
||||
self,
|
||||
request: Optional[Union[tag_bindings.ListTagBindingsRequest, dict]] = None,
|
||||
*,
|
||||
parent: Optional[str] = None,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> pagers.ListTagBindingsAsyncPager:
|
||||
r"""Lists the TagBindings for the given Google Cloud resource, as
|
||||
specified with ``parent``.
|
||||
|
||||
NOTE: The ``parent`` field is expected to be a full resource
|
||||
name:
|
||||
https://cloud.google.com/apis/design/resource_names#full_resource_name
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# This snippet has been automatically generated and should be regarded as a
|
||||
# code template only.
|
||||
# It will require modifications to work:
|
||||
# - It may require correct/in-range values for request initialization.
|
||||
# - It may require specifying regional endpoints when creating the service
|
||||
# client as shown in:
|
||||
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
||||
from google.cloud import resourcemanager_v3
|
||||
|
||||
async def sample_list_tag_bindings():
|
||||
# Create a client
|
||||
client = resourcemanager_v3.TagBindingsAsyncClient()
|
||||
|
||||
# Initialize request argument(s)
|
||||
request = resourcemanager_v3.ListTagBindingsRequest(
|
||||
parent="parent_value",
|
||||
)
|
||||
|
||||
# Make the request
|
||||
page_result = client.list_tag_bindings(request=request)
|
||||
|
||||
# Handle the response
|
||||
async for response in page_result:
|
||||
print(response)
|
||||
|
||||
Args:
|
||||
request (Optional[Union[google.cloud.resourcemanager_v3.types.ListTagBindingsRequest, dict]]):
|
||||
The request object. The request message to list all
|
||||
TagBindings for a parent.
|
||||
parent (:class:`str`):
|
||||
Required. The full resource name of a
|
||||
resource for which you want to list
|
||||
existing TagBindings. E.g.
|
||||
"//cloudresourcemanager.googleapis.com/projects/123"
|
||||
|
||||
This corresponds to the ``parent`` field
|
||||
on the ``request`` instance; if ``request`` is provided, this
|
||||
should not be set.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
||||
should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
|
||||
Returns:
|
||||
google.cloud.resourcemanager_v3.services.tag_bindings.pagers.ListTagBindingsAsyncPager:
|
||||
The ListTagBindings response.
|
||||
|
||||
Iterating over this object will yield
|
||||
results and resolve additional pages
|
||||
automatically.
|
||||
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# - Quick check: If we got a request object, we should *not* have
|
||||
# gotten any keyword arguments that map to the request.
|
||||
flattened_params = [parent]
|
||||
has_flattened_params = (
|
||||
len([param for param in flattened_params if param is not None]) > 0
|
||||
)
|
||||
if request is not None and has_flattened_params:
|
||||
raise ValueError(
|
||||
"If the `request` argument is set, then none of "
|
||||
"the individual field arguments should be set."
|
||||
)
|
||||
|
||||
# - Use the request object if provided (there's no risk of modifying the input as
|
||||
# there are no flattened fields), or create one.
|
||||
if not isinstance(request, tag_bindings.ListTagBindingsRequest):
|
||||
request = tag_bindings.ListTagBindingsRequest(request)
|
||||
|
||||
# If we have keyword arguments corresponding to fields on the
|
||||
# request, apply these.
|
||||
if parent is not None:
|
||||
request.parent = parent
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self._client._transport._wrapped_methods[
|
||||
self._client._transport.list_tag_bindings
|
||||
]
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# This method is paged; wrap the response in a pager, which provides
|
||||
# an `__aiter__` convenience method.
|
||||
response = pagers.ListTagBindingsAsyncPager(
|
||||
method=rpc,
|
||||
request=request,
|
||||
response=response,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def create_tag_binding(
|
||||
self,
|
||||
request: Optional[Union[tag_bindings.CreateTagBindingRequest, dict]] = None,
|
||||
*,
|
||||
tag_binding: Optional[tag_bindings.TagBinding] = None,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> operation_async.AsyncOperation:
|
||||
r"""Creates a TagBinding between a TagValue and a Google
|
||||
Cloud resource.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# This snippet has been automatically generated and should be regarded as a
|
||||
# code template only.
|
||||
# It will require modifications to work:
|
||||
# - It may require correct/in-range values for request initialization.
|
||||
# - It may require specifying regional endpoints when creating the service
|
||||
# client as shown in:
|
||||
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
||||
from google.cloud import resourcemanager_v3
|
||||
|
||||
async def sample_create_tag_binding():
|
||||
# Create a client
|
||||
client = resourcemanager_v3.TagBindingsAsyncClient()
|
||||
|
||||
# Initialize request argument(s)
|
||||
request = resourcemanager_v3.CreateTagBindingRequest(
|
||||
)
|
||||
|
||||
# Make the request
|
||||
operation = client.create_tag_binding(request=request)
|
||||
|
||||
print("Waiting for operation to complete...")
|
||||
|
||||
response = (await operation).result()
|
||||
|
||||
# Handle the response
|
||||
print(response)
|
||||
|
||||
Args:
|
||||
request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateTagBindingRequest, dict]]):
|
||||
The request object. The request message to create a
|
||||
TagBinding.
|
||||
tag_binding (:class:`google.cloud.resourcemanager_v3.types.TagBinding`):
|
||||
Required. The TagBinding to be
|
||||
created.
|
||||
|
||||
This corresponds to the ``tag_binding`` field
|
||||
on the ``request`` instance; if ``request`` is provided, this
|
||||
should not be set.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
||||
should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
|
||||
Returns:
|
||||
google.api_core.operation_async.AsyncOperation:
|
||||
An object representing a long-running operation.
|
||||
|
||||
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
|
||||
resource Once a TagBinding is created, the TagValue
|
||||
is applied to all the descendants of the Google Cloud
|
||||
resource.
|
||||
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# - Quick check: If we got a request object, we should *not* have
|
||||
# gotten any keyword arguments that map to the request.
|
||||
flattened_params = [tag_binding]
|
||||
has_flattened_params = (
|
||||
len([param for param in flattened_params if param is not None]) > 0
|
||||
)
|
||||
if request is not None and has_flattened_params:
|
||||
raise ValueError(
|
||||
"If the `request` argument is set, then none of "
|
||||
"the individual field arguments should be set."
|
||||
)
|
||||
|
||||
# - Use the request object if provided (there's no risk of modifying the input as
|
||||
# there are no flattened fields), or create one.
|
||||
if not isinstance(request, tag_bindings.CreateTagBindingRequest):
|
||||
request = tag_bindings.CreateTagBindingRequest(request)
|
||||
|
||||
# If we have keyword arguments corresponding to fields on the
|
||||
# request, apply these.
|
||||
if tag_binding is not None:
|
||||
request.tag_binding = tag_binding
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self._client._transport._wrapped_methods[
|
||||
self._client._transport.create_tag_binding
|
||||
]
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Wrap the response in an operation future.
|
||||
response = operation_async.from_gapic(
|
||||
response,
|
||||
self._client._transport.operations_client,
|
||||
tag_bindings.TagBinding,
|
||||
metadata_type=tag_bindings.CreateTagBindingMetadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def delete_tag_binding(
|
||||
self,
|
||||
request: Optional[Union[tag_bindings.DeleteTagBindingRequest, dict]] = None,
|
||||
*,
|
||||
name: Optional[str] = None,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> operation_async.AsyncOperation:
|
||||
r"""Deletes a TagBinding.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# This snippet has been automatically generated and should be regarded as a
|
||||
# code template only.
|
||||
# It will require modifications to work:
|
||||
# - It may require correct/in-range values for request initialization.
|
||||
# - It may require specifying regional endpoints when creating the service
|
||||
# client as shown in:
|
||||
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
||||
from google.cloud import resourcemanager_v3
|
||||
|
||||
async def sample_delete_tag_binding():
|
||||
# Create a client
|
||||
client = resourcemanager_v3.TagBindingsAsyncClient()
|
||||
|
||||
# Initialize request argument(s)
|
||||
request = resourcemanager_v3.DeleteTagBindingRequest(
|
||||
name="name_value",
|
||||
)
|
||||
|
||||
# Make the request
|
||||
operation = client.delete_tag_binding(request=request)
|
||||
|
||||
print("Waiting for operation to complete...")
|
||||
|
||||
response = (await operation).result()
|
||||
|
||||
# Handle the response
|
||||
print(response)
|
||||
|
||||
Args:
|
||||
request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteTagBindingRequest, dict]]):
|
||||
The request object. The request message to delete a
|
||||
TagBinding.
|
||||
name (:class:`str`):
|
||||
Required. The name of the TagBinding. This is a String
|
||||
of the form: ``tagBindings/{id}`` (e.g.
|
||||
``tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F123/tagValues/456``).
|
||||
|
||||
This corresponds to the ``name`` field
|
||||
on the ``request`` instance; if ``request`` is provided, this
|
||||
should not be set.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
||||
should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
|
||||
Returns:
|
||||
google.api_core.operation_async.AsyncOperation:
|
||||
An object representing a long-running operation.
|
||||
|
||||
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
|
||||
empty messages in your APIs. A typical example is to
|
||||
use it as the request or the response type of an API
|
||||
method. For instance:
|
||||
|
||||
service Foo {
|
||||
rpc Bar(google.protobuf.Empty) returns
|
||||
(google.protobuf.Empty);
|
||||
|
||||
}
|
||||
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# - Quick check: If we got a request object, we should *not* have
|
||||
# gotten any keyword arguments that map to the request.
|
||||
flattened_params = [name]
|
||||
has_flattened_params = (
|
||||
len([param for param in flattened_params if param is not None]) > 0
|
||||
)
|
||||
if request is not None and has_flattened_params:
|
||||
raise ValueError(
|
||||
"If the `request` argument is set, then none of "
|
||||
"the individual field arguments should be set."
|
||||
)
|
||||
|
||||
# - Use the request object if provided (there's no risk of modifying the input as
|
||||
# there are no flattened fields), or create one.
|
||||
if not isinstance(request, tag_bindings.DeleteTagBindingRequest):
|
||||
request = tag_bindings.DeleteTagBindingRequest(request)
|
||||
|
||||
# If we have keyword arguments corresponding to fields on the
|
||||
# request, apply these.
|
||||
if name is not None:
|
||||
request.name = name
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self._client._transport._wrapped_methods[
|
||||
self._client._transport.delete_tag_binding
|
||||
]
|
||||
|
||||
# Certain fields should be provided within the metadata header;
|
||||
# add these here.
|
||||
metadata = tuple(metadata) + (
|
||||
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
||||
)
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Wrap the response in an operation future.
|
||||
response = operation_async.from_gapic(
|
||||
response,
|
||||
self._client._transport.operations_client,
|
||||
empty_pb2.Empty,
|
||||
metadata_type=tag_bindings.DeleteTagBindingMetadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def list_effective_tags(
|
||||
self,
|
||||
request: Optional[Union[tag_bindings.ListEffectiveTagsRequest, dict]] = None,
|
||||
*,
|
||||
parent: Optional[str] = None,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> pagers.ListEffectiveTagsAsyncPager:
|
||||
r"""Return a list of effective tags for the given Google Cloud
|
||||
resource, as specified in ``parent``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# This snippet has been automatically generated and should be regarded as a
|
||||
# code template only.
|
||||
# It will require modifications to work:
|
||||
# - It may require correct/in-range values for request initialization.
|
||||
# - It may require specifying regional endpoints when creating the service
|
||||
# client as shown in:
|
||||
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
||||
from google.cloud import resourcemanager_v3
|
||||
|
||||
async def sample_list_effective_tags():
|
||||
# Create a client
|
||||
client = resourcemanager_v3.TagBindingsAsyncClient()
|
||||
|
||||
# Initialize request argument(s)
|
||||
request = resourcemanager_v3.ListEffectiveTagsRequest(
|
||||
parent="parent_value",
|
||||
)
|
||||
|
||||
# Make the request
|
||||
page_result = client.list_effective_tags(request=request)
|
||||
|
||||
# Handle the response
|
||||
async for response in page_result:
|
||||
print(response)
|
||||
|
||||
Args:
|
||||
request (Optional[Union[google.cloud.resourcemanager_v3.types.ListEffectiveTagsRequest, dict]]):
|
||||
The request object. The request message to
|
||||
ListEffectiveTags
|
||||
parent (:class:`str`):
|
||||
Required. The full resource name of a
|
||||
resource for which you want to list the
|
||||
effective tags. E.g.
|
||||
"//cloudresourcemanager.googleapis.com/projects/123"
|
||||
|
||||
This corresponds to the ``parent`` field
|
||||
on the ``request`` instance; if ``request`` is provided, this
|
||||
should not be set.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
||||
should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
|
||||
Returns:
|
||||
google.cloud.resourcemanager_v3.services.tag_bindings.pagers.ListEffectiveTagsAsyncPager:
|
||||
The response of ListEffectiveTags.
|
||||
|
||||
Iterating over this object will yield
|
||||
results and resolve additional pages
|
||||
automatically.
|
||||
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# - Quick check: If we got a request object, we should *not* have
|
||||
# gotten any keyword arguments that map to the request.
|
||||
flattened_params = [parent]
|
||||
has_flattened_params = (
|
||||
len([param for param in flattened_params if param is not None]) > 0
|
||||
)
|
||||
if request is not None and has_flattened_params:
|
||||
raise ValueError(
|
||||
"If the `request` argument is set, then none of "
|
||||
"the individual field arguments should be set."
|
||||
)
|
||||
|
||||
# - Use the request object if provided (there's no risk of modifying the input as
|
||||
# there are no flattened fields), or create one.
|
||||
if not isinstance(request, tag_bindings.ListEffectiveTagsRequest):
|
||||
request = tag_bindings.ListEffectiveTagsRequest(request)
|
||||
|
||||
# If we have keyword arguments corresponding to fields on the
|
||||
# request, apply these.
|
||||
if parent is not None:
|
||||
request.parent = parent
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self._client._transport._wrapped_methods[
|
||||
self._client._transport.list_effective_tags
|
||||
]
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# This method is paged; wrap the response in a pager, which provides
|
||||
# an `__aiter__` convenience method.
|
||||
response = pagers.ListEffectiveTagsAsyncPager(
|
||||
method=rpc,
|
||||
request=request,
|
||||
response=response,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def get_operation(
|
||||
self,
|
||||
request: Optional[operations_pb2.GetOperationRequest] = None,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> operations_pb2.Operation:
|
||||
r"""Gets the latest state of a long-running operation.
|
||||
|
||||
Args:
|
||||
request (:class:`~.operations_pb2.GetOperationRequest`):
|
||||
The request object. Request message for
|
||||
`GetOperation` method.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
Returns:
|
||||
~.operations_pb2.Operation:
|
||||
An ``Operation`` object.
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# The request isn't a proto-plus wrapped type,
|
||||
# so it must be constructed via keyword expansion.
|
||||
if isinstance(request, dict):
|
||||
request = operations_pb2.GetOperationRequest(**request)
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
|
||||
|
||||
# Certain fields should be provided within the metadata header;
|
||||
# add these here.
|
||||
metadata = tuple(metadata) + (
|
||||
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
||||
)
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def __aenter__(self) -> "TagBindingsAsyncClient":
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
await self.transport.close()
|
||||
|
||||
|
||||
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
||||
gapic_version=package_version.__version__
|
||||
)
|
||||
|
||||
|
||||
__all__ = ("TagBindingsAsyncClient",)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,353 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Iterator,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
|
||||
from google.api_core import gapic_v1
|
||||
from google.api_core import retry as retries
|
||||
from google.api_core import retry_async as retries_async
|
||||
|
||||
try:
|
||||
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
||||
OptionalAsyncRetry = Union[
|
||||
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
|
||||
]
|
||||
except AttributeError: # pragma: NO COVER
|
||||
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
||||
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import tag_bindings
|
||||
|
||||
|
||||
class ListTagBindingsPager:
|
||||
"""A pager for iterating through ``list_tag_bindings`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` object, and
|
||||
provides an ``__iter__`` method to iterate through its
|
||||
``tag_bindings`` field.
|
||||
|
||||
If there are more pages, the ``__iter__`` method will make additional
|
||||
``ListTagBindings`` requests and continue to iterate
|
||||
through the ``tag_bindings`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., tag_bindings.ListTagBindingsResponse],
|
||||
request: tag_bindings.ListTagBindingsRequest,
|
||||
response: tag_bindings.ListTagBindingsResponse,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiate the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListTagBindingsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListTagBindingsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.Retry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = tag_bindings.ListTagBindingsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
def pages(self) -> Iterator[tag_bindings.ListTagBindingsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __iter__(self) -> Iterator[tag_bindings.TagBinding]:
|
||||
for page in self.pages:
|
||||
yield from page.tag_bindings
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class ListTagBindingsAsyncPager:
|
||||
"""A pager for iterating through ``list_tag_bindings`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse` object, and
|
||||
provides an ``__aiter__`` method to iterate through its
|
||||
``tag_bindings`` field.
|
||||
|
||||
If there are more pages, the ``__aiter__`` method will make additional
|
||||
``ListTagBindings`` requests and continue to iterate
|
||||
through the ``tag_bindings`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagBindingsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., Awaitable[tag_bindings.ListTagBindingsResponse]],
|
||||
request: tag_bindings.ListTagBindingsRequest,
|
||||
response: tag_bindings.ListTagBindingsResponse,
|
||||
*,
|
||||
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiates the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListTagBindingsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListTagBindingsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = tag_bindings.ListTagBindingsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
async def pages(self) -> AsyncIterator[tag_bindings.ListTagBindingsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = await self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __aiter__(self) -> AsyncIterator[tag_bindings.TagBinding]:
|
||||
async def async_generator():
|
||||
async for page in self.pages:
|
||||
for response in page.tag_bindings:
|
||||
yield response
|
||||
|
||||
return async_generator()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class ListEffectiveTagsPager:
|
||||
"""A pager for iterating through ``list_effective_tags`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListEffectiveTagsResponse` object, and
|
||||
provides an ``__iter__`` method to iterate through its
|
||||
``effective_tags`` field.
|
||||
|
||||
If there are more pages, the ``__iter__`` method will make additional
|
||||
``ListEffectiveTags`` requests and continue to iterate
|
||||
through the ``effective_tags`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListEffectiveTagsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., tag_bindings.ListEffectiveTagsResponse],
|
||||
request: tag_bindings.ListEffectiveTagsRequest,
|
||||
response: tag_bindings.ListEffectiveTagsResponse,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiate the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListEffectiveTagsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListEffectiveTagsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.Retry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = tag_bindings.ListEffectiveTagsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
def pages(self) -> Iterator[tag_bindings.ListEffectiveTagsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __iter__(self) -> Iterator[tag_bindings.EffectiveTag]:
|
||||
for page in self.pages:
|
||||
yield from page.effective_tags
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class ListEffectiveTagsAsyncPager:
|
||||
"""A pager for iterating through ``list_effective_tags`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListEffectiveTagsResponse` object, and
|
||||
provides an ``__aiter__`` method to iterate through its
|
||||
``effective_tags`` field.
|
||||
|
||||
If there are more pages, the ``__aiter__`` method will make additional
|
||||
``ListEffectiveTags`` requests and continue to iterate
|
||||
through the ``effective_tags`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListEffectiveTagsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., Awaitable[tag_bindings.ListEffectiveTagsResponse]],
|
||||
request: tag_bindings.ListEffectiveTagsRequest,
|
||||
response: tag_bindings.ListEffectiveTagsResponse,
|
||||
*,
|
||||
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiates the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListEffectiveTagsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListEffectiveTagsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = tag_bindings.ListEffectiveTagsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
async def pages(self) -> AsyncIterator[tag_bindings.ListEffectiveTagsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = await self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __aiter__(self) -> AsyncIterator[tag_bindings.EffectiveTag]:
|
||||
async def async_generator():
|
||||
async for page in self.pages:
|
||||
for response in page.effective_tags:
|
||||
yield response
|
||||
|
||||
return async_generator()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from collections import OrderedDict
|
||||
from typing import Dict, Type
|
||||
|
||||
from .base import TagBindingsTransport
|
||||
from .grpc import TagBindingsGrpcTransport
|
||||
from .grpc_asyncio import TagBindingsGrpcAsyncIOTransport
|
||||
from .rest import TagBindingsRestInterceptor, TagBindingsRestTransport
|
||||
|
||||
# Compile a registry of transports.
|
||||
_transport_registry = OrderedDict() # type: Dict[str, Type[TagBindingsTransport]]
|
||||
_transport_registry["grpc"] = TagBindingsGrpcTransport
|
||||
_transport_registry["grpc_asyncio"] = TagBindingsGrpcAsyncIOTransport
|
||||
_transport_registry["rest"] = TagBindingsRestTransport
|
||||
|
||||
__all__ = (
|
||||
"TagBindingsTransport",
|
||||
"TagBindingsGrpcTransport",
|
||||
"TagBindingsGrpcAsyncIOTransport",
|
||||
"TagBindingsRestTransport",
|
||||
"TagBindingsRestInterceptor",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,241 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import abc
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
|
||||
|
||||
import google.api_core
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, operations_v1
|
||||
from google.api_core import retry as retries
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.oauth2 import service_account # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3 import gapic_version as package_version
|
||||
from google.cloud.resourcemanager_v3.types import tag_bindings
|
||||
|
||||
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
||||
gapic_version=package_version.__version__
|
||||
)
|
||||
|
||||
|
||||
class TagBindingsTransport(abc.ABC):
|
||||
"""Abstract transport class for TagBindings."""
|
||||
|
||||
AUTH_SCOPES = (
|
||||
"https://www.googleapis.com/auth/cloud-platform",
|
||||
"https://www.googleapis.com/auth/cloud-platform.read-only",
|
||||
)
|
||||
|
||||
DEFAULT_HOST: str = "cloudresourcemanager.googleapis.com"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = DEFAULT_HOST,
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A list of scopes.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
"""
|
||||
|
||||
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
|
||||
|
||||
# Save the scopes.
|
||||
self._scopes = scopes
|
||||
if not hasattr(self, "_ignore_credentials"):
|
||||
self._ignore_credentials: bool = False
|
||||
|
||||
# If no credentials are provided, then determine the appropriate
|
||||
# defaults.
|
||||
if credentials and credentials_file:
|
||||
raise core_exceptions.DuplicateCredentialArgs(
|
||||
"'credentials_file' and 'credentials' are mutually exclusive"
|
||||
)
|
||||
|
||||
if credentials_file is not None:
|
||||
credentials, _ = google.auth.load_credentials_from_file(
|
||||
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
elif credentials is None and not self._ignore_credentials:
|
||||
credentials, _ = google.auth.default(
|
||||
**scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
# Don't apply audience if the credentials file passed from user.
|
||||
if hasattr(credentials, "with_gdch_audience"):
|
||||
credentials = credentials.with_gdch_audience(
|
||||
api_audience if api_audience else host
|
||||
)
|
||||
|
||||
# If the credentials are service account credentials, then always try to use self signed JWT.
|
||||
if (
|
||||
always_use_jwt_access
|
||||
and isinstance(credentials, service_account.Credentials)
|
||||
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
|
||||
):
|
||||
credentials = credentials.with_always_use_jwt_access(True)
|
||||
|
||||
# Save the credentials.
|
||||
self._credentials = credentials
|
||||
|
||||
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
|
||||
if ":" not in host:
|
||||
host += ":443"
|
||||
self._host = host
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
return self._host
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
# Precompute the wrapped methods.
|
||||
self._wrapped_methods = {
|
||||
self.list_tag_bindings: gapic_v1.method.wrap_method(
|
||||
self.list_tag_bindings,
|
||||
default_retry=retries.Retry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.create_tag_binding: gapic_v1.method.wrap_method(
|
||||
self.create_tag_binding,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.delete_tag_binding: gapic_v1.method.wrap_method(
|
||||
self.delete_tag_binding,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.list_effective_tags: gapic_v1.method.wrap_method(
|
||||
self.list_effective_tags,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: gapic_v1.method.wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def close(self):
|
||||
"""Closes resources associated with the transport.
|
||||
|
||||
.. warning::
|
||||
Only call this method if the transport is NOT shared
|
||||
with other clients - this may cause errors in other clients!
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def operations_client(self):
|
||||
"""Return the client designed to process long-running operations."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def list_tag_bindings(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.ListTagBindingsRequest],
|
||||
Union[
|
||||
tag_bindings.ListTagBindingsResponse,
|
||||
Awaitable[tag_bindings.ListTagBindingsResponse],
|
||||
],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def create_tag_binding(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.CreateTagBindingRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def delete_tag_binding(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.DeleteTagBindingRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def list_effective_tags(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.ListEffectiveTagsRequest],
|
||||
Union[
|
||||
tag_bindings.ListEffectiveTagsResponse,
|
||||
Awaitable[tag_bindings.ListEffectiveTagsResponse],
|
||||
],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[
|
||||
[operations_pb2.GetOperationRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
__all__ = ("TagBindingsTransport",)
|
||||
@@ -0,0 +1,483 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import gapic_v1, grpc_helpers, operations_v1
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import tag_bindings
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, TagBindingsTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
|
||||
def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagBindings",
|
||||
"rpcName": client_call_details.method,
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
|
||||
response = continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = response.result()
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response for {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagBindings",
|
||||
"rpcName": client_call_details.method,
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class TagBindingsGrpcTransport(TagBindingsTransport):
|
||||
"""gRPC backend transport for TagBindings.
|
||||
|
||||
Allow users to create and manage TagBindings between
|
||||
TagValues and different Google Cloud resources throughout the
|
||||
GCP resource hierarchy.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_stubs: Dict[str, Callable]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
||||
ignored if a ``channel`` instance is provided.
|
||||
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
self._operations_client: Optional[operations_v1.OperationsClient] = None
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, grpc.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientInterceptor()
|
||||
self._logged_channel = grpc.intercept_channel(
|
||||
self._grpc_channel, self._interceptor
|
||||
)
|
||||
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> grpc.Channel:
|
||||
"""Create and return a gRPC channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
grpc.Channel: A gRPC channel object.
|
||||
|
||||
Raises:
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
|
||||
return grpc_helpers.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> grpc.Channel:
|
||||
"""Return the channel designed to connect to this service."""
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def operations_client(self) -> operations_v1.OperationsClient:
|
||||
"""Create the client designed to process long-running operations.
|
||||
|
||||
This property caches on the instance; repeated calls return the same
|
||||
client.
|
||||
"""
|
||||
# Quick check: Only create a new client if we do not already have one.
|
||||
if self._operations_client is None:
|
||||
self._operations_client = operations_v1.OperationsClient(
|
||||
self._logged_channel
|
||||
)
|
||||
|
||||
# Return the client from cache.
|
||||
return self._operations_client
|
||||
|
||||
@property
|
||||
def list_tag_bindings(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.ListTagBindingsRequest], tag_bindings.ListTagBindingsResponse
|
||||
]:
|
||||
r"""Return a callable for the list tag bindings method over gRPC.
|
||||
|
||||
Lists the TagBindings for the given Google Cloud resource, as
|
||||
specified with ``parent``.
|
||||
|
||||
NOTE: The ``parent`` field is expected to be a full resource
|
||||
name:
|
||||
https://cloud.google.com/apis/design/resource_names#full_resource_name
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListTagBindingsRequest],
|
||||
~.ListTagBindingsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_tag_bindings" not in self._stubs:
|
||||
self._stubs["list_tag_bindings"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagBindings/ListTagBindings",
|
||||
request_serializer=tag_bindings.ListTagBindingsRequest.serialize,
|
||||
response_deserializer=tag_bindings.ListTagBindingsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_tag_bindings"]
|
||||
|
||||
@property
|
||||
def create_tag_binding(
|
||||
self,
|
||||
) -> Callable[[tag_bindings.CreateTagBindingRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the create tag binding method over gRPC.
|
||||
|
||||
Creates a TagBinding between a TagValue and a Google
|
||||
Cloud resource.
|
||||
|
||||
Returns:
|
||||
Callable[[~.CreateTagBindingRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "create_tag_binding" not in self._stubs:
|
||||
self._stubs["create_tag_binding"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagBindings/CreateTagBinding",
|
||||
request_serializer=tag_bindings.CreateTagBindingRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["create_tag_binding"]
|
||||
|
||||
@property
|
||||
def delete_tag_binding(
|
||||
self,
|
||||
) -> Callable[[tag_bindings.DeleteTagBindingRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the delete tag binding method over gRPC.
|
||||
|
||||
Deletes a TagBinding.
|
||||
|
||||
Returns:
|
||||
Callable[[~.DeleteTagBindingRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "delete_tag_binding" not in self._stubs:
|
||||
self._stubs["delete_tag_binding"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagBindings/DeleteTagBinding",
|
||||
request_serializer=tag_bindings.DeleteTagBindingRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["delete_tag_binding"]
|
||||
|
||||
@property
|
||||
def list_effective_tags(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.ListEffectiveTagsRequest], tag_bindings.ListEffectiveTagsResponse
|
||||
]:
|
||||
r"""Return a callable for the list effective tags method over gRPC.
|
||||
|
||||
Return a list of effective tags for the given Google Cloud
|
||||
resource, as specified in ``parent``.
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListEffectiveTagsRequest],
|
||||
~.ListEffectiveTagsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_effective_tags" not in self._stubs:
|
||||
self._stubs["list_effective_tags"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagBindings/ListEffectiveTags",
|
||||
request_serializer=tag_bindings.ListEffectiveTagsRequest.serialize,
|
||||
response_deserializer=tag_bindings.ListEffectiveTagsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_effective_tags"]
|
||||
|
||||
def close(self):
|
||||
self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc"
|
||||
|
||||
|
||||
__all__ = ("TagBindingsGrpcTransport",)
|
||||
@@ -0,0 +1,540 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import inspect
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, grpc_helpers_async, operations_v1
|
||||
from google.api_core import retry_async as retries
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
from grpc.experimental import aio # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import tag_bindings
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, TagBindingsTransport
|
||||
from .grpc import TagBindingsGrpcTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientAIOInterceptor(
|
||||
grpc.aio.UnaryUnaryClientInterceptor
|
||||
): # pragma: NO COVER
|
||||
async def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagBindings",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
response = await continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = await response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = await response
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response to rpc {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagBindings",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class TagBindingsGrpcAsyncIOTransport(TagBindingsTransport):
|
||||
"""gRPC AsyncIO backend transport for TagBindings.
|
||||
|
||||
Allow users to create and manage TagBindings between
|
||||
TagValues and different Google Cloud resources throughout the
|
||||
GCP resource hierarchy.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_grpc_channel: aio.Channel
|
||||
_stubs: Dict[str, Callable] = {}
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> aio.Channel:
|
||||
"""Create and return a gRPC AsyncIO channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
aio.Channel: A gRPC AsyncIO channel object.
|
||||
"""
|
||||
|
||||
return grpc_helpers_async.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, aio.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientAIOInterceptor()
|
||||
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
|
||||
self._logged_channel = self._grpc_channel
|
||||
self._wrap_with_kind = (
|
||||
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
|
||||
)
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> aio.Channel:
|
||||
"""Create the channel designed to connect to this service.
|
||||
|
||||
This property caches on the instance; repeated calls return
|
||||
the same channel.
|
||||
"""
|
||||
# Return the channel from cache.
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def operations_client(self) -> operations_v1.OperationsAsyncClient:
|
||||
"""Create the client designed to process long-running operations.
|
||||
|
||||
This property caches on the instance; repeated calls return the same
|
||||
client.
|
||||
"""
|
||||
# Quick check: Only create a new client if we do not already have one.
|
||||
if self._operations_client is None:
|
||||
self._operations_client = operations_v1.OperationsAsyncClient(
|
||||
self._logged_channel
|
||||
)
|
||||
|
||||
# Return the client from cache.
|
||||
return self._operations_client
|
||||
|
||||
@property
|
||||
def list_tag_bindings(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.ListTagBindingsRequest],
|
||||
Awaitable[tag_bindings.ListTagBindingsResponse],
|
||||
]:
|
||||
r"""Return a callable for the list tag bindings method over gRPC.
|
||||
|
||||
Lists the TagBindings for the given Google Cloud resource, as
|
||||
specified with ``parent``.
|
||||
|
||||
NOTE: The ``parent`` field is expected to be a full resource
|
||||
name:
|
||||
https://cloud.google.com/apis/design/resource_names#full_resource_name
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListTagBindingsRequest],
|
||||
Awaitable[~.ListTagBindingsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_tag_bindings" not in self._stubs:
|
||||
self._stubs["list_tag_bindings"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagBindings/ListTagBindings",
|
||||
request_serializer=tag_bindings.ListTagBindingsRequest.serialize,
|
||||
response_deserializer=tag_bindings.ListTagBindingsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_tag_bindings"]
|
||||
|
||||
@property
|
||||
def create_tag_binding(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.CreateTagBindingRequest], Awaitable[operations_pb2.Operation]
|
||||
]:
|
||||
r"""Return a callable for the create tag binding method over gRPC.
|
||||
|
||||
Creates a TagBinding between a TagValue and a Google
|
||||
Cloud resource.
|
||||
|
||||
Returns:
|
||||
Callable[[~.CreateTagBindingRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "create_tag_binding" not in self._stubs:
|
||||
self._stubs["create_tag_binding"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagBindings/CreateTagBinding",
|
||||
request_serializer=tag_bindings.CreateTagBindingRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["create_tag_binding"]
|
||||
|
||||
@property
|
||||
def delete_tag_binding(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.DeleteTagBindingRequest], Awaitable[operations_pb2.Operation]
|
||||
]:
|
||||
r"""Return a callable for the delete tag binding method over gRPC.
|
||||
|
||||
Deletes a TagBinding.
|
||||
|
||||
Returns:
|
||||
Callable[[~.DeleteTagBindingRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "delete_tag_binding" not in self._stubs:
|
||||
self._stubs["delete_tag_binding"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagBindings/DeleteTagBinding",
|
||||
request_serializer=tag_bindings.DeleteTagBindingRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["delete_tag_binding"]
|
||||
|
||||
@property
|
||||
def list_effective_tags(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_bindings.ListEffectiveTagsRequest],
|
||||
Awaitable[tag_bindings.ListEffectiveTagsResponse],
|
||||
]:
|
||||
r"""Return a callable for the list effective tags method over gRPC.
|
||||
|
||||
Return a list of effective tags for the given Google Cloud
|
||||
resource, as specified in ``parent``.
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListEffectiveTagsRequest],
|
||||
Awaitable[~.ListEffectiveTagsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_effective_tags" not in self._stubs:
|
||||
self._stubs["list_effective_tags"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagBindings/ListEffectiveTags",
|
||||
request_serializer=tag_bindings.ListEffectiveTagsRequest.serialize,
|
||||
response_deserializer=tag_bindings.ListEffectiveTagsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_effective_tags"]
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
|
||||
self._wrapped_methods = {
|
||||
self.list_tag_bindings: self._wrap_method(
|
||||
self.list_tag_bindings,
|
||||
default_retry=retries.AsyncRetry(
|
||||
initial=0.1,
|
||||
maximum=60.0,
|
||||
multiplier=1.3,
|
||||
predicate=retries.if_exception_type(
|
||||
core_exceptions.ServiceUnavailable,
|
||||
),
|
||||
deadline=60.0,
|
||||
),
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.create_tag_binding: self._wrap_method(
|
||||
self.create_tag_binding,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.delete_tag_binding: self._wrap_method(
|
||||
self.delete_tag_binding,
|
||||
default_timeout=60.0,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.list_effective_tags: self._wrap_method(
|
||||
self.list_effective_tags,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: self._wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def _wrap_method(self, func, *args, **kwargs):
|
||||
if self._wrap_with_kind: # pragma: NO COVER
|
||||
kwargs["kind"] = self.kind
|
||||
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
|
||||
|
||||
def close(self):
|
||||
return self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc_asyncio"
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
|
||||
__all__ = ("TagBindingsGrpcAsyncIOTransport",)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,319 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json # type: ignore
|
||||
import re
|
||||
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
||||
|
||||
from google.api_core import gapic_v1, path_template
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf import json_format
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import tag_bindings
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, TagBindingsTransport
|
||||
|
||||
|
||||
class _BaseTagBindingsRestTransport(TagBindingsTransport):
|
||||
"""Base REST backend transport for TagBindings.
|
||||
|
||||
Note: This class is not meant to be used directly. Use its sync and
|
||||
async sub-classes instead.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends JSON representations of protocol buffers over HTTP/1.1
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[Any] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
url_scheme: str = "https",
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[Any]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you are developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
url_scheme: the protocol scheme for the API endpoint. Normally
|
||||
"https", but for testing or local servers,
|
||||
"http" can be specified.
|
||||
"""
|
||||
# Run the base constructor
|
||||
maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
|
||||
if maybe_url_match is None:
|
||||
raise ValueError(
|
||||
f"Unexpected hostname structure: {host}"
|
||||
) # pragma: NO COVER
|
||||
|
||||
url_match_items = maybe_url_match.groupdict()
|
||||
|
||||
host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host
|
||||
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
class _BaseCreateTagBinding:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "post",
|
||||
"uri": "/v3/tagBindings",
|
||||
"body": "tag_binding",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = tag_bindings.CreateTagBindingRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_request_body_json(transcoded_request):
|
||||
# Jsonify the request body
|
||||
|
||||
body = json_format.MessageToJson(
|
||||
transcoded_request["body"], use_integers_for_enums=True
|
||||
)
|
||||
return body
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseTagBindingsRestTransport._BaseCreateTagBinding._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseDeleteTagBinding:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "delete",
|
||||
"uri": "/v3/{name=tagBindings/**}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = tag_bindings.DeleteTagBindingRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseTagBindingsRestTransport._BaseDeleteTagBinding._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseListEffectiveTags:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
|
||||
"parent": "",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/effectiveTags",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = tag_bindings.ListEffectiveTagsRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseTagBindingsRestTransport._BaseListEffectiveTags._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseListTagBindings:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
__REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
|
||||
"parent": "",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_unset_required_fields(cls, message_dict):
|
||||
return {
|
||||
k: v
|
||||
for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
|
||||
if k not in message_dict
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/tagBindings",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
pb_request = tag_bindings.ListTagBindingsRequest.pb(request)
|
||||
transcoded_request = path_template.transcode(http_options, pb_request)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(
|
||||
json_format.MessageToJson(
|
||||
transcoded_request["query_params"],
|
||||
use_integers_for_enums=True,
|
||||
)
|
||||
)
|
||||
query_params.update(
|
||||
_BaseTagBindingsRestTransport._BaseListTagBindings._get_unset_required_fields(
|
||||
query_params
|
||||
)
|
||||
)
|
||||
|
||||
query_params["$alt"] = "json;enum-encoding=int"
|
||||
return query_params
|
||||
|
||||
class _BaseGetOperation:
|
||||
def __hash__(self): # pragma: NO COVER
|
||||
return NotImplementedError("__hash__ must be implemented.")
|
||||
|
||||
@staticmethod
|
||||
def _get_http_options():
|
||||
http_options: List[Dict[str, str]] = [
|
||||
{
|
||||
"method": "get",
|
||||
"uri": "/v3/{name=operations/**}",
|
||||
},
|
||||
]
|
||||
return http_options
|
||||
|
||||
@staticmethod
|
||||
def _get_transcoded_request(http_options, request):
|
||||
request_kwargs = json_format.MessageToDict(request)
|
||||
transcoded_request = path_template.transcode(http_options, **request_kwargs)
|
||||
return transcoded_request
|
||||
|
||||
@staticmethod
|
||||
def _get_query_params_json(transcoded_request):
|
||||
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
|
||||
return query_params
|
||||
|
||||
|
||||
__all__ = ("_BaseTagBindingsRestTransport",)
|
||||
@@ -0,0 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from .async_client import TagHoldsAsyncClient
|
||||
from .client import TagHoldsClient
|
||||
|
||||
__all__ = (
|
||||
"TagHoldsClient",
|
||||
"TagHoldsAsyncClient",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,760 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from collections import OrderedDict
|
||||
import logging as std_logging
|
||||
import re
|
||||
from typing import (
|
||||
Callable,
|
||||
Dict,
|
||||
Mapping,
|
||||
MutableMapping,
|
||||
MutableSequence,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
Type,
|
||||
Union,
|
||||
)
|
||||
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1
|
||||
from google.api_core import retry_async as retries
|
||||
from google.api_core.client_options import ClientOptions
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.oauth2 import service_account # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3 import gapic_version as package_version
|
||||
|
||||
try:
|
||||
OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
|
||||
except AttributeError: # pragma: NO COVER
|
||||
OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
|
||||
|
||||
from google.api_core import operation # type: ignore
|
||||
from google.api_core import operation_async # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf import empty_pb2 # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.services.tag_holds import pagers
|
||||
from google.cloud.resourcemanager_v3.types import tag_holds
|
||||
|
||||
from .client import TagHoldsClient
|
||||
from .transports.base import DEFAULT_CLIENT_INFO, TagHoldsTransport
|
||||
from .transports.grpc_asyncio import TagHoldsGrpcAsyncIOTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TagHoldsAsyncClient:
|
||||
"""Allow users to create and manage TagHolds for TagValues.
|
||||
TagHolds represent the use of a Tag Value that is not captured
|
||||
by TagBindings but should still block TagValue deletion (such as
|
||||
a reference in a policy condition). This service provides
|
||||
isolated failure domains by cloud location so that TagHolds can
|
||||
be managed in the same location as their usage.
|
||||
"""
|
||||
|
||||
_client: TagHoldsClient
|
||||
|
||||
# Copy defaults from the synchronous client for use here.
|
||||
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
|
||||
DEFAULT_ENDPOINT = TagHoldsClient.DEFAULT_ENDPOINT
|
||||
DEFAULT_MTLS_ENDPOINT = TagHoldsClient.DEFAULT_MTLS_ENDPOINT
|
||||
_DEFAULT_ENDPOINT_TEMPLATE = TagHoldsClient._DEFAULT_ENDPOINT_TEMPLATE
|
||||
_DEFAULT_UNIVERSE = TagHoldsClient._DEFAULT_UNIVERSE
|
||||
|
||||
tag_hold_path = staticmethod(TagHoldsClient.tag_hold_path)
|
||||
parse_tag_hold_path = staticmethod(TagHoldsClient.parse_tag_hold_path)
|
||||
common_billing_account_path = staticmethod(
|
||||
TagHoldsClient.common_billing_account_path
|
||||
)
|
||||
parse_common_billing_account_path = staticmethod(
|
||||
TagHoldsClient.parse_common_billing_account_path
|
||||
)
|
||||
common_folder_path = staticmethod(TagHoldsClient.common_folder_path)
|
||||
parse_common_folder_path = staticmethod(TagHoldsClient.parse_common_folder_path)
|
||||
common_organization_path = staticmethod(TagHoldsClient.common_organization_path)
|
||||
parse_common_organization_path = staticmethod(
|
||||
TagHoldsClient.parse_common_organization_path
|
||||
)
|
||||
common_project_path = staticmethod(TagHoldsClient.common_project_path)
|
||||
parse_common_project_path = staticmethod(TagHoldsClient.parse_common_project_path)
|
||||
common_location_path = staticmethod(TagHoldsClient.common_location_path)
|
||||
parse_common_location_path = staticmethod(TagHoldsClient.parse_common_location_path)
|
||||
|
||||
@classmethod
|
||||
def from_service_account_info(cls, info: dict, *args, **kwargs):
|
||||
"""Creates an instance of this client using the provided credentials
|
||||
info.
|
||||
|
||||
Args:
|
||||
info (dict): The service account private key info.
|
||||
args: Additional arguments to pass to the constructor.
|
||||
kwargs: Additional arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
TagHoldsAsyncClient: The constructed client.
|
||||
"""
|
||||
return TagHoldsClient.from_service_account_info.__func__(TagHoldsAsyncClient, info, *args, **kwargs) # type: ignore
|
||||
|
||||
@classmethod
|
||||
def from_service_account_file(cls, filename: str, *args, **kwargs):
|
||||
"""Creates an instance of this client using the provided credentials
|
||||
file.
|
||||
|
||||
Args:
|
||||
filename (str): The path to the service account private key json
|
||||
file.
|
||||
args: Additional arguments to pass to the constructor.
|
||||
kwargs: Additional arguments to pass to the constructor.
|
||||
|
||||
Returns:
|
||||
TagHoldsAsyncClient: The constructed client.
|
||||
"""
|
||||
return TagHoldsClient.from_service_account_file.__func__(TagHoldsAsyncClient, filename, *args, **kwargs) # type: ignore
|
||||
|
||||
from_service_account_json = from_service_account_file
|
||||
|
||||
@classmethod
|
||||
def get_mtls_endpoint_and_cert_source(
|
||||
cls, client_options: Optional[ClientOptions] = None
|
||||
):
|
||||
"""Return the API endpoint and client cert source for mutual TLS.
|
||||
|
||||
The client cert source is determined in the following order:
|
||||
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
|
||||
client cert source is None.
|
||||
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
|
||||
default client cert source exists, use the default one; otherwise the client cert
|
||||
source is None.
|
||||
|
||||
The API endpoint is determined in the following order:
|
||||
(1) if `client_options.api_endpoint` if provided, use the provided one.
|
||||
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
|
||||
default mTLS endpoint; if the environment variable is "never", use the default API
|
||||
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
|
||||
use the default API endpoint.
|
||||
|
||||
More details can be found at https://google.aip.dev/auth/4114.
|
||||
|
||||
Args:
|
||||
client_options (google.api_core.client_options.ClientOptions): Custom options for the
|
||||
client. Only the `api_endpoint` and `client_cert_source` properties may be used
|
||||
in this method.
|
||||
|
||||
Returns:
|
||||
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
|
||||
client cert source to use.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
|
||||
"""
|
||||
return TagHoldsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
|
||||
|
||||
@property
|
||||
def transport(self) -> TagHoldsTransport:
|
||||
"""Returns the transport used by the client instance.
|
||||
|
||||
Returns:
|
||||
TagHoldsTransport: The transport used by the client instance.
|
||||
"""
|
||||
return self._client.transport
|
||||
|
||||
@property
|
||||
def api_endpoint(self):
|
||||
"""Return the API endpoint used by the client instance.
|
||||
|
||||
Returns:
|
||||
str: The API endpoint used by the client instance.
|
||||
"""
|
||||
return self._client._api_endpoint
|
||||
|
||||
@property
|
||||
def universe_domain(self) -> str:
|
||||
"""Return the universe domain used by the client instance.
|
||||
|
||||
Returns:
|
||||
str: The universe domain used
|
||||
by the client instance.
|
||||
"""
|
||||
return self._client._universe_domain
|
||||
|
||||
get_transport_class = TagHoldsClient.get_transport_class
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
transport: Optional[
|
||||
Union[str, TagHoldsTransport, Callable[..., TagHoldsTransport]]
|
||||
] = "grpc_asyncio",
|
||||
client_options: Optional[ClientOptions] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
) -> None:
|
||||
"""Instantiates the tag holds async client.
|
||||
|
||||
Args:
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
transport (Optional[Union[str,TagHoldsTransport,Callable[..., TagHoldsTransport]]]):
|
||||
The transport to use, or a Callable that constructs and returns a new transport to use.
|
||||
If a Callable is given, it will be called with the same set of initialization
|
||||
arguments as used in the TagHoldsTransport constructor.
|
||||
If set to None, a transport is chosen automatically.
|
||||
client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
|
||||
Custom options for the client.
|
||||
|
||||
1. The ``api_endpoint`` property can be used to override the
|
||||
default endpoint provided by the client when ``transport`` is
|
||||
not explicitly provided. Only if this property is not set and
|
||||
``transport`` was not explicitly provided, the endpoint is
|
||||
determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
|
||||
variable, which have one of the following values:
|
||||
"always" (always use the default mTLS endpoint), "never" (always
|
||||
use the default regular endpoint) and "auto" (auto-switch to the
|
||||
default mTLS endpoint if client certificate is present; this is
|
||||
the default value).
|
||||
|
||||
2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
|
||||
is "true", then the ``client_cert_source`` property can be used
|
||||
to provide a client certificate for mTLS transport. If
|
||||
not provided, the default SSL client certificate will be used if
|
||||
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
|
||||
set, no client certificate will be used.
|
||||
|
||||
3. The ``universe_domain`` property can be used to override the
|
||||
default "googleapis.com" universe. Note that ``api_endpoint``
|
||||
property still takes precedence; and ``universe_domain`` is
|
||||
currently not supported for mTLS.
|
||||
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
"""
|
||||
self._client = TagHoldsClient(
|
||||
credentials=credentials,
|
||||
transport=transport,
|
||||
client_options=client_options,
|
||||
client_info=client_info,
|
||||
)
|
||||
|
||||
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
): # pragma: NO COVER
|
||||
_LOGGER.debug(
|
||||
"Created client `google.cloud.resourcemanager_v3.TagHoldsAsyncClient`.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagHolds",
|
||||
"universeDomain": getattr(
|
||||
self._client._transport._credentials, "universe_domain", ""
|
||||
),
|
||||
"credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
|
||||
"credentialsInfo": getattr(
|
||||
self.transport._credentials, "get_cred_info", lambda: None
|
||||
)(),
|
||||
}
|
||||
if hasattr(self._client._transport, "_credentials")
|
||||
else {
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagHolds",
|
||||
"credentialsType": None,
|
||||
},
|
||||
)
|
||||
|
||||
async def create_tag_hold(
|
||||
self,
|
||||
request: Optional[Union[tag_holds.CreateTagHoldRequest, dict]] = None,
|
||||
*,
|
||||
parent: Optional[str] = None,
|
||||
tag_hold: Optional[tag_holds.TagHold] = None,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> operation_async.AsyncOperation:
|
||||
r"""Creates a TagHold. Returns ALREADY_EXISTS if a TagHold with the
|
||||
same resource and origin exists under the same TagValue.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# This snippet has been automatically generated and should be regarded as a
|
||||
# code template only.
|
||||
# It will require modifications to work:
|
||||
# - It may require correct/in-range values for request initialization.
|
||||
# - It may require specifying regional endpoints when creating the service
|
||||
# client as shown in:
|
||||
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
||||
from google.cloud import resourcemanager_v3
|
||||
|
||||
async def sample_create_tag_hold():
|
||||
# Create a client
|
||||
client = resourcemanager_v3.TagHoldsAsyncClient()
|
||||
|
||||
# Initialize request argument(s)
|
||||
tag_hold = resourcemanager_v3.TagHold()
|
||||
tag_hold.holder = "holder_value"
|
||||
|
||||
request = resourcemanager_v3.CreateTagHoldRequest(
|
||||
parent="parent_value",
|
||||
tag_hold=tag_hold,
|
||||
)
|
||||
|
||||
# Make the request
|
||||
operation = client.create_tag_hold(request=request)
|
||||
|
||||
print("Waiting for operation to complete...")
|
||||
|
||||
response = (await operation).result()
|
||||
|
||||
# Handle the response
|
||||
print(response)
|
||||
|
||||
Args:
|
||||
request (Optional[Union[google.cloud.resourcemanager_v3.types.CreateTagHoldRequest, dict]]):
|
||||
The request object. The request message to create a
|
||||
TagHold.
|
||||
parent (:class:`str`):
|
||||
Required. The resource name of the TagHold's parent
|
||||
TagValue. Must be of the form:
|
||||
``tagValues/{tag-value-id}``.
|
||||
|
||||
This corresponds to the ``parent`` field
|
||||
on the ``request`` instance; if ``request`` is provided, this
|
||||
should not be set.
|
||||
tag_hold (:class:`google.cloud.resourcemanager_v3.types.TagHold`):
|
||||
Required. The TagHold to be created.
|
||||
This corresponds to the ``tag_hold`` field
|
||||
on the ``request`` instance; if ``request`` is provided, this
|
||||
should not be set.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
||||
should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
|
||||
Returns:
|
||||
google.api_core.operation_async.AsyncOperation:
|
||||
An object representing a long-running operation.
|
||||
|
||||
The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.TagHold` A TagHold represents the use of a TagValue that is not captured by
|
||||
TagBindings. If a TagValue has any TagHolds, deletion
|
||||
will be blocked. This resource is intended to be
|
||||
created in the same cloud location as the holder.
|
||||
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# - Quick check: If we got a request object, we should *not* have
|
||||
# gotten any keyword arguments that map to the request.
|
||||
flattened_params = [parent, tag_hold]
|
||||
has_flattened_params = (
|
||||
len([param for param in flattened_params if param is not None]) > 0
|
||||
)
|
||||
if request is not None and has_flattened_params:
|
||||
raise ValueError(
|
||||
"If the `request` argument is set, then none of "
|
||||
"the individual field arguments should be set."
|
||||
)
|
||||
|
||||
# - Use the request object if provided (there's no risk of modifying the input as
|
||||
# there are no flattened fields), or create one.
|
||||
if not isinstance(request, tag_holds.CreateTagHoldRequest):
|
||||
request = tag_holds.CreateTagHoldRequest(request)
|
||||
|
||||
# If we have keyword arguments corresponding to fields on the
|
||||
# request, apply these.
|
||||
if parent is not None:
|
||||
request.parent = parent
|
||||
if tag_hold is not None:
|
||||
request.tag_hold = tag_hold
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self._client._transport._wrapped_methods[
|
||||
self._client._transport.create_tag_hold
|
||||
]
|
||||
|
||||
# Certain fields should be provided within the metadata header;
|
||||
# add these here.
|
||||
metadata = tuple(metadata) + (
|
||||
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
|
||||
)
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Wrap the response in an operation future.
|
||||
response = operation_async.from_gapic(
|
||||
response,
|
||||
self._client._transport.operations_client,
|
||||
tag_holds.TagHold,
|
||||
metadata_type=tag_holds.CreateTagHoldMetadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def delete_tag_hold(
|
||||
self,
|
||||
request: Optional[Union[tag_holds.DeleteTagHoldRequest, dict]] = None,
|
||||
*,
|
||||
name: Optional[str] = None,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> operation_async.AsyncOperation:
|
||||
r"""Deletes a TagHold.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# This snippet has been automatically generated and should be regarded as a
|
||||
# code template only.
|
||||
# It will require modifications to work:
|
||||
# - It may require correct/in-range values for request initialization.
|
||||
# - It may require specifying regional endpoints when creating the service
|
||||
# client as shown in:
|
||||
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
||||
from google.cloud import resourcemanager_v3
|
||||
|
||||
async def sample_delete_tag_hold():
|
||||
# Create a client
|
||||
client = resourcemanager_v3.TagHoldsAsyncClient()
|
||||
|
||||
# Initialize request argument(s)
|
||||
request = resourcemanager_v3.DeleteTagHoldRequest(
|
||||
name="name_value",
|
||||
)
|
||||
|
||||
# Make the request
|
||||
operation = client.delete_tag_hold(request=request)
|
||||
|
||||
print("Waiting for operation to complete...")
|
||||
|
||||
response = (await operation).result()
|
||||
|
||||
# Handle the response
|
||||
print(response)
|
||||
|
||||
Args:
|
||||
request (Optional[Union[google.cloud.resourcemanager_v3.types.DeleteTagHoldRequest, dict]]):
|
||||
The request object. The request message to delete a
|
||||
TagHold.
|
||||
name (:class:`str`):
|
||||
Required. The resource name of the TagHold to delete.
|
||||
Must be of the form:
|
||||
``tagValues/{tag-value-id}/tagHolds/{tag-hold-id}``.
|
||||
|
||||
This corresponds to the ``name`` field
|
||||
on the ``request`` instance; if ``request`` is provided, this
|
||||
should not be set.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
||||
should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
|
||||
Returns:
|
||||
google.api_core.operation_async.AsyncOperation:
|
||||
An object representing a long-running operation.
|
||||
|
||||
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
|
||||
empty messages in your APIs. A typical example is to
|
||||
use it as the request or the response type of an API
|
||||
method. For instance:
|
||||
|
||||
service Foo {
|
||||
rpc Bar(google.protobuf.Empty) returns
|
||||
(google.protobuf.Empty);
|
||||
|
||||
}
|
||||
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# - Quick check: If we got a request object, we should *not* have
|
||||
# gotten any keyword arguments that map to the request.
|
||||
flattened_params = [name]
|
||||
has_flattened_params = (
|
||||
len([param for param in flattened_params if param is not None]) > 0
|
||||
)
|
||||
if request is not None and has_flattened_params:
|
||||
raise ValueError(
|
||||
"If the `request` argument is set, then none of "
|
||||
"the individual field arguments should be set."
|
||||
)
|
||||
|
||||
# - Use the request object if provided (there's no risk of modifying the input as
|
||||
# there are no flattened fields), or create one.
|
||||
if not isinstance(request, tag_holds.DeleteTagHoldRequest):
|
||||
request = tag_holds.DeleteTagHoldRequest(request)
|
||||
|
||||
# If we have keyword arguments corresponding to fields on the
|
||||
# request, apply these.
|
||||
if name is not None:
|
||||
request.name = name
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self._client._transport._wrapped_methods[
|
||||
self._client._transport.delete_tag_hold
|
||||
]
|
||||
|
||||
# Certain fields should be provided within the metadata header;
|
||||
# add these here.
|
||||
metadata = tuple(metadata) + (
|
||||
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
||||
)
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Wrap the response in an operation future.
|
||||
response = operation_async.from_gapic(
|
||||
response,
|
||||
self._client._transport.operations_client,
|
||||
empty_pb2.Empty,
|
||||
metadata_type=tag_holds.DeleteTagHoldMetadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def list_tag_holds(
|
||||
self,
|
||||
request: Optional[Union[tag_holds.ListTagHoldsRequest, dict]] = None,
|
||||
*,
|
||||
parent: Optional[str] = None,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> pagers.ListTagHoldsAsyncPager:
|
||||
r"""Lists TagHolds under a TagValue.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# This snippet has been automatically generated and should be regarded as a
|
||||
# code template only.
|
||||
# It will require modifications to work:
|
||||
# - It may require correct/in-range values for request initialization.
|
||||
# - It may require specifying regional endpoints when creating the service
|
||||
# client as shown in:
|
||||
# https://googleapis.dev/python/google-api-core/latest/client_options.html
|
||||
from google.cloud import resourcemanager_v3
|
||||
|
||||
async def sample_list_tag_holds():
|
||||
# Create a client
|
||||
client = resourcemanager_v3.TagHoldsAsyncClient()
|
||||
|
||||
# Initialize request argument(s)
|
||||
request = resourcemanager_v3.ListTagHoldsRequest(
|
||||
parent="parent_value",
|
||||
)
|
||||
|
||||
# Make the request
|
||||
page_result = client.list_tag_holds(request=request)
|
||||
|
||||
# Handle the response
|
||||
async for response in page_result:
|
||||
print(response)
|
||||
|
||||
Args:
|
||||
request (Optional[Union[google.cloud.resourcemanager_v3.types.ListTagHoldsRequest, dict]]):
|
||||
The request object. The request message for listing the
|
||||
TagHolds under a TagValue.
|
||||
parent (:class:`str`):
|
||||
Required. The resource name of the parent TagValue. Must
|
||||
be of the form: ``tagValues/{tag-value-id}``.
|
||||
|
||||
This corresponds to the ``parent`` field
|
||||
on the ``request`` instance; if ``request`` is provided, this
|
||||
should not be set.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
|
||||
should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
|
||||
Returns:
|
||||
google.cloud.resourcemanager_v3.services.tag_holds.pagers.ListTagHoldsAsyncPager:
|
||||
The ListTagHolds response.
|
||||
|
||||
Iterating over this object will yield
|
||||
results and resolve additional pages
|
||||
automatically.
|
||||
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# - Quick check: If we got a request object, we should *not* have
|
||||
# gotten any keyword arguments that map to the request.
|
||||
flattened_params = [parent]
|
||||
has_flattened_params = (
|
||||
len([param for param in flattened_params if param is not None]) > 0
|
||||
)
|
||||
if request is not None and has_flattened_params:
|
||||
raise ValueError(
|
||||
"If the `request` argument is set, then none of "
|
||||
"the individual field arguments should be set."
|
||||
)
|
||||
|
||||
# - Use the request object if provided (there's no risk of modifying the input as
|
||||
# there are no flattened fields), or create one.
|
||||
if not isinstance(request, tag_holds.ListTagHoldsRequest):
|
||||
request = tag_holds.ListTagHoldsRequest(request)
|
||||
|
||||
# If we have keyword arguments corresponding to fields on the
|
||||
# request, apply these.
|
||||
if parent is not None:
|
||||
request.parent = parent
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self._client._transport._wrapped_methods[
|
||||
self._client._transport.list_tag_holds
|
||||
]
|
||||
|
||||
# Certain fields should be provided within the metadata header;
|
||||
# add these here.
|
||||
metadata = tuple(metadata) + (
|
||||
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
|
||||
)
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# This method is paged; wrap the response in a pager, which provides
|
||||
# an `__aiter__` convenience method.
|
||||
response = pagers.ListTagHoldsAsyncPager(
|
||||
method=rpc,
|
||||
request=request,
|
||||
response=response,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def get_operation(
|
||||
self,
|
||||
request: Optional[operations_pb2.GetOperationRequest] = None,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
|
||||
) -> operations_pb2.Operation:
|
||||
r"""Gets the latest state of a long-running operation.
|
||||
|
||||
Args:
|
||||
request (:class:`~.operations_pb2.GetOperationRequest`):
|
||||
The request object. Request message for
|
||||
`GetOperation` method.
|
||||
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
Returns:
|
||||
~.operations_pb2.Operation:
|
||||
An ``Operation`` object.
|
||||
"""
|
||||
# Create or coerce a protobuf request object.
|
||||
# The request isn't a proto-plus wrapped type,
|
||||
# so it must be constructed via keyword expansion.
|
||||
if isinstance(request, dict):
|
||||
request = operations_pb2.GetOperationRequest(**request)
|
||||
|
||||
# Wrap the RPC method; this adds retry and timeout information,
|
||||
# and friendly error handling.
|
||||
rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
|
||||
|
||||
# Certain fields should be provided within the metadata header;
|
||||
# add these here.
|
||||
metadata = tuple(metadata) + (
|
||||
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
|
||||
)
|
||||
|
||||
# Validate the universe domain.
|
||||
self._client._validate_universe_domain()
|
||||
|
||||
# Send the request.
|
||||
response = await rpc(
|
||||
request,
|
||||
retry=retry,
|
||||
timeout=timeout,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
# Done; return the response.
|
||||
return response
|
||||
|
||||
async def __aenter__(self) -> "TagHoldsAsyncClient":
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
await self.transport.close()
|
||||
|
||||
|
||||
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
||||
gapic_version=package_version.__version__
|
||||
)
|
||||
|
||||
|
||||
__all__ = ("TagHoldsAsyncClient",)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,197 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Iterator,
|
||||
Optional,
|
||||
Sequence,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
|
||||
from google.api_core import gapic_v1
|
||||
from google.api_core import retry as retries
|
||||
from google.api_core import retry_async as retries_async
|
||||
|
||||
try:
|
||||
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
|
||||
OptionalAsyncRetry = Union[
|
||||
retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
|
||||
]
|
||||
except AttributeError: # pragma: NO COVER
|
||||
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
|
||||
OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import tag_holds
|
||||
|
||||
|
||||
class ListTagHoldsPager:
|
||||
"""A pager for iterating through ``list_tag_holds`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListTagHoldsResponse` object, and
|
||||
provides an ``__iter__`` method to iterate through its
|
||||
``tag_holds`` field.
|
||||
|
||||
If there are more pages, the ``__iter__`` method will make additional
|
||||
``ListTagHolds`` requests and continue to iterate
|
||||
through the ``tag_holds`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagHoldsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., tag_holds.ListTagHoldsResponse],
|
||||
request: tag_holds.ListTagHoldsRequest,
|
||||
response: tag_holds.ListTagHoldsResponse,
|
||||
*,
|
||||
retry: OptionalRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiate the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListTagHoldsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListTagHoldsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.Retry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = tag_holds.ListTagHoldsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
def pages(self) -> Iterator[tag_holds.ListTagHoldsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __iter__(self) -> Iterator[tag_holds.TagHold]:
|
||||
for page in self.pages:
|
||||
yield from page.tag_holds
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
|
||||
|
||||
class ListTagHoldsAsyncPager:
|
||||
"""A pager for iterating through ``list_tag_holds`` requests.
|
||||
|
||||
This class thinly wraps an initial
|
||||
:class:`google.cloud.resourcemanager_v3.types.ListTagHoldsResponse` object, and
|
||||
provides an ``__aiter__`` method to iterate through its
|
||||
``tag_holds`` field.
|
||||
|
||||
If there are more pages, the ``__aiter__`` method will make additional
|
||||
``ListTagHolds`` requests and continue to iterate
|
||||
through the ``tag_holds`` field on the
|
||||
corresponding responses.
|
||||
|
||||
All the usual :class:`google.cloud.resourcemanager_v3.types.ListTagHoldsResponse`
|
||||
attributes are available on the pager. If multiple requests are made, only
|
||||
the most recent response is retained, and thus used for attribute lookup.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
method: Callable[..., Awaitable[tag_holds.ListTagHoldsResponse]],
|
||||
request: tag_holds.ListTagHoldsRequest,
|
||||
response: tag_holds.ListTagHoldsResponse,
|
||||
*,
|
||||
retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT,
|
||||
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
|
||||
metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()
|
||||
):
|
||||
"""Instantiates the pager.
|
||||
|
||||
Args:
|
||||
method (Callable): The method that was originally called, and
|
||||
which instantiated this pager.
|
||||
request (google.cloud.resourcemanager_v3.types.ListTagHoldsRequest):
|
||||
The initial request object.
|
||||
response (google.cloud.resourcemanager_v3.types.ListTagHoldsResponse):
|
||||
The initial response object.
|
||||
retry (google.api_core.retry.AsyncRetry): Designation of what errors,
|
||||
if any, should be retried.
|
||||
timeout (float): The timeout for this request.
|
||||
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
|
||||
sent along with the request as metadata. Normally, each value must be of type `str`,
|
||||
but for metadata keys ending with the suffix `-bin`, the corresponding values must
|
||||
be of type `bytes`.
|
||||
"""
|
||||
self._method = method
|
||||
self._request = tag_holds.ListTagHoldsRequest(request)
|
||||
self._response = response
|
||||
self._retry = retry
|
||||
self._timeout = timeout
|
||||
self._metadata = metadata
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(self._response, name)
|
||||
|
||||
@property
|
||||
async def pages(self) -> AsyncIterator[tag_holds.ListTagHoldsResponse]:
|
||||
yield self._response
|
||||
while self._response.next_page_token:
|
||||
self._request.page_token = self._response.next_page_token
|
||||
self._response = await self._method(
|
||||
self._request,
|
||||
retry=self._retry,
|
||||
timeout=self._timeout,
|
||||
metadata=self._metadata,
|
||||
)
|
||||
yield self._response
|
||||
|
||||
def __aiter__(self) -> AsyncIterator[tag_holds.TagHold]:
|
||||
async def async_generator():
|
||||
async for page in self.pages:
|
||||
for response in page.tag_holds:
|
||||
yield response
|
||||
|
||||
return async_generator()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
from collections import OrderedDict
|
||||
from typing import Dict, Type
|
||||
|
||||
from .base import TagHoldsTransport
|
||||
from .grpc import TagHoldsGrpcTransport
|
||||
from .grpc_asyncio import TagHoldsGrpcAsyncIOTransport
|
||||
from .rest import TagHoldsRestInterceptor, TagHoldsRestTransport
|
||||
|
||||
# Compile a registry of transports.
|
||||
_transport_registry = OrderedDict() # type: Dict[str, Type[TagHoldsTransport]]
|
||||
_transport_registry["grpc"] = TagHoldsGrpcTransport
|
||||
_transport_registry["grpc_asyncio"] = TagHoldsGrpcAsyncIOTransport
|
||||
_transport_registry["rest"] = TagHoldsRestTransport
|
||||
|
||||
__all__ = (
|
||||
"TagHoldsTransport",
|
||||
"TagHoldsGrpcTransport",
|
||||
"TagHoldsGrpcAsyncIOTransport",
|
||||
"TagHoldsRestTransport",
|
||||
"TagHoldsRestInterceptor",
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,214 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import abc
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
|
||||
|
||||
import google.api_core
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, operations_v1
|
||||
from google.api_core import retry as retries
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.oauth2 import service_account # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3 import gapic_version as package_version
|
||||
from google.cloud.resourcemanager_v3.types import tag_holds
|
||||
|
||||
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
|
||||
gapic_version=package_version.__version__
|
||||
)
|
||||
|
||||
|
||||
class TagHoldsTransport(abc.ABC):
|
||||
"""Abstract transport class for TagHolds."""
|
||||
|
||||
AUTH_SCOPES = (
|
||||
"https://www.googleapis.com/auth/cloud-platform",
|
||||
"https://www.googleapis.com/auth/cloud-platform.read-only",
|
||||
)
|
||||
|
||||
DEFAULT_HOST: str = "cloudresourcemanager.googleapis.com"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = DEFAULT_HOST,
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A list of scopes.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
"""
|
||||
|
||||
scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}
|
||||
|
||||
# Save the scopes.
|
||||
self._scopes = scopes
|
||||
if not hasattr(self, "_ignore_credentials"):
|
||||
self._ignore_credentials: bool = False
|
||||
|
||||
# If no credentials are provided, then determine the appropriate
|
||||
# defaults.
|
||||
if credentials and credentials_file:
|
||||
raise core_exceptions.DuplicateCredentialArgs(
|
||||
"'credentials_file' and 'credentials' are mutually exclusive"
|
||||
)
|
||||
|
||||
if credentials_file is not None:
|
||||
credentials, _ = google.auth.load_credentials_from_file(
|
||||
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
elif credentials is None and not self._ignore_credentials:
|
||||
credentials, _ = google.auth.default(
|
||||
**scopes_kwargs, quota_project_id=quota_project_id
|
||||
)
|
||||
# Don't apply audience if the credentials file passed from user.
|
||||
if hasattr(credentials, "with_gdch_audience"):
|
||||
credentials = credentials.with_gdch_audience(
|
||||
api_audience if api_audience else host
|
||||
)
|
||||
|
||||
# If the credentials are service account credentials, then always try to use self signed JWT.
|
||||
if (
|
||||
always_use_jwt_access
|
||||
and isinstance(credentials, service_account.Credentials)
|
||||
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
|
||||
):
|
||||
credentials = credentials.with_always_use_jwt_access(True)
|
||||
|
||||
# Save the credentials.
|
||||
self._credentials = credentials
|
||||
|
||||
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
|
||||
if ":" not in host:
|
||||
host += ":443"
|
||||
self._host = host
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
return self._host
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
# Precompute the wrapped methods.
|
||||
self._wrapped_methods = {
|
||||
self.create_tag_hold: gapic_v1.method.wrap_method(
|
||||
self.create_tag_hold,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.delete_tag_hold: gapic_v1.method.wrap_method(
|
||||
self.delete_tag_hold,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.list_tag_holds: gapic_v1.method.wrap_method(
|
||||
self.list_tag_holds,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: gapic_v1.method.wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def close(self):
|
||||
"""Closes resources associated with the transport.
|
||||
|
||||
.. warning::
|
||||
Only call this method if the transport is NOT shared
|
||||
with other clients - this may cause errors in other clients!
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def operations_client(self):
|
||||
"""Return the client designed to process long-running operations."""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def create_tag_hold(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_holds.CreateTagHoldRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def delete_tag_hold(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_holds.DeleteTagHoldRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def list_tag_holds(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_holds.ListTagHoldsRequest],
|
||||
Union[
|
||||
tag_holds.ListTagHoldsResponse, Awaitable[tag_holds.ListTagHoldsResponse]
|
||||
],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[
|
||||
[operations_pb2.GetOperationRequest],
|
||||
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
|
||||
]:
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
__all__ = ("TagHoldsTransport",)
|
||||
@@ -0,0 +1,450 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import gapic_v1, grpc_helpers, operations_v1
|
||||
import google.auth # type: ignore
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import tag_holds
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, TagHoldsTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
|
||||
def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagHolds",
|
||||
"rpcName": client_call_details.method,
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
|
||||
response = continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = response.result()
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response for {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagHolds",
|
||||
"rpcName": client_call_details.method,
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class TagHoldsGrpcTransport(TagHoldsTransport):
|
||||
"""gRPC backend transport for TagHolds.
|
||||
|
||||
Allow users to create and manage TagHolds for TagValues.
|
||||
TagHolds represent the use of a Tag Value that is not captured
|
||||
by TagBindings but should still block TagValue deletion (such as
|
||||
a reference in a policy condition). This service provides
|
||||
isolated failure domains by cloud location so that TagHolds can
|
||||
be managed in the same location as their usage.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_stubs: Dict[str, Callable]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional(Sequence[str])): A list of scopes. This argument is
|
||||
ignored if a ``channel`` instance is provided.
|
||||
channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
self._operations_client: Optional[operations_v1.OperationsClient] = None
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, grpc.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientInterceptor()
|
||||
self._logged_channel = grpc.intercept_channel(
|
||||
self._grpc_channel, self._interceptor
|
||||
)
|
||||
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> grpc.Channel:
|
||||
"""Create and return a gRPC channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is mutually exclusive with credentials.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
grpc.Channel: A gRPC channel object.
|
||||
|
||||
Raises:
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
|
||||
return grpc_helpers.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> grpc.Channel:
|
||||
"""Return the channel designed to connect to this service."""
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def operations_client(self) -> operations_v1.OperationsClient:
|
||||
"""Create the client designed to process long-running operations.
|
||||
|
||||
This property caches on the instance; repeated calls return the same
|
||||
client.
|
||||
"""
|
||||
# Quick check: Only create a new client if we do not already have one.
|
||||
if self._operations_client is None:
|
||||
self._operations_client = operations_v1.OperationsClient(
|
||||
self._logged_channel
|
||||
)
|
||||
|
||||
# Return the client from cache.
|
||||
return self._operations_client
|
||||
|
||||
@property
|
||||
def create_tag_hold(
|
||||
self,
|
||||
) -> Callable[[tag_holds.CreateTagHoldRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the create tag hold method over gRPC.
|
||||
|
||||
Creates a TagHold. Returns ALREADY_EXISTS if a TagHold with the
|
||||
same resource and origin exists under the same TagValue.
|
||||
|
||||
Returns:
|
||||
Callable[[~.CreateTagHoldRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "create_tag_hold" not in self._stubs:
|
||||
self._stubs["create_tag_hold"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagHolds/CreateTagHold",
|
||||
request_serializer=tag_holds.CreateTagHoldRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["create_tag_hold"]
|
||||
|
||||
@property
|
||||
def delete_tag_hold(
|
||||
self,
|
||||
) -> Callable[[tag_holds.DeleteTagHoldRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the delete tag hold method over gRPC.
|
||||
|
||||
Deletes a TagHold.
|
||||
|
||||
Returns:
|
||||
Callable[[~.DeleteTagHoldRequest],
|
||||
~.Operation]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "delete_tag_hold" not in self._stubs:
|
||||
self._stubs["delete_tag_hold"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagHolds/DeleteTagHold",
|
||||
request_serializer=tag_holds.DeleteTagHoldRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["delete_tag_hold"]
|
||||
|
||||
@property
|
||||
def list_tag_holds(
|
||||
self,
|
||||
) -> Callable[[tag_holds.ListTagHoldsRequest], tag_holds.ListTagHoldsResponse]:
|
||||
r"""Return a callable for the list tag holds method over gRPC.
|
||||
|
||||
Lists TagHolds under a TagValue.
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListTagHoldsRequest],
|
||||
~.ListTagHoldsResponse]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_tag_holds" not in self._stubs:
|
||||
self._stubs["list_tag_holds"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagHolds/ListTagHolds",
|
||||
request_serializer=tag_holds.ListTagHoldsRequest.serialize,
|
||||
response_deserializer=tag_holds.ListTagHoldsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_tag_holds"]
|
||||
|
||||
def close(self):
|
||||
self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc"
|
||||
|
||||
|
||||
__all__ = ("TagHoldsGrpcTransport",)
|
||||
@@ -0,0 +1,493 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright 2024 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
import inspect
|
||||
import json
|
||||
import logging as std_logging
|
||||
import pickle
|
||||
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
|
||||
import warnings
|
||||
|
||||
from google.api_core import exceptions as core_exceptions
|
||||
from google.api_core import gapic_v1, grpc_helpers_async, operations_v1
|
||||
from google.api_core import retry_async as retries
|
||||
from google.auth import credentials as ga_credentials # type: ignore
|
||||
from google.auth.transport.grpc import SslCredentials # type: ignore
|
||||
from google.longrunning import operations_pb2 # type: ignore
|
||||
from google.protobuf.json_format import MessageToJson
|
||||
import google.protobuf.message
|
||||
import grpc # type: ignore
|
||||
from grpc.experimental import aio # type: ignore
|
||||
import proto # type: ignore
|
||||
|
||||
from google.cloud.resourcemanager_v3.types import tag_holds
|
||||
|
||||
from .base import DEFAULT_CLIENT_INFO, TagHoldsTransport
|
||||
from .grpc import TagHoldsGrpcTransport
|
||||
|
||||
try:
|
||||
from google.api_core import client_logging # type: ignore
|
||||
|
||||
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
|
||||
except ImportError: # pragma: NO COVER
|
||||
CLIENT_LOGGING_SUPPORTED = False
|
||||
|
||||
_LOGGER = std_logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _LoggingClientAIOInterceptor(
|
||||
grpc.aio.UnaryUnaryClientInterceptor
|
||||
): # pragma: NO COVER
|
||||
async def intercept_unary_unary(self, continuation, client_call_details, request):
|
||||
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
|
||||
std_logging.DEBUG
|
||||
)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
request_metadata = client_call_details.metadata
|
||||
if isinstance(request, proto.Message):
|
||||
request_payload = type(request).to_json(request)
|
||||
elif isinstance(request, google.protobuf.message.Message):
|
||||
request_payload = MessageToJson(request)
|
||||
else:
|
||||
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
|
||||
|
||||
request_metadata = {
|
||||
key: value.decode("utf-8") if isinstance(value, bytes) else value
|
||||
for key, value in request_metadata
|
||||
}
|
||||
grpc_request = {
|
||||
"payload": request_payload,
|
||||
"requestMethod": "grpc",
|
||||
"metadata": dict(request_metadata),
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Sending request for {client_call_details.method}",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagHolds",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"request": grpc_request,
|
||||
"metadata": grpc_request["metadata"],
|
||||
},
|
||||
)
|
||||
response = await continuation(client_call_details, request)
|
||||
if logging_enabled: # pragma: NO COVER
|
||||
response_metadata = await response.trailing_metadata()
|
||||
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
|
||||
metadata = (
|
||||
dict([(k, str(v)) for k, v in response_metadata])
|
||||
if response_metadata
|
||||
else None
|
||||
)
|
||||
result = await response
|
||||
if isinstance(result, proto.Message):
|
||||
response_payload = type(result).to_json(result)
|
||||
elif isinstance(result, google.protobuf.message.Message):
|
||||
response_payload = MessageToJson(result)
|
||||
else:
|
||||
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
|
||||
grpc_response = {
|
||||
"payload": response_payload,
|
||||
"metadata": metadata,
|
||||
"status": "OK",
|
||||
}
|
||||
_LOGGER.debug(
|
||||
f"Received response to rpc {client_call_details.method}.",
|
||||
extra={
|
||||
"serviceName": "google.cloud.resourcemanager.v3.TagHolds",
|
||||
"rpcName": str(client_call_details.method),
|
||||
"response": grpc_response,
|
||||
"metadata": grpc_response["metadata"],
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
class TagHoldsGrpcAsyncIOTransport(TagHoldsTransport):
|
||||
"""gRPC AsyncIO backend transport for TagHolds.
|
||||
|
||||
Allow users to create and manage TagHolds for TagValues.
|
||||
TagHolds represent the use of a Tag Value that is not captured
|
||||
by TagBindings but should still block TagValue deletion (such as
|
||||
a reference in a policy condition). This service provides
|
||||
isolated failure domains by cloud location so that TagHolds can
|
||||
be managed in the same location as their usage.
|
||||
|
||||
This class defines the same methods as the primary client, so the
|
||||
primary client can load the underlying transport implementation
|
||||
and call it.
|
||||
|
||||
It sends protocol buffers over the wire using gRPC (which is built on
|
||||
top of HTTP/2); the ``grpcio`` package must be installed.
|
||||
"""
|
||||
|
||||
_grpc_channel: aio.Channel
|
||||
_stubs: Dict[str, Callable] = {}
|
||||
|
||||
@classmethod
|
||||
def create_channel(
|
||||
cls,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
**kwargs,
|
||||
) -> aio.Channel:
|
||||
"""Create and return a gRPC AsyncIO channel object.
|
||||
Args:
|
||||
host (Optional[str]): The host for the channel to use.
|
||||
credentials (Optional[~.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify this application to the service. If
|
||||
none are specified, the client will attempt to ascertain
|
||||
the credentials from the environment.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
kwargs (Optional[dict]): Keyword arguments, which are passed to the
|
||||
channel creation.
|
||||
Returns:
|
||||
aio.Channel: A gRPC AsyncIO channel object.
|
||||
"""
|
||||
|
||||
return grpc_helpers_async.create_channel(
|
||||
host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
quota_project_id=quota_project_id,
|
||||
default_scopes=cls.AUTH_SCOPES,
|
||||
scopes=scopes,
|
||||
default_host=cls.DEFAULT_HOST,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host: str = "cloudresourcemanager.googleapis.com",
|
||||
credentials: Optional[ga_credentials.Credentials] = None,
|
||||
credentials_file: Optional[str] = None,
|
||||
scopes: Optional[Sequence[str]] = None,
|
||||
channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None,
|
||||
api_mtls_endpoint: Optional[str] = None,
|
||||
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
|
||||
client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
||||
quota_project_id: Optional[str] = None,
|
||||
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
|
||||
always_use_jwt_access: Optional[bool] = False,
|
||||
api_audience: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Instantiate the transport.
|
||||
|
||||
Args:
|
||||
host (Optional[str]):
|
||||
The hostname to connect to (default: 'cloudresourcemanager.googleapis.com').
|
||||
credentials (Optional[google.auth.credentials.Credentials]): The
|
||||
authorization credentials to attach to requests. These
|
||||
credentials identify the application to the service; if none
|
||||
are specified, the client will attempt to ascertain the
|
||||
credentials from the environment.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
credentials_file (Optional[str]): A file with credentials that can
|
||||
be loaded with :func:`google.auth.load_credentials_from_file`.
|
||||
This argument is ignored if a ``channel`` instance is provided.
|
||||
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
|
||||
service. These are only used when credentials are not specified and
|
||||
are passed to :func:`google.auth.default`.
|
||||
channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]):
|
||||
A ``Channel`` instance through which to make calls, or a Callable
|
||||
that constructs and returns one. If set to None, ``self.create_channel``
|
||||
is used to create the channel. If a Callable is given, it will be called
|
||||
with the same arguments as used in ``self.create_channel``.
|
||||
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
|
||||
If provided, it overrides the ``host`` argument and tries to create
|
||||
a mutual TLS channel with client SSL credentials from
|
||||
``client_cert_source`` or application default SSL credentials.
|
||||
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
Deprecated. A callback to provide client SSL certificate bytes and
|
||||
private key bytes, both in PEM format. It is ignored if
|
||||
``api_mtls_endpoint`` is None.
|
||||
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
|
||||
for the grpc channel. It is ignored if a ``channel`` instance is provided.
|
||||
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
|
||||
A callback to provide client certificate bytes and private key bytes,
|
||||
both in PEM format. It is used to configure a mutual TLS channel. It is
|
||||
ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
|
||||
quota_project_id (Optional[str]): An optional project to use for billing
|
||||
and quota.
|
||||
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
|
||||
The client info used to send a user-agent string along with
|
||||
API requests. If ``None``, then default info will be used.
|
||||
Generally, you only need to set this if you're developing
|
||||
your own client library.
|
||||
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
|
||||
be used for service account credentials.
|
||||
|
||||
Raises:
|
||||
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
|
||||
creation failed for any reason.
|
||||
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
|
||||
and ``credentials_file`` are passed.
|
||||
"""
|
||||
self._grpc_channel = None
|
||||
self._ssl_channel_credentials = ssl_channel_credentials
|
||||
self._stubs: Dict[str, Callable] = {}
|
||||
self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None
|
||||
|
||||
if api_mtls_endpoint:
|
||||
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
|
||||
if client_cert_source:
|
||||
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
|
||||
|
||||
if isinstance(channel, aio.Channel):
|
||||
# Ignore credentials if a channel was passed.
|
||||
credentials = None
|
||||
self._ignore_credentials = True
|
||||
# If a channel was explicitly provided, set it.
|
||||
self._grpc_channel = channel
|
||||
self._ssl_channel_credentials = None
|
||||
else:
|
||||
if api_mtls_endpoint:
|
||||
host = api_mtls_endpoint
|
||||
|
||||
# Create SSL credentials with client_cert_source or application
|
||||
# default SSL credentials.
|
||||
if client_cert_source:
|
||||
cert, key = client_cert_source()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
else:
|
||||
self._ssl_channel_credentials = SslCredentials().ssl_credentials
|
||||
|
||||
else:
|
||||
if client_cert_source_for_mtls and not ssl_channel_credentials:
|
||||
cert, key = client_cert_source_for_mtls()
|
||||
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
|
||||
certificate_chain=cert, private_key=key
|
||||
)
|
||||
|
||||
# The base transport sets the host, credentials and scopes
|
||||
super().__init__(
|
||||
host=host,
|
||||
credentials=credentials,
|
||||
credentials_file=credentials_file,
|
||||
scopes=scopes,
|
||||
quota_project_id=quota_project_id,
|
||||
client_info=client_info,
|
||||
always_use_jwt_access=always_use_jwt_access,
|
||||
api_audience=api_audience,
|
||||
)
|
||||
|
||||
if not self._grpc_channel:
|
||||
# initialize with the provided callable or the default channel
|
||||
channel_init = channel or type(self).create_channel
|
||||
self._grpc_channel = channel_init(
|
||||
self._host,
|
||||
# use the credentials which are saved
|
||||
credentials=self._credentials,
|
||||
# Set ``credentials_file`` to ``None`` here as
|
||||
# the credentials that we saved earlier should be used.
|
||||
credentials_file=None,
|
||||
scopes=self._scopes,
|
||||
ssl_credentials=self._ssl_channel_credentials,
|
||||
quota_project_id=quota_project_id,
|
||||
options=[
|
||||
("grpc.max_send_message_length", -1),
|
||||
("grpc.max_receive_message_length", -1),
|
||||
],
|
||||
)
|
||||
|
||||
self._interceptor = _LoggingClientAIOInterceptor()
|
||||
self._grpc_channel._unary_unary_interceptors.append(self._interceptor)
|
||||
self._logged_channel = self._grpc_channel
|
||||
self._wrap_with_kind = (
|
||||
"kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters
|
||||
)
|
||||
# Wrap messages. This must be done after self._logged_channel exists
|
||||
self._prep_wrapped_messages(client_info)
|
||||
|
||||
@property
|
||||
def grpc_channel(self) -> aio.Channel:
|
||||
"""Create the channel designed to connect to this service.
|
||||
|
||||
This property caches on the instance; repeated calls return
|
||||
the same channel.
|
||||
"""
|
||||
# Return the channel from cache.
|
||||
return self._grpc_channel
|
||||
|
||||
@property
|
||||
def operations_client(self) -> operations_v1.OperationsAsyncClient:
|
||||
"""Create the client designed to process long-running operations.
|
||||
|
||||
This property caches on the instance; repeated calls return the same
|
||||
client.
|
||||
"""
|
||||
# Quick check: Only create a new client if we do not already have one.
|
||||
if self._operations_client is None:
|
||||
self._operations_client = operations_v1.OperationsAsyncClient(
|
||||
self._logged_channel
|
||||
)
|
||||
|
||||
# Return the client from cache.
|
||||
return self._operations_client
|
||||
|
||||
@property
|
||||
def create_tag_hold(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_holds.CreateTagHoldRequest], Awaitable[operations_pb2.Operation]
|
||||
]:
|
||||
r"""Return a callable for the create tag hold method over gRPC.
|
||||
|
||||
Creates a TagHold. Returns ALREADY_EXISTS if a TagHold with the
|
||||
same resource and origin exists under the same TagValue.
|
||||
|
||||
Returns:
|
||||
Callable[[~.CreateTagHoldRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "create_tag_hold" not in self._stubs:
|
||||
self._stubs["create_tag_hold"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagHolds/CreateTagHold",
|
||||
request_serializer=tag_holds.CreateTagHoldRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["create_tag_hold"]
|
||||
|
||||
@property
|
||||
def delete_tag_hold(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_holds.DeleteTagHoldRequest], Awaitable[operations_pb2.Operation]
|
||||
]:
|
||||
r"""Return a callable for the delete tag hold method over gRPC.
|
||||
|
||||
Deletes a TagHold.
|
||||
|
||||
Returns:
|
||||
Callable[[~.DeleteTagHoldRequest],
|
||||
Awaitable[~.Operation]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "delete_tag_hold" not in self._stubs:
|
||||
self._stubs["delete_tag_hold"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagHolds/DeleteTagHold",
|
||||
request_serializer=tag_holds.DeleteTagHoldRequest.serialize,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["delete_tag_hold"]
|
||||
|
||||
@property
|
||||
def list_tag_holds(
|
||||
self,
|
||||
) -> Callable[
|
||||
[tag_holds.ListTagHoldsRequest], Awaitable[tag_holds.ListTagHoldsResponse]
|
||||
]:
|
||||
r"""Return a callable for the list tag holds method over gRPC.
|
||||
|
||||
Lists TagHolds under a TagValue.
|
||||
|
||||
Returns:
|
||||
Callable[[~.ListTagHoldsRequest],
|
||||
Awaitable[~.ListTagHoldsResponse]]:
|
||||
A function that, when called, will call the underlying RPC
|
||||
on the server.
|
||||
"""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "list_tag_holds" not in self._stubs:
|
||||
self._stubs["list_tag_holds"] = self._logged_channel.unary_unary(
|
||||
"/google.cloud.resourcemanager.v3.TagHolds/ListTagHolds",
|
||||
request_serializer=tag_holds.ListTagHoldsRequest.serialize,
|
||||
response_deserializer=tag_holds.ListTagHoldsResponse.deserialize,
|
||||
)
|
||||
return self._stubs["list_tag_holds"]
|
||||
|
||||
def _prep_wrapped_messages(self, client_info):
|
||||
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
|
||||
self._wrapped_methods = {
|
||||
self.create_tag_hold: self._wrap_method(
|
||||
self.create_tag_hold,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.delete_tag_hold: self._wrap_method(
|
||||
self.delete_tag_hold,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.list_tag_holds: self._wrap_method(
|
||||
self.list_tag_holds,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
self.get_operation: self._wrap_method(
|
||||
self.get_operation,
|
||||
default_timeout=None,
|
||||
client_info=client_info,
|
||||
),
|
||||
}
|
||||
|
||||
def _wrap_method(self, func, *args, **kwargs):
|
||||
if self._wrap_with_kind: # pragma: NO COVER
|
||||
kwargs["kind"] = self.kind
|
||||
return gapic_v1.method_async.wrap_method(func, *args, **kwargs)
|
||||
|
||||
def close(self):
|
||||
return self._logged_channel.close()
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return "grpc_asyncio"
|
||||
|
||||
@property
|
||||
def get_operation(
|
||||
self,
|
||||
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
|
||||
r"""Return a callable for the get_operation method over gRPC."""
|
||||
# Generate a "stub function" on-the-fly which will actually make
|
||||
# the request.
|
||||
# gRPC handles serialization and deserialization, so we just need
|
||||
# to pass in the functions for each.
|
||||
if "get_operation" not in self._stubs:
|
||||
self._stubs["get_operation"] = self._logged_channel.unary_unary(
|
||||
"/google.longrunning.Operations/GetOperation",
|
||||
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
|
||||
response_deserializer=operations_pb2.Operation.FromString,
|
||||
)
|
||||
return self._stubs["get_operation"]
|
||||
|
||||
|
||||
__all__ = ("TagHoldsGrpcAsyncIOTransport",)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user