- On January 1, 2020 this library will no longer support Python 2 on the latest released version. - Previously released library versions will continue to be available. For more information please + As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.
{% block body %} {% endblock %} diff --git a/docs/asset_v1/services.rst b/docs/asset_v1/services.rst new file mode 100644 index 00000000..7f520451 --- /dev/null +++ b/docs/asset_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1 API +====================================== + +.. automodule:: google.cloud.asset_v1.services.asset_service + :members: + :inherited-members: diff --git a/docs/asset_v1/types.rst b/docs/asset_v1/types.rst new file mode 100644 index 00000000..cdddc7e3 --- /dev/null +++ b/docs/asset_v1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Asset v1 API +=================================== + +.. automodule:: google.cloud.asset_v1.types + :members: diff --git a/docs/asset_v1beta1/services.rst b/docs/asset_v1beta1/services.rst new file mode 100644 index 00000000..f14b6c6f --- /dev/null +++ b/docs/asset_v1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1beta1 API +=========================================== + +.. automodule:: google.cloud.asset_v1beta1.services.asset_service + :members: + :inherited-members: diff --git a/docs/asset_v1beta1/types.rst b/docs/asset_v1beta1/types.rst new file mode 100644 index 00000000..0c8d7ee2 --- /dev/null +++ b/docs/asset_v1beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Asset v1beta1 API +======================================== + +.. automodule:: google.cloud.asset_v1beta1.types + :members: diff --git a/docs/asset_v1p1beta1/services.rst b/docs/asset_v1p1beta1/services.rst new file mode 100644 index 00000000..e2f85315 --- /dev/null +++ b/docs/asset_v1p1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1p1beta1 API +============================================= + +.. automodule:: google.cloud.asset_v1p1beta1.services.asset_service + :members: + :inherited-members: diff --git a/docs/asset_v1p1beta1/types.rst b/docs/asset_v1p1beta1/types.rst new file mode 100644 index 00000000..044a7358 --- /dev/null +++ b/docs/asset_v1p1beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Asset v1p1beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p1beta1.types + :members: diff --git a/docs/asset_v1p2beta1/services.rst b/docs/asset_v1p2beta1/services.rst new file mode 100644 index 00000000..82401a22 --- /dev/null +++ b/docs/asset_v1p2beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1p2beta1 API +============================================= + +.. automodule:: google.cloud.asset_v1p2beta1.services.asset_service + :members: + :inherited-members: diff --git a/docs/asset_v1p2beta1/types.rst b/docs/asset_v1p2beta1/types.rst new file mode 100644 index 00000000..16ea1eeb --- /dev/null +++ b/docs/asset_v1p2beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Asset v1p2beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p2beta1.types + :members: diff --git a/docs/asset_v1p4beta1/services.rst b/docs/asset_v1p4beta1/services.rst new file mode 100644 index 00000000..27b24147 --- /dev/null +++ b/docs/asset_v1p4beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1p4beta1 API +============================================= + +.. automodule:: google.cloud.asset_v1p4beta1.services.asset_service + :members: + :inherited-members: diff --git a/docs/asset_v1p4beta1/types.rst b/docs/asset_v1p4beta1/types.rst new file mode 100644 index 00000000..ad03a830 --- /dev/null +++ b/docs/asset_v1p4beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Asset v1p4beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p4beta1.types + :members: diff --git a/docs/asset_v1p5beta1/services.rst b/docs/asset_v1p5beta1/services.rst new file mode 100644 index 00000000..09749b31 --- /dev/null +++ b/docs/asset_v1p5beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1p5beta1 API +============================================= + +.. automodule:: google.cloud.asset_v1p5beta1.services.asset_service + :members: + :inherited-members: diff --git a/docs/asset_v1p5beta1/types.rst b/docs/asset_v1p5beta1/types.rst new file mode 100644 index 00000000..eb7cc709 --- /dev/null +++ b/docs/asset_v1p5beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Asset v1p5beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p5beta1.types + :members: diff --git a/docs/conf.py b/docs/conf.py index 3f521b95..a272f47f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,6 +20,10 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + __version__ = "" # -- General configuration ------------------------------------------------ @@ -90,7 +94,12 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["_build"] +exclude_patterns = [ + "_build", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index 12fc69a5..00000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Asset API -========================== - -.. automodule:: google.cloud.asset_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index 962b18ff..00000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Asset API Client -================================ - -.. automodule:: google.cloud.asset_v1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst deleted file mode 100644 index f5b1195a..00000000 --- a/docs/gapic/v1beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Asset API -========================== - -.. automodule:: google.cloud.asset_v1beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst deleted file mode 100644 index 550bd114..00000000 --- a/docs/gapic/v1beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Asset API Client -================================ - -.. automodule:: google.cloud.asset_v1beta1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1p1beta1/api.rst b/docs/gapic/v1p1beta1/api.rst deleted file mode 100644 index 2534b7d3..00000000 --- a/docs/gapic/v1p1beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Asset API -========================== - -.. automodule:: google.cloud.asset_v1p1beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1p1beta1/types.rst b/docs/gapic/v1p1beta1/types.rst deleted file mode 100644 index 3e717313..00000000 --- a/docs/gapic/v1p1beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Asset API Client -================================ - -.. automodule:: google.cloud.asset_v1p1beta1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1p2beta1/api.rst b/docs/gapic/v1p2beta1/api.rst deleted file mode 100644 index ca2696c2..00000000 --- a/docs/gapic/v1p2beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Asset API -========================== - -.. automodule:: google.cloud.asset_v1p2beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1p2beta1/types.rst b/docs/gapic/v1p2beta1/types.rst deleted file mode 100644 index 914469b3..00000000 --- a/docs/gapic/v1p2beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Asset API Client -================================ - -.. automodule:: google.cloud.asset_v1p2beta1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1p4beta1/api.rst b/docs/gapic/v1p4beta1/api.rst deleted file mode 100644 index 0b2ea17d..00000000 --- a/docs/gapic/v1p4beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Asset API -========================== - -.. automodule:: google.cloud.asset_v1p4beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1p4beta1/types.rst b/docs/gapic/v1p4beta1/types.rst deleted file mode 100644 index 2a08e2d5..00000000 --- a/docs/gapic/v1p4beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Asset API Client -================================ - -.. automodule:: google.cloud.asset_v1p4beta1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1p5beta1/api.rst b/docs/gapic/v1p5beta1/api.rst deleted file mode 100644 index bbb03e40..00000000 --- a/docs/gapic/v1p5beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Asset API -========================== - -.. automodule:: google.cloud.asset_v1p5beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1p5beta1/types.rst b/docs/gapic/v1p5beta1/types.rst deleted file mode 100644 index 951aa3ab..00000000 --- a/docs/gapic/v1p5beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Asset API Client -================================ - -.. automodule:: google.cloud.asset_v1p5beta1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index a78971d6..9424b9c7 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -13,13 +13,13 @@ v1 .. toctree:: :maxdepth: 2 - Client (v1) - Types (v1) + asset_v1/services + asset_v1/types Beta releases with additional features over the current stable version. These are expected to move into the stable release soon; until then, the usual beta admonishment (changes are possible, etc.) applies. -In order to use it, you will want to import from +In order to use it, you will want to import from ``google.cloud.asset_v1p4beta1`` in lieu of ``google.cloud.asset_v1``. v1p1beta1 @@ -27,8 +27,8 @@ v1p1beta1 .. toctree:: :maxdepth: 2 - Client (v1p1beta1) - Types (v1p1beta1) + asset_v1p1beta1/services + asset_v1p1beta1/types v1p2beta1 @@ -36,8 +36,8 @@ v1p2beta1 .. toctree:: :maxdepth: 2 - Client (v1p1beta1) - Types (v1p1beta1) + asset_v1p2beta1/services + asset_v1p2beta1/types v1p4beta1 @@ -45,8 +45,8 @@ v1p4beta1 .. toctree:: :maxdepth: 2 - Client (v1p4beta1) - Types (v1p4beta1) + asset_v1p4beta1/services + asset_v1p4beta1/types v1p5beta1 @@ -54,8 +54,8 @@ v1p5beta1 .. toctree:: :maxdepth: 2 - Client (v1p5beta1) - Types (v1p5beta1) + asset_v1p5beta1/services + asset_v1p5beta1/types v1beta1 @@ -63,8 +63,19 @@ v1beta1 .. toctree:: :maxdepth: 2 - Client (v1beta1) - Types (v1beta1) + asset_v1beta1/services + asset_v1beta1/types + + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING Changelog diff --git a/google/cloud/asset/__init__.py b/google/cloud/asset/__init__.py new file mode 100644 index 00000000..ee8344cd --- /dev/null +++ b/google/cloud/asset/__init__.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 google.cloud.asset_v1.services.asset_service.async_client import ( + AssetServiceAsyncClient, +) +from google.cloud.asset_v1.services.asset_service.client import AssetServiceClient +from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryRequest +from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryResponse +from google.cloud.asset_v1.types.asset_service import BigQueryDestination +from google.cloud.asset_v1.types.asset_service import ContentType +from google.cloud.asset_v1.types.asset_service import CreateFeedRequest +from google.cloud.asset_v1.types.asset_service import DeleteFeedRequest +from google.cloud.asset_v1.types.asset_service import ExportAssetsRequest +from google.cloud.asset_v1.types.asset_service import ExportAssetsResponse +from google.cloud.asset_v1.types.asset_service import Feed +from google.cloud.asset_v1.types.asset_service import FeedOutputConfig +from google.cloud.asset_v1.types.asset_service import GcsDestination +from google.cloud.asset_v1.types.asset_service import GetFeedRequest +from google.cloud.asset_v1.types.asset_service import ListFeedsRequest +from google.cloud.asset_v1.types.asset_service import ListFeedsResponse +from google.cloud.asset_v1.types.asset_service import OutputConfig +from google.cloud.asset_v1.types.asset_service import PubsubDestination +from google.cloud.asset_v1.types.asset_service import SearchAllIamPoliciesRequest +from google.cloud.asset_v1.types.asset_service import SearchAllIamPoliciesResponse +from google.cloud.asset_v1.types.asset_service import SearchAllResourcesRequest +from google.cloud.asset_v1.types.asset_service import SearchAllResourcesResponse +from google.cloud.asset_v1.types.asset_service import UpdateFeedRequest +from google.cloud.asset_v1.types.assets import Asset +from google.cloud.asset_v1.types.assets import IamPolicySearchResult +from google.cloud.asset_v1.types.assets import Resource +from google.cloud.asset_v1.types.assets import ResourceSearchResult +from google.cloud.asset_v1.types.assets import TemporalAsset +from google.cloud.asset_v1.types.assets import TimeWindow + +__all__ = ( + "Asset", + "AssetServiceAsyncClient", + "AssetServiceClient", + "BatchGetAssetsHistoryRequest", + "BatchGetAssetsHistoryResponse", + "BigQueryDestination", + "ContentType", + "CreateFeedRequest", + "DeleteFeedRequest", + "ExportAssetsRequest", + "ExportAssetsResponse", + "Feed", + "FeedOutputConfig", + "GcsDestination", + "GetFeedRequest", + "IamPolicySearchResult", + "ListFeedsRequest", + "ListFeedsResponse", + "OutputConfig", + "PubsubDestination", + "Resource", + "ResourceSearchResult", + "SearchAllIamPoliciesRequest", + "SearchAllIamPoliciesResponse", + "SearchAllResourcesRequest", + "SearchAllResourcesResponse", + "TemporalAsset", + "TimeWindow", + "UpdateFeedRequest", +) diff --git a/google/cloud/asset/py.typed b/google/cloud/asset/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/google/cloud/asset/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/google/cloud/asset_v1/__init__.py b/google/cloud/asset_v1/__init__.py index f8e02189..d9f02892 100644 --- a/google/cloud/asset_v1/__init__.py +++ b/google/cloud/asset_v1/__init__.py @@ -1,45 +1,77 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.asset_v1 import types -from google.cloud.asset_v1.gapic import asset_service_client -from google.cloud.asset_v1.gapic import enums - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class AssetServiceClient(asset_service_client.AssetServiceClient): - __doc__ = asset_service_client.AssetServiceClient.__doc__ - enums = enums +from .services.asset_service import AssetServiceClient +from .types.asset_service import BatchGetAssetsHistoryRequest +from .types.asset_service import BatchGetAssetsHistoryResponse +from .types.asset_service import BigQueryDestination +from .types.asset_service import ContentType +from .types.asset_service import CreateFeedRequest +from .types.asset_service import DeleteFeedRequest +from .types.asset_service import ExportAssetsRequest +from .types.asset_service import ExportAssetsResponse +from .types.asset_service import Feed +from .types.asset_service import FeedOutputConfig +from .types.asset_service import GcsDestination +from .types.asset_service import GetFeedRequest +from .types.asset_service import ListFeedsRequest +from .types.asset_service import ListFeedsResponse +from .types.asset_service import OutputConfig +from .types.asset_service import PubsubDestination +from .types.asset_service import SearchAllIamPoliciesRequest +from .types.asset_service import SearchAllIamPoliciesResponse +from .types.asset_service import SearchAllResourcesRequest +from .types.asset_service import SearchAllResourcesResponse +from .types.asset_service import UpdateFeedRequest +from .types.assets import Asset +from .types.assets import IamPolicySearchResult +from .types.assets import Resource +from .types.assets import ResourceSearchResult +from .types.assets import TemporalAsset +from .types.assets import TimeWindow __all__ = ( - "enums", - "types", + "Asset", + "BatchGetAssetsHistoryRequest", + "BatchGetAssetsHistoryResponse", + "BigQueryDestination", + "ContentType", + "CreateFeedRequest", + "DeleteFeedRequest", + "ExportAssetsRequest", + "ExportAssetsResponse", + "Feed", + "FeedOutputConfig", + "GcsDestination", + "GetFeedRequest", + "IamPolicySearchResult", + "ListFeedsRequest", + "ListFeedsResponse", + "OutputConfig", + "PubsubDestination", + "Resource", + "ResourceSearchResult", + "SearchAllIamPoliciesRequest", + "SearchAllIamPoliciesResponse", + "SearchAllResourcesRequest", + "SearchAllResourcesResponse", + "TemporalAsset", + "TimeWindow", + "UpdateFeedRequest", "AssetServiceClient", ) diff --git a/google/cloud/asset_v1/gapic/__init__.py b/google/cloud/asset_v1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1/gapic/asset_service_client.py b/google/cloud/asset_v1/gapic/asset_service_client.py deleted file mode 100644 index 912e8d87..00000000 --- a/google/cloud/asset_v1/gapic/asset_service_client.py +++ /dev/null @@ -1,1140 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Accesses the google.cloud.asset.v1 AssetService API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.asset_v1.gapic import asset_service_client_config -from google.cloud.asset_v1.gapic import enums -from google.cloud.asset_v1.gapic.transports import asset_service_grpc_transport -from google.cloud.asset_v1.proto import asset_service_pb2 -from google.cloud.asset_v1.proto import asset_service_pb2_grpc -from google.cloud.asset_v1.proto import assets_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-asset",).version - - -class AssetServiceClient(object): - """Asset service definition.""" - - SERVICE_ADDRESS = "cloudasset.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.asset.v1.AssetService" - - @classmethod - def from_service_account_file(cls, filename, *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: - AssetServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def feed_path(cls, project, feed): - """Return a fully-qualified feed string.""" - return google.api_core.path_template.expand( - "projects/{project}/feeds/{feed}", project=project, feed=feed, - ) - - @classmethod - def project_path(cls, project): - """Return a fully-qualified project string.""" - return google.api_core.path_template.expand( - "projects/{project}", project=project - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.AssetServiceGrpcTransport, - Callable[[~.Credentials, type], ~.AssetServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = asset_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=asset_service_grpc_transport.AssetServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = asset_service_grpc_transport.AssetServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def export_assets( - self, - parent, - output_config, - read_time=None, - asset_types=None, - content_type=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Exports assets with time and resource types to a given Cloud Storage - location/BigQuery table. For Cloud Storage location destinations, the - output format is newline-delimited JSON. Each line represents a - ``google.cloud.asset.v1.Asset`` in the JSON format; for BigQuery table - destinations, the output table stores the fields in asset proto as - columns. This API implements the ``google.longrunning.Operation`` API , - which allows you to keep track of the export. We recommend intervals of - at least 2 seconds with exponential retry to poll the export operation - result. For regular-size resource parent, the export operation usually - finishes within 5 minutes. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.export_assets(parent, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The relative name of the root asset. This can only be an - organization number (such as "organizations/123"), a project ID (such as - "projects/my-project-id"), or a project number (such as "projects/12345"), - or a folder number (such as "folders/123"). - output_config (Union[dict, ~google.cloud.asset_v1.types.OutputConfig]): Required. Output configuration indicating where the results will be output - to. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1.types.OutputConfig` - read_time (Union[dict, ~google.cloud.asset_v1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp - between the current time and the current time minus 35 days (inclusive). - If not specified, the current time will be used. Due to delays in resource - data collection and indexing, there is a volatile window during which - running the same query may get different results. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1.types.Timestamp` - asset_types (list[str]): A list of asset types of which to take a snapshot for. Example: - "compute.googleapis.com/Disk". If specified, only matching assets will - be returned. See `Introduction to Cloud Asset - Inventory `__ - for all supported asset types. - content_type (~google.cloud.asset_v1.types.ContentType): Asset content type. If not specified, no content but the asset name will be - returned. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "export_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "export_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.export_assets, - default_retry=self._method_configs["ExportAssets"].retry, - default_timeout=self._method_configs["ExportAssets"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.ExportAssetsRequest( - parent=parent, - output_config=output_config, - read_time=read_time, - asset_types=asset_types, - content_type=content_type, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["export_assets"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - asset_service_pb2.ExportAssetsResponse, - metadata_type=asset_service_pb2.ExportAssetsRequest, - ) - - def batch_get_assets_history( - self, - parent, - content_type=None, - read_time_window=None, - asset_names=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Batch gets the update history of assets that overlap a time window. - For IAM_POLICY content, this API outputs history when the asset and its - attached IAM POLICY both exist. This can create gaps in the output - history. Otherwise, this API outputs history with asset in both - non-delete or deleted status. If a specified asset does not exist, this - API returns an INVALID_ARGUMENT error. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> response = client.batch_get_assets_history(parent) - - Args: - parent (str): Required. The relative name of the root asset. It can only be an - organization number (such as "organizations/123"), a project ID (such as - "projects/my-project-id")", or a project number (such as "projects/12345"). - asset_names (list[str]): A list of the full names of the assets. See: - https://cloud.google.com/asset-inventory/docs/resource-name-format - Example: - - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - - The request becomes a no-op if the asset name list is empty, and the max - size of the asset name list is 100 in one request. - content_type (~google.cloud.asset_v1.types.ContentType): Optional. The content type. - read_time_window (Union[dict, ~google.cloud.asset_v1.types.TimeWindow]): Optional. The time window for the asset history. Both start_time and - end_time are optional and if set, it must be after the current time - minus 35 days. If end_time is not set, it is default to current - timestamp. If start_time is not set, the snapshot of the assets at - end_time will be returned. The returned results contain all temporal - assets whose time window overlap with read_time_window. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1.types.TimeWindow` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_get_assets_history" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_get_assets_history" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_get_assets_history, - default_retry=self._method_configs["BatchGetAssetsHistory"].retry, - default_timeout=self._method_configs["BatchGetAssetsHistory"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.BatchGetAssetsHistoryRequest( - parent=parent, - asset_names=asset_names, - content_type=content_type, - read_time_window=read_time_window, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["batch_get_assets_history"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_feed( - self, - parent, - feed_id, - feed, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a feed in a parent project/folder/organization to listen to its - asset updates. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> # TODO: Initialize `feed_id`: - >>> feed_id = '' - >>> - >>> # TODO: Initialize `feed`: - >>> feed = {} - >>> - >>> response = client.create_feed(parent, feed_id, feed) - - Args: - parent (str): Required. The name of the project/folder/organization where this feed - should be created in. It can only be an organization number (such as - "organizations/123"), a folder number (such as "folders/123"), a project ID - (such as "projects/my-project-id")", or a project number (such as - "projects/12345"). - feed_id (str): Required. This is the client-assigned asset feed identifier and it needs to - be unique under a specific parent project/folder/organization. - feed (Union[dict, ~google.cloud.asset_v1.types.Feed]): Required. The feed details. The field ``name`` must be empty and it - will be generated in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1.types.Feed` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1.types.Feed` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_feed" not in self._inner_api_calls: - self._inner_api_calls[ - "create_feed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_feed, - default_retry=self._method_configs["CreateFeed"].retry, - default_timeout=self._method_configs["CreateFeed"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.CreateFeedRequest( - parent=parent, feed_id=feed_id, feed=feed, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_feed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_feed( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets details about an asset feed. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `name`: - >>> name = '' - >>> - >>> response = client.get_feed(name) - - Args: - name (str): Required. The name of the Feed and it must be in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1.types.Feed` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_feed" not in self._inner_api_calls: - self._inner_api_calls[ - "get_feed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_feed, - default_retry=self._method_configs["GetFeed"].retry, - default_timeout=self._method_configs["GetFeed"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.GetFeedRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_feed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_feeds( - self, - parent, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists all asset feeds in a parent project/folder/organization. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> response = client.list_feeds(parent) - - Args: - parent (str): Required. The parent project/folder/organization whose feeds are to be - listed. It can only be using project/folder/organization number (such as - "folders/12345")", or a project ID (such as "projects/my-project-id"). - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1.types.ListFeedsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_feeds" not in self._inner_api_calls: - self._inner_api_calls[ - "list_feeds" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_feeds, - default_retry=self._method_configs["ListFeeds"].retry, - default_timeout=self._method_configs["ListFeeds"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.ListFeedsRequest(parent=parent,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["list_feeds"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_feed( - self, - feed, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates an asset feed configuration. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `feed`: - >>> feed = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_feed(feed, update_mask) - - Args: - feed (Union[dict, ~google.cloud.asset_v1.types.Feed]): Required. The new values of feed details. It must match an existing - feed and the field ``name`` must be in the format of: - projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1.types.Feed` - update_mask (Union[dict, ~google.cloud.asset_v1.types.FieldMask]): Required. Only updates the ``feed`` fields indicated by this mask. - The field mask must not be empty, and it must not contain fields that - are immutable or only set by the server. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1.types.Feed` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_feed" not in self._inner_api_calls: - self._inner_api_calls[ - "update_feed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_feed, - default_retry=self._method_configs["UpdateFeed"].retry, - default_timeout=self._method_configs["UpdateFeed"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.UpdateFeedRequest( - feed=feed, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("feed.name", feed.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_feed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_feed( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes an asset feed. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `name`: - >>> name = '' - >>> - >>> client.delete_feed(name) - - Args: - name (str): Required. The name of the feed and it must be in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_feed" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_feed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_feed, - default_retry=self._method_configs["DeleteFeed"].retry, - default_timeout=self._method_configs["DeleteFeed"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.DeleteFeedRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_feed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def search_all_resources( - self, - scope, - query=None, - asset_types=None, - page_size=None, - order_by=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Searches all the resources within the given accessible scope (e.g., a - project, a folder or an organization). Callers should have - cloud.assets.SearchAllResources permission upon the requested scope, - otherwise the request will be rejected. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `scope`: - >>> scope = '' - >>> - >>> # Iterate over all results - >>> for element in client.search_all_resources(scope): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.search_all_resources(scope).pages: - ... for element in page: - ... # process element - ... pass - - Args: - scope (str): Required. A scope can be a project, a folder or an organization. The - search is limited to the resources within the ``scope``. - - The allowed values are: - - - projects/{PROJECT_ID} - - projects/{PROJECT_NUMBER} - - folders/{FOLDER_NUMBER} - - organizations/{ORGANIZATION_NUMBER} - query (str): Optional. The query statement. An empty query can be specified to - search all the resources of certain ``asset_types`` within the given - ``scope``. - - Examples: - - - ``name : "Important"`` to find Cloud resources whose name contains - "Important" as a word. - - ``displayName : "Impor*"`` to find Cloud resources whose display name - contains "Impor" as a word prefix. - - ``description : "*por*"`` to find Cloud resources whose description - contains "por" as a substring. - - ``location : "us-west*"`` to find Cloud resources whose location is - prefixed with "us-west". - - ``labels : "prod"`` to find Cloud resources whose labels contain - "prod" as a key or value. - - ``labels.env : "prod"`` to find Cloud resources which have a label - "env" and its value is "prod". - - ``labels.env : *`` to find Cloud resources which have a label "env". - - ``"Important"`` to find Cloud resources which contain "Important" as - a word in any of the searchable fields. - - ``"Impor*"`` to find Cloud resources which contain "Impor" as a word - prefix in any of the searchable fields. - - ``"*por*"`` to find Cloud resources which contain "por" as a - substring in any of the searchable fields. - - ``("Important" AND location : ("us-west1" OR "global"))`` to find - Cloud resources which contain "Important" as a word in any of the - searchable fields and are also located in the "us-west1" region or - the "global" location. - - See `how to construct a - query `__ - for more details. - asset_types (list[str]): Optional. A list of asset types that this request searches for. If - empty, it will search all the `searchable asset - types `__. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - order_by (str): Optional. A comma separated list of fields specifying the sorting - order of the results. The default order is ascending. Add " DESC" after - the field name to indicate descending order. Redundant space characters - are ignored. Example: "location DESC, name". See `supported resource - metadata - fields `__ - for more details. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.asset_v1.types.ResourceSearchResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "search_all_resources" not in self._inner_api_calls: - self._inner_api_calls[ - "search_all_resources" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.search_all_resources, - default_retry=self._method_configs["SearchAllResources"].retry, - default_timeout=self._method_configs["SearchAllResources"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.SearchAllResourcesRequest( - scope=scope, - query=query, - asset_types=asset_types, - page_size=page_size, - order_by=order_by, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("scope", scope)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["search_all_resources"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def search_all_iam_policies( - self, - scope, - query=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Searches all the IAM policies within the given accessible scope (e.g., a - project, a folder or an organization). Callers should have - cloud.assets.SearchAllIamPolicies permission upon the requested scope, - otherwise the request will be rejected. - - Example: - >>> from google.cloud import asset_v1 - >>> - >>> client = asset_v1.AssetServiceClient() - >>> - >>> # TODO: Initialize `scope`: - >>> scope = '' - >>> - >>> # Iterate over all results - >>> for element in client.search_all_iam_policies(scope): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.search_all_iam_policies(scope).pages: - ... for element in page: - ... # process element - ... pass - - Args: - scope (str): Required. A scope can be a project, a folder or an organization. The - search is limited to the IAM policies within the ``scope``. - - The allowed values are: - - - projects/{PROJECT_ID} - - projects/{PROJECT_NUMBER} - - folders/{FOLDER_NUMBER} - - organizations/{ORGANIZATION_NUMBER} - query (str): Optional. The query statement. An empty query can be specified to - search all the IAM policies within the given ``scope``. - - Examples: - - - ``policy : "amy@gmail.com"`` to find Cloud IAM policy bindings that - specify user "amy@gmail.com". - - ``policy : "roles/compute.admin"`` to find Cloud IAM policy bindings - that specify the Compute Admin role. - - ``policy.role.permissions : "storage.buckets.update"`` to find Cloud - IAM policy bindings that specify a role containing - "storage.buckets.update" permission. - - ``resource : "organizations/123"`` to find Cloud IAM policy bindings - that are set on "organizations/123". - - ``(resource : ("organizations/123" OR "folders/1234") AND policy : "amy")`` - to find Cloud IAM policy bindings that are set on "organizations/123" - or "folders/1234", and also specify user "amy". - - See `how to construct a - query `__ - for more details. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.asset_v1.types.IamPolicySearchResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "search_all_iam_policies" not in self._inner_api_calls: - self._inner_api_calls[ - "search_all_iam_policies" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.search_all_iam_policies, - default_retry=self._method_configs["SearchAllIamPolicies"].retry, - default_timeout=self._method_configs["SearchAllIamPolicies"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.SearchAllIamPoliciesRequest( - scope=scope, query=query, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("scope", scope)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["search_all_iam_policies"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator diff --git a/google/cloud/asset_v1/gapic/asset_service_client_config.py b/google/cloud/asset_v1/gapic/asset_service_client_config.py deleted file mode 100644 index 6f43e402..00000000 --- a/google/cloud/asset_v1/gapic/asset_service_client_config.py +++ /dev/null @@ -1,97 +0,0 @@ -config = { - "interfaces": { - "google.cloud.asset.v1.AssetService": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 15000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 15000, - "total_timeout_millis": 15000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - }, - "methods": { - "ExportAssets": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "BatchGetAssetsHistory": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "CreateFeed": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetFeed": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "ListFeeds": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "UpdateFeed": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "DeleteFeed": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "SearchAllResources": { - "timeout_millis": 15000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "SearchAllIamPolicies": { - "timeout_millis": 15000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - }, - } - } -} diff --git a/google/cloud/asset_v1/gapic/enums.py b/google/cloud/asset_v1/gapic/enums.py deleted file mode 100644 index a8b39897..00000000 --- a/google/cloud/asset_v1/gapic/enums.py +++ /dev/null @@ -1,201 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class ContentType(enum.IntEnum): - """ - Asset content type. - - Attributes: - CONTENT_TYPE_UNSPECIFIED (int): Unspecified content type. - RESOURCE (int): Resource metadata. - IAM_POLICY (int): The actual IAM policy set on a resource. - ORG_POLICY (int): The Cloud Organization Policy set on an asset. - ACCESS_POLICY (int): The Cloud Access context mananger Policy set on an asset. - """ - - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 - ORG_POLICY = 4 - ACCESS_POLICY = 5 - - -class DeviceEncryptionStatus(enum.IntEnum): - """ - The encryption state of the device. - - Attributes: - ENCRYPTION_UNSPECIFIED (int): The encryption status of the device is not specified or not known. - ENCRYPTION_UNSUPPORTED (int): The device does not support encryption. - UNENCRYPTED (int): The device supports encryption, but is currently unencrypted. - ENCRYPTED (int): The device is encrypted. - """ - - ENCRYPTION_UNSPECIFIED = 0 - ENCRYPTION_UNSUPPORTED = 1 - UNENCRYPTED = 2 - ENCRYPTED = 3 - - -class DeviceManagementLevel(enum.IntEnum): - """ - The degree to which the device is managed by the Cloud organization. - - Attributes: - MANAGEMENT_UNSPECIFIED (int): The device's management level is not specified or not known. - NONE (int): The device is not managed. - BASIC (int): Basic management is enabled, which is generally limited to monitoring and - wiping the corporate account. - COMPLETE (int): Complete device management. This includes more thorough monitoring and the - ability to directly manage the device (such as remote wiping). This can be - enabled through the Android Enterprise Platform. - """ - - MANAGEMENT_UNSPECIFIED = 0 - NONE = 1 - BASIC = 2 - COMPLETE = 3 - - -class NullValue(enum.IntEnum): - """ - ``NullValue`` is a singleton enumeration to represent the null value - for the ``Value`` type union. - - The JSON representation for ``NullValue`` is JSON ``null``. - - Attributes: - NULL_VALUE (int): Null value. - """ - - NULL_VALUE = 0 - - -class OsType(enum.IntEnum): - """ - The operating system type of the device. - Next id: 7 - - Attributes: - OS_UNSPECIFIED (int): The operating system of the device is not specified or not known. - DESKTOP_MAC (int): A desktop Mac operating system. - DESKTOP_WINDOWS (int): A desktop Windows operating system. - DESKTOP_LINUX (int): A desktop Linux operating system. - DESKTOP_CHROME_OS (int): A desktop ChromeOS operating system. - ANDROID (int): An Android operating system. - IOS (int): An iOS operating system. - """ - - OS_UNSPECIFIED = 0 - DESKTOP_MAC = 1 - DESKTOP_WINDOWS = 2 - DESKTOP_LINUX = 3 - DESKTOP_CHROME_OS = 6 - ANDROID = 4 - IOS = 5 - - -class BasicLevel(object): - class ConditionCombiningFunction(enum.IntEnum): - """ - Options for how the ``conditions`` list should be combined to - determine if this ``AccessLevel`` is applied. Default is AND. - - Attributes: - AND (int): All ``Conditions`` must be true for the ``BasicLevel`` to be true. - OR (int): If at least one ``Condition`` is true, then the ``BasicLevel`` is - true. - """ - - AND = 0 - OR = 1 - - -class Policy(object): - class ListPolicy(object): - class AllValues(enum.IntEnum): - """ - This enum can be used to set ``Policies`` that apply to all possible - configuration values rather than specific values in ``allowed_values`` - or ``denied_values``. - - Settting this to ``ALLOW`` will mean this ``Policy`` allows all values. - Similarly, setting it to ``DENY`` will mean no values are allowed. If - set to either ``ALLOW`` or - ``DENY,``\ allowed_values\ ``and``\ denied_values\ ``must be unset. Setting this to``\ ALL_VALUES_UNSPECIFIED\ ``allows for setting``\ allowed_values\ ``and``\ denied_values`. - - Attributes: - ALL_VALUES_UNSPECIFIED (int): Indicates that allowed_values or denied_values must be set. - ALLOW (int): A policy with this set allows all values. - DENY (int): A policy with this set denies all values. - """ - - ALL_VALUES_UNSPECIFIED = 0 - ALLOW = 1 - DENY = 2 - - -class ServicePerimeter(object): - class PerimeterType(enum.IntEnum): - """ - Specifies the type of the Perimeter. There are two types: regular and - bridge. Regular Service Perimeter contains resources, access levels, and - restricted services. Every resource can be in at most ONE - regular Service Perimeter. - - In addition to being in a regular service perimeter, a resource can also - be in zero or more perimeter bridges. A perimeter bridge only contains - resources. Cross project operations are permitted if all effected - resources share some perimeter (whether bridge or regular). Perimeter - Bridge does not contain access levels or services: those are governed - entirely by the regular perimeter that resource is in. - - Perimeter Bridges are typically useful when building more complex toplogies - with many independent perimeters that need to share some data with a common - perimeter, but should not be able to share data among themselves. - - Attributes: - PERIMETER_TYPE_REGULAR (int): Regular Perimeter. - PERIMETER_TYPE_BRIDGE (int): Perimeter Bridge. - """ - - PERIMETER_TYPE_REGULAR = 0 - PERIMETER_TYPE_BRIDGE = 1 - - -class TemporalAsset(object): - class PriorAssetState(enum.IntEnum): - """ - State of prior asset. - - Attributes: - PRIOR_ASSET_STATE_UNSPECIFIED (int): prior_asset is not applicable for the current asset. - PRESENT (int): prior_asset is populated correctly. - INVALID (int): Failed to set prior_asset. - DOES_NOT_EXIST (int): Current asset is the first known state. - DELETED (int): prior_asset is a deletion. - """ - - PRIOR_ASSET_STATE_UNSPECIFIED = 0 - PRESENT = 1 - INVALID = 2 - DOES_NOT_EXIST = 3 - DELETED = 4 diff --git a/google/cloud/asset_v1/gapic/transports/__init__.py b/google/cloud/asset_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1/gapic/transports/asset_service_grpc_transport.py b/google/cloud/asset_v1/gapic/transports/asset_service_grpc_transport.py deleted file mode 100644 index d7d957d1..00000000 --- a/google/cloud/asset_v1/gapic/transports/asset_service_grpc_transport.py +++ /dev/null @@ -1,254 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.asset_v1.proto import asset_service_pb2_grpc - - -class AssetServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.asset.v1 AssetService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="cloudasset.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "asset_service_stub": asset_service_pb2_grpc.AssetServiceStub(channel), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="cloudasset.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def export_assets(self): - """Return the gRPC stub for :meth:`AssetServiceClient.export_assets`. - - Exports assets with time and resource types to a given Cloud Storage - location/BigQuery table. For Cloud Storage location destinations, the - output format is newline-delimited JSON. Each line represents a - ``google.cloud.asset.v1.Asset`` in the JSON format; for BigQuery table - destinations, the output table stores the fields in asset proto as - columns. This API implements the ``google.longrunning.Operation`` API , - which allows you to keep track of the export. We recommend intervals of - at least 2 seconds with exponential retry to poll the export operation - result. For regular-size resource parent, the export operation usually - finishes within 5 minutes. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].ExportAssets - - @property - def batch_get_assets_history(self): - """Return the gRPC stub for :meth:`AssetServiceClient.batch_get_assets_history`. - - Batch gets the update history of assets that overlap a time window. - For IAM_POLICY content, this API outputs history when the asset and its - attached IAM POLICY both exist. This can create gaps in the output - history. Otherwise, this API outputs history with asset in both - non-delete or deleted status. If a specified asset does not exist, this - API returns an INVALID_ARGUMENT error. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].BatchGetAssetsHistory - - @property - def create_feed(self): - """Return the gRPC stub for :meth:`AssetServiceClient.create_feed`. - - Creates a feed in a parent project/folder/organization to listen to its - asset updates. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].CreateFeed - - @property - def get_feed(self): - """Return the gRPC stub for :meth:`AssetServiceClient.get_feed`. - - Gets details about an asset feed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].GetFeed - - @property - def list_feeds(self): - """Return the gRPC stub for :meth:`AssetServiceClient.list_feeds`. - - Lists all asset feeds in a parent project/folder/organization. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].ListFeeds - - @property - def update_feed(self): - """Return the gRPC stub for :meth:`AssetServiceClient.update_feed`. - - Updates an asset feed configuration. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].UpdateFeed - - @property - def delete_feed(self): - """Return the gRPC stub for :meth:`AssetServiceClient.delete_feed`. - - Deletes an asset feed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].DeleteFeed - - @property - def search_all_resources(self): - """Return the gRPC stub for :meth:`AssetServiceClient.search_all_resources`. - - Searches all the resources within the given accessible scope (e.g., a - project, a folder or an organization). Callers should have - cloud.assets.SearchAllResources permission upon the requested scope, - otherwise the request will be rejected. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].SearchAllResources - - @property - def search_all_iam_policies(self): - """Return the gRPC stub for :meth:`AssetServiceClient.search_all_iam_policies`. - - Searches all the IAM policies within the given accessible scope (e.g., a - project, a folder or an organization). Callers should have - cloud.assets.SearchAllIamPolicies permission upon the requested scope, - otherwise the request will be rejected. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].SearchAllIamPolicies diff --git a/google/cloud/asset_v1/proto/__init__.py b/google/cloud/asset_v1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1/proto/asset_service.proto b/google/cloud/asset_v1/proto/asset_service.proto deleted file mode 100644 index 6566d039..00000000 --- a/google/cloud/asset_v1/proto/asset_service.proto +++ /dev/null @@ -1,422 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.asset.v1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/cloud/asset/v1/assets.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/field_mask.proto"; -import "google/protobuf/timestamp.proto"; - -option csharp_namespace = "Google.Cloud.Asset.V1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/asset/v1;asset"; -option java_multiple_files = true; -option java_outer_classname = "AssetServiceProto"; -option java_package = "com.google.cloud.asset.v1"; -option php_namespace = "Google\\Cloud\\Asset\\V1"; - -// Asset service definition. -service AssetService { - option (google.api.default_host) = "cloudasset.googleapis.com"; - option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/cloud-platform"; - - // Exports assets with time and resource types to a given Cloud Storage - // location. The output format is newline-delimited JSON. - // This API implements the [google.longrunning.Operation][google.longrunning.Operation] API allowing you - // to keep track of the export. - rpc ExportAssets(ExportAssetsRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1/{parent=*/*}:exportAssets" - body: "*" - }; - option (google.longrunning.operation_info) = { - response_type: "google.cloud.asset.v1.ExportAssetsResponse" - metadata_type: "google.cloud.asset.v1.ExportAssetsRequest" - }; - } - - // Batch gets the update history of assets that overlap a time window. - // For RESOURCE content, this API outputs history with asset in both - // non-delete or deleted status. - // For IAM_POLICY content, this API outputs history when the asset and its - // attached IAM POLICY both exist. This can create gaps in the output history. - // If a specified asset does not exist, this API returns an INVALID_ARGUMENT - // error. - rpc BatchGetAssetsHistory(BatchGetAssetsHistoryRequest) returns (BatchGetAssetsHistoryResponse) { - option (google.api.http) = { - get: "/v1/{parent=*/*}:batchGetAssetsHistory" - }; - } - - // Creates a feed in a parent project/folder/organization to listen to its - // asset updates. - rpc CreateFeed(CreateFeedRequest) returns (Feed) { - option (google.api.http) = { - post: "/v1/{parent=*/*}/feeds" - body: "*" - }; - option (google.api.method_signature) = "parent"; - } - - // Gets details about an asset feed. - rpc GetFeed(GetFeedRequest) returns (Feed) { - option (google.api.http) = { - get: "/v1/{name=*/*/feeds/*}" - }; - option (google.api.method_signature) = "name"; - } - - // Lists all asset feeds in a parent project/folder/organization. - rpc ListFeeds(ListFeedsRequest) returns (ListFeedsResponse) { - option (google.api.http) = { - get: "/v1/{parent=*/*}/feeds" - }; - option (google.api.method_signature) = "parent"; - } - - // Updates an asset feed configuration. - rpc UpdateFeed(UpdateFeedRequest) returns (Feed) { - option (google.api.http) = { - patch: "/v1/{feed.name=*/*/feeds/*}" - body: "*" - }; - option (google.api.method_signature) = "feed"; - } - - // Deletes an asset feed. - rpc DeleteFeed(DeleteFeedRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1/{name=*/*/feeds/*}" - }; - option (google.api.method_signature) = "name"; - } -} - -// Export asset request. -message ExportAssetsRequest { - // Required. The relative name of the root asset. This can only be an - // organization number (such as "organizations/123"), a project ID (such as - // "projects/my-project-id"), or a project number (such as "projects/12345"), - // or a folder number (such as "folders/123"). - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - child_type: "cloudasset.googleapis.com/Asset" - } - ]; - - // Timestamp to take an asset snapshot. This can only be set to a timestamp - // between 2018-10-02 UTC (inclusive) and the current time. If not specified, - // the current time will be used. Due to delays in resource data collection - // and indexing, there is a volatile window during which running the same - // query may get different results. - google.protobuf.Timestamp read_time = 2; - - // A list of asset types of which to take a snapshot for. For example: - // "compute.googleapis.com/Disk". If specified, only matching assets will be - // returned. See [Introduction to Cloud Asset - // Inventory](https://cloud.google.com/asset-inventory/docs/overview) - // for all supported asset types. - repeated string asset_types = 3; - - // Asset content type. If not specified, no content but the asset name will be - // returned. - ContentType content_type = 4; - - // Required. Output configuration indicating where the results will be output - // to. All results will be in newline delimited JSON format. - OutputConfig output_config = 5 [(google.api.field_behavior) = REQUIRED]; -} - -// The export asset response. This message is returned by the -// [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] method in the returned -// [google.longrunning.Operation.response][google.longrunning.Operation.response] field. -message ExportAssetsResponse { - // Time the snapshot was taken. - google.protobuf.Timestamp read_time = 1; - - // Output configuration indicating where the results were output to. - // All results are in JSON format. - OutputConfig output_config = 2; -} - -// Batch get assets history request. -message BatchGetAssetsHistoryRequest { - // Required. The relative name of the root asset. It can only be an - // organization number (such as "organizations/123"), a project ID (such as - // "projects/my-project-id")", or a project number (such as "projects/12345"). - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - child_type: "cloudasset.googleapis.com/Asset" - } - ]; - - // A list of the full names of the assets. For example: - // `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - // See [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // and [Resource Name - // Format](https://cloud.google.com/asset-inventory/docs/resource-name-format) - // for more info. - // - // The request becomes a no-op if the asset name list is empty, and the max - // size of the asset name list is 100 in one request. - repeated string asset_names = 2; - - // Optional. The content type. - ContentType content_type = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The time window for the asset history. Both start_time and - // end_time are optional and if set, it must be after 2018-10-02 UTC. If - // end_time is not set, it is default to current timestamp. If start_time is - // not set, the snapshot of the assets at end_time will be returned. The - // returned results contain all temporal assets whose time window overlap with - // read_time_window. - TimeWindow read_time_window = 4 [(google.api.field_behavior) = OPTIONAL]; -} - -// Batch get assets history response. -message BatchGetAssetsHistoryResponse { - // A list of assets with valid time windows. - repeated TemporalAsset assets = 1; -} - -// Create asset feed request. -message CreateFeedRequest { - // Required. The name of the project/folder/organization where this feed - // should be created in. It can only be an organization number (such as - // "organizations/123"), a folder number (such as "folders/123"), a project ID - // (such as "projects/my-project-id")", or a project number (such as - // "projects/12345"). - string parent = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. This is the client-assigned asset feed identifier and it needs to - // be unique under a specific parent project/folder/organization. - string feed_id = 2 [(google.api.field_behavior) = REQUIRED]; - - // Required. The feed details. The field `name` must be empty and it will be generated - // in the format of: - // projects/project_number/feeds/feed_id - // folders/folder_number/feeds/feed_id - // organizations/organization_number/feeds/feed_id - Feed feed = 3 [(google.api.field_behavior) = REQUIRED]; -} - -// Get asset feed request. -message GetFeedRequest { - // Required. The name of the Feed and it must be in the format of: - // projects/project_number/feeds/feed_id - // folders/folder_number/feeds/feed_id - // organizations/organization_number/feeds/feed_id - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "cloudasset.googleapis.com/Feed" - } - ]; -} - -// List asset feeds request. -message ListFeedsRequest { - // Required. The parent project/folder/organization whose feeds are to be - // listed. It can only be using project/folder/organization number (such as - // "folders/12345")", or a project ID (such as "projects/my-project-id"). - string parent = 1 [(google.api.field_behavior) = REQUIRED]; -} - -message ListFeedsResponse { - // A list of feeds. - repeated Feed feeds = 1; -} - -// Update asset feed request. -message UpdateFeedRequest { - // Required. The new values of feed details. It must match an existing feed and the - // field `name` must be in the format of: - // projects/project_number/feeds/feed_id or - // folders/folder_number/feeds/feed_id or - // organizations/organization_number/feeds/feed_id. - Feed feed = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. Only updates the `feed` fields indicated by this mask. - // The field mask must not be empty, and it must not contain fields that - // are immutable or only set by the server. - google.protobuf.FieldMask update_mask = 2 [(google.api.field_behavior) = REQUIRED]; -} - -message DeleteFeedRequest { - // Required. The name of the feed and it must be in the format of: - // projects/project_number/feeds/feed_id - // folders/folder_number/feeds/feed_id - // organizations/organization_number/feeds/feed_id - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "cloudasset.googleapis.com/Feed" - } - ]; -} - -// Output configuration for export assets destination. -message OutputConfig { - // Asset export destination. - oneof destination { - // Destination on Cloud Storage. - GcsDestination gcs_destination = 1; - - // Destination on BigQuery. The output table stores the fields in asset - // proto as columns in BigQuery. The resource/iam_policy field is converted - // to a record with each field to a column, except metadata to a single JSON - // string. - BigQueryDestination bigquery_destination = 2; - } -} - -// A Cloud Storage location. -message GcsDestination { - // Required. - oneof object_uri { - // The uri of the Cloud Storage object. It's the same uri that is used by - // gsutil. For example: "gs://bucket_name/object_name". See [Viewing and - // Editing Object - // Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) - // for more information. - string uri = 1; - - // The uri prefix of all generated Cloud Storage objects. For example: - // "gs://bucket_name/object_name_prefix". Each object uri is in format: - // "gs://bucket_name/object_name_prefix// and only - // contains assets for that type. starts from 0. For example: - // "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is - // the first shard of output objects containing all - // compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be - // returned if file with the same name "gs://bucket_name/object_name_prefix" - // already exists. - string uri_prefix = 2; - } -} - -// A BigQuery destination. -message BigQueryDestination { - // Required. The BigQuery dataset in format - // "projects/projectId/datasets/datasetId", to which the snapshot result - // should be exported. If this dataset does not exist, the export call returns - // an error. - string dataset = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. The BigQuery table to which the snapshot result should be - // written. If this table does not exist, a new table with the given name - // will be created. - string table = 2 [(google.api.field_behavior) = REQUIRED]; - - // If the destination table already exists and this flag is `TRUE`, the - // table will be overwritten by the contents of assets snapshot. If the flag - // is not set and the destination table already exists, the export call - // returns an error. - bool force = 3; -} - -// A Cloud Pubsub destination. -message PubsubDestination { - // The name of the Cloud Pub/Sub topic to publish to. - // For example: `projects/PROJECT_ID/topics/TOPIC_ID`. - string topic = 1; -} - -// Asset content type. -enum ContentType { - // Unspecified content type. - CONTENT_TYPE_UNSPECIFIED = 0; - - // Resource metadata. - RESOURCE = 1; - - // The actual IAM policy set on a resource. - IAM_POLICY = 2; - - // The Cloud Organization Policy set on an asset. - ORG_POLICY = 4; - - // The Cloud Access context mananger Policy set on an asset. - ACCESS_POLICY = 5; -} - -// Output configuration for asset feed destination. -message FeedOutputConfig { - // Asset feed destination. - oneof destination { - // Destination on Cloud Pubsub. - PubsubDestination pubsub_destination = 1; - } -} - -// An asset feed used to export asset updates to a destinations. -// An asset feed filter controls what updates are exported. -// The asset feed must be created within a project, organization, or -// folder. Supported destinations are: -// Cloud Pub/Sub topics. -message Feed { - option (google.api.resource) = { - type: "cloudasset.googleapis.com/Feed" - pattern: "projects/{project}/feeds/{feed}" - pattern: "folders/{folder}/feeds/{feed}" - pattern: "organizations/{organization}/feeds/{feed}" - history: ORIGINALLY_SINGLE_PATTERN - }; - - // Required. The format will be - // projects/{project_number}/feeds/{client-assigned_feed_identifier} or - // folders/{folder_number}/feeds/{client-assigned_feed_identifier} or - // organizations/{organization_number}/feeds/{client-assigned_feed_identifier} - // - // The client-assigned feed identifier must be unique within the parent - // project/folder/organization. - string name = 1 [(google.api.field_behavior) = REQUIRED]; - - // A list of the full names of the assets to receive updates. You must specify - // either or both of asset_names and asset_types. Only asset updates matching - // specified asset_names and asset_types are exported to the feed. For - // example: - // `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - // See [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more info. - repeated string asset_names = 2; - - // A list of types of the assets to receive updates. You must specify either - // or both of asset_names and asset_types. Only asset updates matching - // specified asset_names and asset_types are exported to the feed. - // For example: - // "compute.googleapis.com/Disk" See [Introduction to Cloud Asset - // Inventory](https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview) - // for all supported asset types. - repeated string asset_types = 3; - - // Asset content type. If not specified, no content but the asset name and - // type will be returned. - ContentType content_type = 4; - - // Required. Feed output configuration defining where the asset updates are - // published to. - FeedOutputConfig feed_output_config = 5 [(google.api.field_behavior) = REQUIRED]; -} diff --git a/google/cloud/asset_v1/proto/asset_service_pb2.py b/google/cloud/asset_v1/proto/asset_service_pb2.py deleted file mode 100644 index e1c5c209..00000000 --- a/google/cloud/asset_v1/proto/asset_service_pb2.py +++ /dev/null @@ -1,2376 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1/proto/asset_service.proto -"""Generated protocol buffer code.""" -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.asset_v1.proto import ( - assets_pb2 as google_dot_cloud_dot_asset__v1_dot_proto_dot_assets__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.type import expr_pb2 as google_dot_type_dot_expr__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1/proto/asset_service.proto", - package="google.cloud.asset.v1", - syntax="proto3", - serialized_options=b"\n\031com.google.cloud.asset.v1B\021AssetServiceProtoP\001Z:google.golang.org/genproto/googleapis/cloud/asset/v1;asset\252\002\025Google.Cloud.Asset.V1\312\002\025Google\\Cloud\\Asset\\V1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n/google/cloud/asset_v1/proto/asset_service.proto\x12\x15google.cloud.asset.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a(google/cloud/asset_v1/proto/assets.proto\x1a#google/longrunning/operations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x16google/type/expr.proto"\x8d\x02\n\x13\x45xportAssetsRequest\x12\x37\n\x06parent\x18\x01 \x01(\tB\'\xe0\x41\x02\xfa\x41!\x12\x1f\x63loudasset.googleapis.com/Asset\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x13\n\x0b\x61sset_types\x18\x03 \x03(\t\x12\x38\n\x0c\x63ontent_type\x18\x04 \x01(\x0e\x32".google.cloud.asset.v1.ContentType\x12?\n\routput_config\x18\x05 \x01(\x0b\x32#.google.cloud.asset.v1.OutputConfigB\x03\xe0\x41\x02"\x81\x01\n\x14\x45xportAssetsResponse\x12-\n\tread_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12:\n\routput_config\x18\x02 \x01(\x0b\x32#.google.cloud.asset.v1.OutputConfig"\xed\x01\n\x1c\x42\x61tchGetAssetsHistoryRequest\x12\x37\n\x06parent\x18\x01 \x01(\tB\'\xe0\x41\x02\xfa\x41!\x12\x1f\x63loudasset.googleapis.com/Asset\x12\x13\n\x0b\x61sset_names\x18\x02 \x03(\t\x12=\n\x0c\x63ontent_type\x18\x03 \x01(\x0e\x32".google.cloud.asset.v1.ContentTypeB\x03\xe0\x41\x01\x12@\n\x10read_time_window\x18\x04 \x01(\x0b\x32!.google.cloud.asset.v1.TimeWindowB\x03\xe0\x41\x01"U\n\x1d\x42\x61tchGetAssetsHistoryResponse\x12\x34\n\x06\x61ssets\x18\x01 \x03(\x0b\x32$.google.cloud.asset.v1.TemporalAsset"n\n\x11\x43reateFeedRequest\x12\x13\n\x06parent\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x14\n\x07\x66\x65\x65\x64_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12.\n\x04\x66\x65\x65\x64\x18\x03 \x01(\x0b\x32\x1b.google.cloud.asset.v1.FeedB\x03\xe0\x41\x02"F\n\x0eGetFeedRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudasset.googleapis.com/Feed"\'\n\x10ListFeedsRequest\x12\x13\n\x06parent\x18\x01 \x01(\tB\x03\xe0\x41\x02"?\n\x11ListFeedsResponse\x12*\n\x05\x66\x65\x65\x64s\x18\x01 \x03(\x0b\x32\x1b.google.cloud.asset.v1.Feed"y\n\x11UpdateFeedRequest\x12.\n\x04\x66\x65\x65\x64\x18\x01 \x01(\x0b\x32\x1b.google.cloud.asset.v1.FeedB\x03\xe0\x41\x02\x12\x34\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x02"I\n\x11\x44\x65leteFeedRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudasset.googleapis.com/Feed"\xab\x01\n\x0cOutputConfig\x12@\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32%.google.cloud.asset.v1.GcsDestinationH\x00\x12J\n\x14\x62igquery_destination\x18\x02 \x01(\x0b\x32*.google.cloud.asset.v1.BigQueryDestinationH\x00\x42\r\n\x0b\x64\x65stination"C\n\x0eGcsDestination\x12\r\n\x03uri\x18\x01 \x01(\tH\x00\x12\x14\n\nuri_prefix\x18\x02 \x01(\tH\x00\x42\x0c\n\nobject_uri"N\n\x13\x42igQueryDestination\x12\x14\n\x07\x64\x61taset\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x12\n\x05table\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\r\n\x05\x66orce\x18\x03 \x01(\x08""\n\x11PubsubDestination\x12\r\n\x05topic\x18\x01 \x01(\t"i\n\x10\x46\x65\x65\x64OutputConfig\x12\x46\n\x12pubsub_destination\x18\x01 \x01(\x0b\x32(.google.cloud.asset.v1.PubsubDestinationH\x00\x42\r\n\x0b\x64\x65stination"\x81\x03\n\x04\x46\x65\x65\x64\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x13\n\x0b\x61sset_names\x18\x02 \x03(\t\x12\x13\n\x0b\x61sset_types\x18\x03 \x03(\t\x12\x38\n\x0c\x63ontent_type\x18\x04 \x01(\x0e\x32".google.cloud.asset.v1.ContentType\x12H\n\x12\x66\x65\x65\x64_output_config\x18\x05 \x01(\x0b\x32\'.google.cloud.asset.v1.FeedOutputConfigB\x03\xe0\x41\x02\x12$\n\tcondition\x18\x06 \x01(\x0b\x32\x11.google.type.Expr:\x91\x01\xea\x41\x8d\x01\n\x1e\x63loudasset.googleapis.com/Feed\x12\x1fprojects/{project}/feeds/{feed}\x12\x1d\x66olders/{folder}/feeds/{feed}\x12)organizations/{organization}/feeds/{feed} \x01"\xa5\x01\n\x19SearchAllResourcesRequest\x12\x12\n\x05scope\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x12\n\x05query\x18\x02 \x01(\tB\x03\xe0\x41\x01\x12\x18\n\x0b\x61sset_types\x18\x03 \x03(\tB\x03\xe0\x41\x01\x12\x16\n\tpage_size\x18\x04 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x05 \x01(\tB\x03\xe0\x41\x01\x12\x15\n\x08order_by\x18\x06 \x01(\tB\x03\xe0\x41\x01"s\n\x1aSearchAllResourcesResponse\x12<\n\x07results\x18\x01 \x03(\x0b\x32+.google.cloud.asset.v1.ResourceSearchResult\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"v\n\x1bSearchAllIamPoliciesRequest\x12\x12\n\x05scope\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x12\n\x05query\x18\x02 \x01(\tB\x03\xe0\x41\x01\x12\x16\n\tpage_size\x18\x03 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x04 \x01(\tB\x03\xe0\x41\x01"v\n\x1cSearchAllIamPoliciesResponse\x12=\n\x07results\x18\x01 \x03(\x0b\x32,.google.cloud.asset.v1.IamPolicySearchResult\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t*l\n\x0b\x43ontentType\x12\x1c\n\x18\x43ONTENT_TYPE_UNSPECIFIED\x10\x00\x12\x0c\n\x08RESOURCE\x10\x01\x12\x0e\n\nIAM_POLICY\x10\x02\x12\x0e\n\nORG_POLICY\x10\x04\x12\x11\n\rACCESS_POLICY\x10\x05\x32\xf0\x0b\n\x0c\x41ssetService\x12\xde\x01\n\x0c\x45xportAssets\x12*.google.cloud.asset.v1.ExportAssetsRequest\x1a\x1d.google.longrunning.Operation"\x82\x01\x82\xd3\xe4\x93\x02""\x1d/v1/{parent=*/*}:exportAssets:\x01*\xca\x41W\n*google.cloud.asset.v1.ExportAssetsResponse\x12)google.cloud.asset.v1.ExportAssetsRequest\x12\xb2\x01\n\x15\x42\x61tchGetAssetsHistory\x12\x33.google.cloud.asset.v1.BatchGetAssetsHistoryRequest\x1a\x34.google.cloud.asset.v1.BatchGetAssetsHistoryResponse".\x82\xd3\xe4\x93\x02(\x12&/v1/{parent=*/*}:batchGetAssetsHistory\x12\x7f\n\nCreateFeed\x12(.google.cloud.asset.v1.CreateFeedRequest\x1a\x1b.google.cloud.asset.v1.Feed"*\x82\xd3\xe4\x93\x02\x1b"\x16/v1/{parent=*/*}/feeds:\x01*\xda\x41\x06parent\x12t\n\x07GetFeed\x12%.google.cloud.asset.v1.GetFeedRequest\x1a\x1b.google.cloud.asset.v1.Feed"%\x82\xd3\xe4\x93\x02\x18\x12\x16/v1/{name=*/*/feeds/*}\xda\x41\x04name\x12\x87\x01\n\tListFeeds\x12\'.google.cloud.asset.v1.ListFeedsRequest\x1a(.google.cloud.asset.v1.ListFeedsResponse"\'\x82\xd3\xe4\x93\x02\x18\x12\x16/v1/{parent=*/*}/feeds\xda\x41\x06parent\x12\x82\x01\n\nUpdateFeed\x12(.google.cloud.asset.v1.UpdateFeedRequest\x1a\x1b.google.cloud.asset.v1.Feed"-\x82\xd3\xe4\x93\x02 2\x1b/v1/{feed.name=*/*/feeds/*}:\x01*\xda\x41\x04\x66\x65\x65\x64\x12u\n\nDeleteFeed\x12(.google.cloud.asset.v1.DeleteFeedRequest\x1a\x16.google.protobuf.Empty"%\x82\xd3\xe4\x93\x02\x18*\x16/v1/{name=*/*/feeds/*}\xda\x41\x04name\x12\xbf\x01\n\x12SearchAllResources\x12\x30.google.cloud.asset.v1.SearchAllResourcesRequest\x1a\x31.google.cloud.asset.v1.SearchAllResourcesResponse"D\x82\xd3\xe4\x93\x02$\x12"/v1/{scope=*/*}:searchAllResources\xda\x41\x17scope,query,asset_types\x12\xbb\x01\n\x14SearchAllIamPolicies\x12\x32.google.cloud.asset.v1.SearchAllIamPoliciesRequest\x1a\x33.google.cloud.asset.v1.SearchAllIamPoliciesResponse":\x82\xd3\xe4\x93\x02&\x12$/v1/{scope=*/*}:searchAllIamPolicies\xda\x41\x0bscope,query\x1aM\xca\x41\x19\x63loudasset.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\x9c\x01\n\x19\x63om.google.cloud.asset.v1B\x11\x41ssetServiceProtoP\x01Z:google.golang.org/genproto/googleapis/cloud/asset/v1;asset\xaa\x02\x15Google.Cloud.Asset.V1\xca\x02\x15Google\\Cloud\\Asset\\V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_asset__v1_dot_proto_dot_assets__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_duration__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_type_dot_expr__pb2.DESCRIPTOR, - ], -) - -_CONTENTTYPE = _descriptor.EnumDescriptor( - name="ContentType", - full_name="google.cloud.asset.v1.ContentType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="CONTENT_TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RESOURCE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="IAM_POLICY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ORG_POLICY", - index=3, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACCESS_POLICY", - index=4, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=3018, - serialized_end=3126, -) -_sym_db.RegisterEnumDescriptor(_CONTENTTYPE) - -ContentType = enum_type_wrapper.EnumTypeWrapper(_CONTENTTYPE) -CONTENT_TYPE_UNSPECIFIED = 0 -RESOURCE = 1 -IAM_POLICY = 2 -ORG_POLICY = 4 -ACCESS_POLICY = 5 - - -_EXPORTASSETSREQUEST = _descriptor.Descriptor( - name="ExportAssetsRequest", - full_name="google.cloud.asset.v1.ExportAssetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1.ExportAssetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A!\022\037cloudasset.googleapis.com/Asset", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.asset.v1.ExportAssetsRequest.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_types", - full_name="google.cloud.asset.v1.ExportAssetsRequest.asset_types", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content_type", - full_name="google.cloud.asset.v1.ExportAssetsRequest.content_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.asset.v1.ExportAssetsRequest.output_config", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=421, - serialized_end=690, -) - - -_EXPORTASSETSRESPONSE = _descriptor.Descriptor( - name="ExportAssetsResponse", - full_name="google.cloud.asset.v1.ExportAssetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.asset.v1.ExportAssetsResponse.read_time", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.asset.v1.ExportAssetsResponse.output_config", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=693, - serialized_end=822, -) - - -_BATCHGETASSETSHISTORYREQUEST = _descriptor.Descriptor( - name="BatchGetAssetsHistoryRequest", - full_name="google.cloud.asset.v1.BatchGetAssetsHistoryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1.BatchGetAssetsHistoryRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A!\022\037cloudasset.googleapis.com/Asset", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_names", - full_name="google.cloud.asset.v1.BatchGetAssetsHistoryRequest.asset_names", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content_type", - full_name="google.cloud.asset.v1.BatchGetAssetsHistoryRequest.content_type", - index=2, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time_window", - full_name="google.cloud.asset.v1.BatchGetAssetsHistoryRequest.read_time_window", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=825, - serialized_end=1062, -) - - -_BATCHGETASSETSHISTORYRESPONSE = _descriptor.Descriptor( - name="BatchGetAssetsHistoryResponse", - full_name="google.cloud.asset.v1.BatchGetAssetsHistoryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="assets", - full_name="google.cloud.asset.v1.BatchGetAssetsHistoryResponse.assets", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1064, - serialized_end=1149, -) - - -_CREATEFEEDREQUEST = _descriptor.Descriptor( - name="CreateFeedRequest", - full_name="google.cloud.asset.v1.CreateFeedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1.CreateFeedRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="feed_id", - full_name="google.cloud.asset.v1.CreateFeedRequest.feed_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="feed", - full_name="google.cloud.asset.v1.CreateFeedRequest.feed", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1151, - serialized_end=1261, -) - - -_GETFEEDREQUEST = _descriptor.Descriptor( - name="GetFeedRequest", - full_name="google.cloud.asset.v1.GetFeedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1.GetFeedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudasset.googleapis.com/Feed", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1263, - serialized_end=1333, -) - - -_LISTFEEDSREQUEST = _descriptor.Descriptor( - name="ListFeedsRequest", - full_name="google.cloud.asset.v1.ListFeedsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1.ListFeedsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1335, - serialized_end=1374, -) - - -_LISTFEEDSRESPONSE = _descriptor.Descriptor( - name="ListFeedsResponse", - full_name="google.cloud.asset.v1.ListFeedsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="feeds", - full_name="google.cloud.asset.v1.ListFeedsResponse.feeds", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1376, - serialized_end=1439, -) - - -_UPDATEFEEDREQUEST = _descriptor.Descriptor( - name="UpdateFeedRequest", - full_name="google.cloud.asset.v1.UpdateFeedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="feed", - full_name="google.cloud.asset.v1.UpdateFeedRequest.feed", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.asset.v1.UpdateFeedRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1441, - serialized_end=1562, -) - - -_DELETEFEEDREQUEST = _descriptor.Descriptor( - name="DeleteFeedRequest", - full_name="google.cloud.asset.v1.DeleteFeedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1.DeleteFeedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudasset.googleapis.com/Feed", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1564, - serialized_end=1637, -) - - -_OUTPUTCONFIG = _descriptor.Descriptor( - name="OutputConfig", - full_name="google.cloud.asset.v1.OutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_destination", - full_name="google.cloud.asset.v1.OutputConfig.gcs_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bigquery_destination", - full_name="google.cloud.asset.v1.OutputConfig.bigquery_destination", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="destination", - full_name="google.cloud.asset.v1.OutputConfig.destination", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1640, - serialized_end=1811, -) - - -_GCSDESTINATION = _descriptor.Descriptor( - name="GcsDestination", - full_name="google.cloud.asset.v1.GcsDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.asset.v1.GcsDestination.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uri_prefix", - full_name="google.cloud.asset.v1.GcsDestination.uri_prefix", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="object_uri", - full_name="google.cloud.asset.v1.GcsDestination.object_uri", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1813, - serialized_end=1880, -) - - -_BIGQUERYDESTINATION = _descriptor.Descriptor( - name="BigQueryDestination", - full_name="google.cloud.asset.v1.BigQueryDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="dataset", - full_name="google.cloud.asset.v1.BigQueryDestination.dataset", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="table", - full_name="google.cloud.asset.v1.BigQueryDestination.table", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="force", - full_name="google.cloud.asset.v1.BigQueryDestination.force", - index=2, - number=3, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1882, - serialized_end=1960, -) - - -_PUBSUBDESTINATION = _descriptor.Descriptor( - name="PubsubDestination", - full_name="google.cloud.asset.v1.PubsubDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="topic", - full_name="google.cloud.asset.v1.PubsubDestination.topic", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1962, - serialized_end=1996, -) - - -_FEEDOUTPUTCONFIG = _descriptor.Descriptor( - name="FeedOutputConfig", - full_name="google.cloud.asset.v1.FeedOutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="pubsub_destination", - full_name="google.cloud.asset.v1.FeedOutputConfig.pubsub_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="destination", - full_name="google.cloud.asset.v1.FeedOutputConfig.destination", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1998, - serialized_end=2103, -) - - -_FEED = _descriptor.Descriptor( - name="Feed", - full_name="google.cloud.asset.v1.Feed", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1.Feed.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_names", - full_name="google.cloud.asset.v1.Feed.asset_names", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_types", - full_name="google.cloud.asset.v1.Feed.asset_types", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content_type", - full_name="google.cloud.asset.v1.Feed.content_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="feed_output_config", - full_name="google.cloud.asset.v1.Feed.feed_output_config", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="condition", - full_name="google.cloud.asset.v1.Feed.condition", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352A\215\001\n\036cloudasset.googleapis.com/Feed\022\037projects/{project}/feeds/{feed}\022\035folders/{folder}/feeds/{feed}\022)organizations/{organization}/feeds/{feed} \001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2106, - serialized_end=2491, -) - - -_SEARCHALLRESOURCESREQUEST = _descriptor.Descriptor( - name="SearchAllResourcesRequest", - full_name="google.cloud.asset.v1.SearchAllResourcesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="scope", - full_name="google.cloud.asset.v1.SearchAllResourcesRequest.scope", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="query", - full_name="google.cloud.asset.v1.SearchAllResourcesRequest.query", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_types", - full_name="google.cloud.asset.v1.SearchAllResourcesRequest.asset_types", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.asset.v1.SearchAllResourcesRequest.page_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.asset.v1.SearchAllResourcesRequest.page_token", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="order_by", - full_name="google.cloud.asset.v1.SearchAllResourcesRequest.order_by", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2494, - serialized_end=2659, -) - - -_SEARCHALLRESOURCESRESPONSE = _descriptor.Descriptor( - name="SearchAllResourcesResponse", - full_name="google.cloud.asset.v1.SearchAllResourcesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="results", - full_name="google.cloud.asset.v1.SearchAllResourcesResponse.results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.asset.v1.SearchAllResourcesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2661, - serialized_end=2776, -) - - -_SEARCHALLIAMPOLICIESREQUEST = _descriptor.Descriptor( - name="SearchAllIamPoliciesRequest", - full_name="google.cloud.asset.v1.SearchAllIamPoliciesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="scope", - full_name="google.cloud.asset.v1.SearchAllIamPoliciesRequest.scope", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="query", - full_name="google.cloud.asset.v1.SearchAllIamPoliciesRequest.query", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.asset.v1.SearchAllIamPoliciesRequest.page_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.asset.v1.SearchAllIamPoliciesRequest.page_token", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2778, - serialized_end=2896, -) - - -_SEARCHALLIAMPOLICIESRESPONSE = _descriptor.Descriptor( - name="SearchAllIamPoliciesResponse", - full_name="google.cloud.asset.v1.SearchAllIamPoliciesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="results", - full_name="google.cloud.asset.v1.SearchAllIamPoliciesResponse.results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.asset.v1.SearchAllIamPoliciesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2898, - serialized_end=3016, -) - -_EXPORTASSETSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_EXPORTASSETSREQUEST.fields_by_name["content_type"].enum_type = _CONTENTTYPE -_EXPORTASSETSREQUEST.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_EXPORTASSETSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_EXPORTASSETSRESPONSE.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_BATCHGETASSETSHISTORYREQUEST.fields_by_name["content_type"].enum_type = _CONTENTTYPE -_BATCHGETASSETSHISTORYREQUEST.fields_by_name[ - "read_time_window" -].message_type = google_dot_cloud_dot_asset__v1_dot_proto_dot_assets__pb2._TIMEWINDOW -_BATCHGETASSETSHISTORYRESPONSE.fields_by_name[ - "assets" -].message_type = google_dot_cloud_dot_asset__v1_dot_proto_dot_assets__pb2._TEMPORALASSET -_CREATEFEEDREQUEST.fields_by_name["feed"].message_type = _FEED -_LISTFEEDSRESPONSE.fields_by_name["feeds"].message_type = _FEED -_UPDATEFEEDREQUEST.fields_by_name["feed"].message_type = _FEED -_UPDATEFEEDREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_OUTPUTCONFIG.fields_by_name["gcs_destination"].message_type = _GCSDESTINATION -_OUTPUTCONFIG.fields_by_name["bigquery_destination"].message_type = _BIGQUERYDESTINATION -_OUTPUTCONFIG.oneofs_by_name["destination"].fields.append( - _OUTPUTCONFIG.fields_by_name["gcs_destination"] -) -_OUTPUTCONFIG.fields_by_name[ - "gcs_destination" -].containing_oneof = _OUTPUTCONFIG.oneofs_by_name["destination"] -_OUTPUTCONFIG.oneofs_by_name["destination"].fields.append( - _OUTPUTCONFIG.fields_by_name["bigquery_destination"] -) -_OUTPUTCONFIG.fields_by_name[ - "bigquery_destination" -].containing_oneof = _OUTPUTCONFIG.oneofs_by_name["destination"] -_GCSDESTINATION.oneofs_by_name["object_uri"].fields.append( - _GCSDESTINATION.fields_by_name["uri"] -) -_GCSDESTINATION.fields_by_name["uri"].containing_oneof = _GCSDESTINATION.oneofs_by_name[ - "object_uri" -] -_GCSDESTINATION.oneofs_by_name["object_uri"].fields.append( - _GCSDESTINATION.fields_by_name["uri_prefix"] -) -_GCSDESTINATION.fields_by_name[ - "uri_prefix" -].containing_oneof = _GCSDESTINATION.oneofs_by_name["object_uri"] -_FEEDOUTPUTCONFIG.fields_by_name["pubsub_destination"].message_type = _PUBSUBDESTINATION -_FEEDOUTPUTCONFIG.oneofs_by_name["destination"].fields.append( - _FEEDOUTPUTCONFIG.fields_by_name["pubsub_destination"] -) -_FEEDOUTPUTCONFIG.fields_by_name[ - "pubsub_destination" -].containing_oneof = _FEEDOUTPUTCONFIG.oneofs_by_name["destination"] -_FEED.fields_by_name["content_type"].enum_type = _CONTENTTYPE -_FEED.fields_by_name["feed_output_config"].message_type = _FEEDOUTPUTCONFIG -_FEED.fields_by_name["condition"].message_type = google_dot_type_dot_expr__pb2._EXPR -_SEARCHALLRESOURCESRESPONSE.fields_by_name[ - "results" -].message_type = ( - google_dot_cloud_dot_asset__v1_dot_proto_dot_assets__pb2._RESOURCESEARCHRESULT -) -_SEARCHALLIAMPOLICIESRESPONSE.fields_by_name[ - "results" -].message_type = ( - google_dot_cloud_dot_asset__v1_dot_proto_dot_assets__pb2._IAMPOLICYSEARCHRESULT -) -DESCRIPTOR.message_types_by_name["ExportAssetsRequest"] = _EXPORTASSETSREQUEST -DESCRIPTOR.message_types_by_name["ExportAssetsResponse"] = _EXPORTASSETSRESPONSE -DESCRIPTOR.message_types_by_name[ - "BatchGetAssetsHistoryRequest" -] = _BATCHGETASSETSHISTORYREQUEST -DESCRIPTOR.message_types_by_name[ - "BatchGetAssetsHistoryResponse" -] = _BATCHGETASSETSHISTORYRESPONSE -DESCRIPTOR.message_types_by_name["CreateFeedRequest"] = _CREATEFEEDREQUEST -DESCRIPTOR.message_types_by_name["GetFeedRequest"] = _GETFEEDREQUEST -DESCRIPTOR.message_types_by_name["ListFeedsRequest"] = _LISTFEEDSREQUEST -DESCRIPTOR.message_types_by_name["ListFeedsResponse"] = _LISTFEEDSRESPONSE -DESCRIPTOR.message_types_by_name["UpdateFeedRequest"] = _UPDATEFEEDREQUEST -DESCRIPTOR.message_types_by_name["DeleteFeedRequest"] = _DELETEFEEDREQUEST -DESCRIPTOR.message_types_by_name["OutputConfig"] = _OUTPUTCONFIG -DESCRIPTOR.message_types_by_name["GcsDestination"] = _GCSDESTINATION -DESCRIPTOR.message_types_by_name["BigQueryDestination"] = _BIGQUERYDESTINATION -DESCRIPTOR.message_types_by_name["PubsubDestination"] = _PUBSUBDESTINATION -DESCRIPTOR.message_types_by_name["FeedOutputConfig"] = _FEEDOUTPUTCONFIG -DESCRIPTOR.message_types_by_name["Feed"] = _FEED -DESCRIPTOR.message_types_by_name[ - "SearchAllResourcesRequest" -] = _SEARCHALLRESOURCESREQUEST -DESCRIPTOR.message_types_by_name[ - "SearchAllResourcesResponse" -] = _SEARCHALLRESOURCESRESPONSE -DESCRIPTOR.message_types_by_name[ - "SearchAllIamPoliciesRequest" -] = _SEARCHALLIAMPOLICIESREQUEST -DESCRIPTOR.message_types_by_name[ - "SearchAllIamPoliciesResponse" -] = _SEARCHALLIAMPOLICIESRESPONSE -DESCRIPTOR.enum_types_by_name["ContentType"] = _CONTENTTYPE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ExportAssetsRequest = _reflection.GeneratedProtocolMessageType( - "ExportAssetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _EXPORTASSETSREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Export asset request. - - Attributes: - parent: - Required. The relative name of the root asset. This can only - be an organization number (such as “organizations/123”), a - project ID (such as “projects/my-project-id”), or a project - number (such as “projects/12345”), or a folder number (such as - “folders/123”). - read_time: - Timestamp to take an asset snapshot. This can only be set to a - timestamp between the current time and the current time minus - 35 days (inclusive). If not specified, the current time will - be used. Due to delays in resource data collection and - indexing, there is a volatile window during which running the - same query may get different results. - asset_types: - A list of asset types of which to take a snapshot for. - Example: “compute.googleapis.com/Disk”. If specified, only - matching assets will be returned. See `Introduction to Cloud - Asset Inventory `__ for all supported asset types. - content_type: - Asset content type. If not specified, no content but the asset - name will be returned. - output_config: - Required. Output configuration indicating where the results - will be output to. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.ExportAssetsRequest) - }, -) -_sym_db.RegisterMessage(ExportAssetsRequest) - -ExportAssetsResponse = _reflection.GeneratedProtocolMessageType( - "ExportAssetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _EXPORTASSETSRESPONSE, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """The export asset response. This message is returned by the [google.lon - grunning.Operations.GetOperation][google.longrunning.Operations.GetOpe - ration] method in the returned [google.longrunning.Operation.response] - [google.longrunning.Operation.response] field. - - Attributes: - read_time: - Time the snapshot was taken. - output_config: - Output configuration indicating where the results were output - to. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.ExportAssetsResponse) - }, -) -_sym_db.RegisterMessage(ExportAssetsResponse) - -BatchGetAssetsHistoryRequest = _reflection.GeneratedProtocolMessageType( - "BatchGetAssetsHistoryRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHGETASSETSHISTORYREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Batch get assets history request. - - Attributes: - parent: - Required. The relative name of the root asset. It can only be - an organization number (such as “organizations/123”), a - project ID (such as “projects/my-project-id”)“, or a project - number (such as”projects/12345"). - asset_names: - A list of the full names of the assets. See: - https://cloud.google.com/asset-inventory/docs/resource-name- - format Example: ``//compute.googleapis.com/projects/my_projec - t_123/zones/zone1/instances/instance1``. The request becomes - a no-op if the asset name list is empty, and the max size of - the asset name list is 100 in one request. - content_type: - Optional. The content type. - read_time_window: - Optional. The time window for the asset history. Both - start_time and end_time are optional and if set, it must be - after the current time minus 35 days. If end_time is not set, - it is default to current timestamp. If start_time is not set, - the snapshot of the assets at end_time will be returned. The - returned results contain all temporal assets whose time window - overlap with read_time_window. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.BatchGetAssetsHistoryRequest) - }, -) -_sym_db.RegisterMessage(BatchGetAssetsHistoryRequest) - -BatchGetAssetsHistoryResponse = _reflection.GeneratedProtocolMessageType( - "BatchGetAssetsHistoryResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHGETASSETSHISTORYRESPONSE, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Batch get assets history response. - - Attributes: - assets: - A list of assets with valid time windows. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.BatchGetAssetsHistoryResponse) - }, -) -_sym_db.RegisterMessage(BatchGetAssetsHistoryResponse) - -CreateFeedRequest = _reflection.GeneratedProtocolMessageType( - "CreateFeedRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEFEEDREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Create asset feed request. - - Attributes: - parent: - Required. The name of the project/folder/organization where - this feed should be created in. It can only be an organization - number (such as “organizations/123”), a folder number (such as - “folders/123”), a project ID (such as “projects/my-project- - id”)“, or a project number (such as”projects/12345"). - feed_id: - Required. This is the client-assigned asset feed identifier - and it needs to be unique under a specific parent - project/folder/organization. - feed: - Required. The feed details. The field ``name`` must be empty - and it will be generated in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.CreateFeedRequest) - }, -) -_sym_db.RegisterMessage(CreateFeedRequest) - -GetFeedRequest = _reflection.GeneratedProtocolMessageType( - "GetFeedRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETFEEDREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Get asset feed request. - - Attributes: - name: - Required. The name of the Feed and it must be in the format - of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.GetFeedRequest) - }, -) -_sym_db.RegisterMessage(GetFeedRequest) - -ListFeedsRequest = _reflection.GeneratedProtocolMessageType( - "ListFeedsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTFEEDSREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """List asset feeds request. - - Attributes: - parent: - Required. The parent project/folder/organization whose feeds - are to be listed. It can only be using - project/folder/organization number (such as “folders/12345”)“, - or a project ID (such as”projects/my-project-id"). - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.ListFeedsRequest) - }, -) -_sym_db.RegisterMessage(ListFeedsRequest) - -ListFeedsResponse = _reflection.GeneratedProtocolMessageType( - "ListFeedsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTFEEDSRESPONSE, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """ - Attributes: - feeds: - A list of feeds. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.ListFeedsResponse) - }, -) -_sym_db.RegisterMessage(ListFeedsResponse) - -UpdateFeedRequest = _reflection.GeneratedProtocolMessageType( - "UpdateFeedRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEFEEDREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Update asset feed request. - - Attributes: - feed: - Required. The new values of feed details. It must match an - existing feed and the field ``name`` must be in the format of: - projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - update_mask: - Required. Only updates the ``feed`` fields indicated by this - mask. The field mask must not be empty, and it must not - contain fields that are immutable or only set by the server. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.UpdateFeedRequest) - }, -) -_sym_db.RegisterMessage(UpdateFeedRequest) - -DeleteFeedRequest = _reflection.GeneratedProtocolMessageType( - "DeleteFeedRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEFEEDREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """ - Attributes: - name: - Required. The name of the feed and it must be in the format - of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.DeleteFeedRequest) - }, -) -_sym_db.RegisterMessage(DeleteFeedRequest) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Output configuration for export assets destination. - - Attributes: - destination: - Asset export destination. - gcs_destination: - Destination on Cloud Storage. - bigquery_destination: - Destination on BigQuery. The output table stores the fields in - asset proto as columns in BigQuery. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """A Cloud Storage location. - - Attributes: - object_uri: - Required. - uri: - The uri of the Cloud Storage object. It’s the same uri that is - used by gsutil. Example: “gs://bucket_name/object_name”. See - `Viewing and Editing Object Metadata - `__ for more information. - uri_prefix: - The uri prefix of all generated Cloud Storage objects. - Example: “gs://bucket_name/object_name_prefix”. Each object - uri is in format: “gs://bucket_name/object_name_prefix// and - only contains assets for that type. starts from 0. Example:”gs - ://bucket_name/object_name_prefix/compute.googleapis.com/Disk/ - 0" is the first shard of output objects containing all - compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error - will be returned if file with the same name - “gs://bucket_name/object_name_prefix” already exists. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - -BigQueryDestination = _reflection.GeneratedProtocolMessageType( - "BigQueryDestination", - (_message.Message,), - { - "DESCRIPTOR": _BIGQUERYDESTINATION, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """A BigQuery destination for exporting assets to. - - Attributes: - dataset: - Required. The BigQuery dataset in format - “projects/projectId/datasets/datasetId”, to which the snapshot - result should be exported. If this dataset does not exist, the - export call returns an INVALID_ARGUMENT error. - table: - Required. The BigQuery table to which the snapshot result - should be written. If this table does not exist, a new table - with the given name will be created. - force: - If the destination table already exists and this flag is - ``TRUE``, the table will be overwritten by the contents of - assets snapshot. If the flag is ``FALSE`` or unset and the - destination table already exists, the export call returns an - INVALID_ARGUMEMT error. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.BigQueryDestination) - }, -) -_sym_db.RegisterMessage(BigQueryDestination) - -PubsubDestination = _reflection.GeneratedProtocolMessageType( - "PubsubDestination", - (_message.Message,), - { - "DESCRIPTOR": _PUBSUBDESTINATION, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """A Pub/Sub destination. - - Attributes: - topic: - The name of the Pub/Sub topic to publish to. Example: - ``projects/PROJECT_ID/topics/TOPIC_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.PubsubDestination) - }, -) -_sym_db.RegisterMessage(PubsubDestination) - -FeedOutputConfig = _reflection.GeneratedProtocolMessageType( - "FeedOutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _FEEDOUTPUTCONFIG, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Output configuration for asset feed destination. - - Attributes: - destination: - Asset feed destination. - pubsub_destination: - Destination on Pub/Sub. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.FeedOutputConfig) - }, -) -_sym_db.RegisterMessage(FeedOutputConfig) - -Feed = _reflection.GeneratedProtocolMessageType( - "Feed", - (_message.Message,), - { - "DESCRIPTOR": _FEED, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """An asset feed used to export asset updates to a destinations. An asset - feed filter controls what updates are exported. The asset feed must be - created within a project, organization, or folder. Supported - destinations are: Pub/Sub topics. - - Attributes: - name: - Required. The format will be - projects/{project_number}/feeds/{client- - assigned_feed_identifier} or - folders/{folder_number}/feeds/{client- - assigned_feed_identifier} or - organizations/{organization_number}/feeds/{client- - assigned_feed_identifier} The client-assigned feed identifier - must be unique within the parent project/folder/organization. - asset_names: - A list of the full names of the assets to receive updates. You - must specify either or both of asset_names and asset_types. - Only asset updates matching specified asset_names or - asset_types are exported to the feed. Example: ``//compute.goo - gleapis.com/projects/my_project_123/zones/zone1/instances/inst - ance1``. See `Resource Names `__ for more info. - asset_types: - A list of types of the assets to receive updates. You must - specify either or both of asset_names and asset_types. Only - asset updates matching specified asset_names or asset_types - are exported to the feed. Example: - ``"compute.googleapis.com/Disk"`` See `this topic - `__ for a list of all supported asset types. - content_type: - Asset content type. If not specified, no content but the asset - name and type will be returned. - feed_output_config: - Required. Feed output configuration defining where the asset - updates are published to. - condition: - A condition which determines whether an asset update should be - published. If specified, an asset will be returned only when - the expression evaluates to true. When set, ``expression`` - field in the ``Expr`` must be a valid [CEL expression] - (https://github.com/google/cel-spec) on a TemporalAsset with - name ``temporal_asset``. Example: a Feed with expression - (“temporal_asset.deleted == true”) will only publish Asset - deletions. Other fields in ``Expr`` are optional. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.Feed) - }, -) -_sym_db.RegisterMessage(Feed) - -SearchAllResourcesRequest = _reflection.GeneratedProtocolMessageType( - "SearchAllResourcesRequest", - (_message.Message,), - { - "DESCRIPTOR": _SEARCHALLRESOURCESREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Search all resources request. - - Attributes: - scope: - Required. A scope can be a project, a folder or an - organization. The search is limited to the resources within - the ``scope``. The allowed values are: - - projects/{PROJECT_ID} - projects/{PROJECT_NUMBER} - - folders/{FOLDER_NUMBER} - organizations/{ORGANIZATION_NUMBER} - query: - Optional. The query statement. An empty query can be specified - to search all the resources of certain ``asset_types`` within - the given ``scope``. Examples: - ``name : "Important"`` to - find Cloud resources whose name contains “Important” as a - word. - ``displayName : "Impor*"`` to find Cloud resources - whose display name contains “Impor” as a word prefix. - - ``description : "*por*"`` to find Cloud resources whose - description contains “por” as a substring. - ``location : - "us-west*"`` to find Cloud resources whose location is - prefixed with “us-west”. - ``labels : "prod"`` to find Cloud - resources whose labels contain “prod” as a key or value. - - ``labels.env : "prod"`` to find Cloud resources which have a - label “env” and its value is “prod”. - ``labels.env : *`` - to find Cloud resources which have a label “env”. - - ``"Important"`` to find Cloud resources which contain - “Important” as a word in any of the searchable fields. - - ``"Impor*"`` to find Cloud resources which contain “Impor” as - a word prefix in any of the searchable fields. - - ``"*por*"`` to find Cloud resources which contain “por” as a - substring in any of the searchable fields. - ``("Important" - AND location : ("us-west1" OR "global"))`` to find Cloud - resources which contain “Important” as a word in any of the - searchable fields and are also located in the “us-west1” - region or the “global” location. See `how to construct a - query `__ for more details. - asset_types: - Optional. A list of asset types that this request searches - for. If empty, it will search all the `searchable asset types - `__. - page_size: - Optional. The page size for search result pagination. Page - size is capped at 500 even if a larger value is given. If set - to zero, server will pick an appropriate default. Returned - results may be fewer than requested. When this happens, there - could be more results as long as ``next_page_token`` is - returned. - page_token: - Optional. If present, then retrieve the next batch of results - from the preceding call to this method. ``page_token`` must be - the value of ``next_page_token`` from the previous response. - The values of all other method parameters, must be identical - to those in the previous call. - order_by: - Optional. A comma separated list of fields specifying the - sorting order of the results. The default order is ascending. - Add " DESC" after the field name to indicate descending order. - Redundant space characters are ignored. Example: “location - DESC, name”. See `supported resource metadata fields - `__ for more - details. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.SearchAllResourcesRequest) - }, -) -_sym_db.RegisterMessage(SearchAllResourcesRequest) - -SearchAllResourcesResponse = _reflection.GeneratedProtocolMessageType( - "SearchAllResourcesResponse", - (_message.Message,), - { - "DESCRIPTOR": _SEARCHALLRESOURCESRESPONSE, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Search all resources response. - - Attributes: - results: - A list of Resources that match the search query. It contains - the resource standard metadata information. - next_page_token: - If there are more results than those appearing in this - response, then ``next_page_token`` is included. To get the - next set of results, call this method again using the value of - ``next_page_token`` as ``page_token``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.SearchAllResourcesResponse) - }, -) -_sym_db.RegisterMessage(SearchAllResourcesResponse) - -SearchAllIamPoliciesRequest = _reflection.GeneratedProtocolMessageType( - "SearchAllIamPoliciesRequest", - (_message.Message,), - { - "DESCRIPTOR": _SEARCHALLIAMPOLICIESREQUEST, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Search all IAM policies request. - - Attributes: - scope: - Required. A scope can be a project, a folder or an - organization. The search is limited to the IAM policies within - the ``scope``. The allowed values are: - - projects/{PROJECT_ID} - projects/{PROJECT_NUMBER} - - folders/{FOLDER_NUMBER} - organizations/{ORGANIZATION_NUMBER} - query: - Optional. The query statement. An empty query can be specified - to search all the IAM policies within the given ``scope``. - Examples: - ``policy : "amy@gmail.com"`` to find Cloud IAM - policy bindings that specify user “amy@gmail.com”. - - ``policy : "roles/compute.admin"`` to find Cloud IAM policy - bindings that specify the Compute Admin role. - - ``policy.role.permissions : "storage.buckets.update"`` to find - Cloud IAM policy bindings that specify a role containing - “storage.buckets.update” permission. - ``resource : - "organizations/123"`` to find Cloud IAM policy bindings - that are set on “organizations/123”. - ``(resource : - ("organizations/123" OR "folders/1234") AND policy : "amy")`` - to find Cloud IAM policy bindings that are set on - “organizations/123” or “folders/1234”, and also specify - user “amy”. See `how to construct a query - `__ for more details. - page_size: - Optional. The page size for search result pagination. Page - size is capped at 500 even if a larger value is given. If set - to zero, server will pick an appropriate default. Returned - results may be fewer than requested. When this happens, there - could be more results as long as ``next_page_token`` is - returned. - page_token: - Optional. If present, retrieve the next batch of results from - the preceding call to this method. ``page_token`` must be the - value of ``next_page_token`` from the previous response. The - values of all other method parameters must be identical to - those in the previous call. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.SearchAllIamPoliciesRequest) - }, -) -_sym_db.RegisterMessage(SearchAllIamPoliciesRequest) - -SearchAllIamPoliciesResponse = _reflection.GeneratedProtocolMessageType( - "SearchAllIamPoliciesResponse", - (_message.Message,), - { - "DESCRIPTOR": _SEARCHALLIAMPOLICIESRESPONSE, - "__module__": "google.cloud.asset_v1.proto.asset_service_pb2", - "__doc__": """Search all IAM policies response. - - Attributes: - results: - A list of IamPolicy that match the search query. Related - information such as the associated resource is returned along - with the policy. - next_page_token: - Set if there are more results than those appearing in this - response; to get the next set of results, call this method - again, using this value as the ``page_token``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.SearchAllIamPoliciesResponse) - }, -) -_sym_db.RegisterMessage(SearchAllIamPoliciesResponse) - - -DESCRIPTOR._options = None -_EXPORTASSETSREQUEST.fields_by_name["parent"]._options = None -_EXPORTASSETSREQUEST.fields_by_name["output_config"]._options = None -_BATCHGETASSETSHISTORYREQUEST.fields_by_name["parent"]._options = None -_BATCHGETASSETSHISTORYREQUEST.fields_by_name["content_type"]._options = None -_BATCHGETASSETSHISTORYREQUEST.fields_by_name["read_time_window"]._options = None -_CREATEFEEDREQUEST.fields_by_name["parent"]._options = None -_CREATEFEEDREQUEST.fields_by_name["feed_id"]._options = None -_CREATEFEEDREQUEST.fields_by_name["feed"]._options = None -_GETFEEDREQUEST.fields_by_name["name"]._options = None -_LISTFEEDSREQUEST.fields_by_name["parent"]._options = None -_UPDATEFEEDREQUEST.fields_by_name["feed"]._options = None -_UPDATEFEEDREQUEST.fields_by_name["update_mask"]._options = None -_DELETEFEEDREQUEST.fields_by_name["name"]._options = None -_BIGQUERYDESTINATION.fields_by_name["dataset"]._options = None -_BIGQUERYDESTINATION.fields_by_name["table"]._options = None -_FEED.fields_by_name["name"]._options = None -_FEED.fields_by_name["feed_output_config"]._options = None -_FEED._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["scope"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["query"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["asset_types"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["page_size"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["page_token"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["order_by"]._options = None -_SEARCHALLIAMPOLICIESREQUEST.fields_by_name["scope"]._options = None -_SEARCHALLIAMPOLICIESREQUEST.fields_by_name["query"]._options = None -_SEARCHALLIAMPOLICIESREQUEST.fields_by_name["page_size"]._options = None -_SEARCHALLIAMPOLICIESREQUEST.fields_by_name["page_token"]._options = None - -_ASSETSERVICE = _descriptor.ServiceDescriptor( - name="AssetService", - full_name="google.cloud.asset.v1.AssetService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\031cloudasset.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=3129, - serialized_end=4649, - methods=[ - _descriptor.MethodDescriptor( - name="ExportAssets", - full_name="google.cloud.asset.v1.AssetService.ExportAssets", - index=0, - containing_service=None, - input_type=_EXPORTASSETSREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002""\035/v1/{parent=*/*}:exportAssets:\001*\312AW\n*google.cloud.asset.v1.ExportAssetsResponse\022)google.cloud.asset.v1.ExportAssetsRequest', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="BatchGetAssetsHistory", - full_name="google.cloud.asset.v1.AssetService.BatchGetAssetsHistory", - index=1, - containing_service=None, - input_type=_BATCHGETASSETSHISTORYREQUEST, - output_type=_BATCHGETASSETSHISTORYRESPONSE, - serialized_options=b"\202\323\344\223\002(\022&/v1/{parent=*/*}:batchGetAssetsHistory", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateFeed", - full_name="google.cloud.asset.v1.AssetService.CreateFeed", - index=2, - containing_service=None, - input_type=_CREATEFEEDREQUEST, - output_type=_FEED, - serialized_options=b'\202\323\344\223\002\033"\026/v1/{parent=*/*}/feeds:\001*\332A\006parent', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetFeed", - full_name="google.cloud.asset.v1.AssetService.GetFeed", - index=3, - containing_service=None, - input_type=_GETFEEDREQUEST, - output_type=_FEED, - serialized_options=b"\202\323\344\223\002\030\022\026/v1/{name=*/*/feeds/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListFeeds", - full_name="google.cloud.asset.v1.AssetService.ListFeeds", - index=4, - containing_service=None, - input_type=_LISTFEEDSREQUEST, - output_type=_LISTFEEDSRESPONSE, - serialized_options=b"\202\323\344\223\002\030\022\026/v1/{parent=*/*}/feeds\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateFeed", - full_name="google.cloud.asset.v1.AssetService.UpdateFeed", - index=5, - containing_service=None, - input_type=_UPDATEFEEDREQUEST, - output_type=_FEED, - serialized_options=b"\202\323\344\223\002 2\033/v1/{feed.name=*/*/feeds/*}:\001*\332A\004feed", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteFeed", - full_name="google.cloud.asset.v1.AssetService.DeleteFeed", - index=6, - containing_service=None, - input_type=_DELETEFEEDREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002\030*\026/v1/{name=*/*/feeds/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SearchAllResources", - full_name="google.cloud.asset.v1.AssetService.SearchAllResources", - index=7, - containing_service=None, - input_type=_SEARCHALLRESOURCESREQUEST, - output_type=_SEARCHALLRESOURCESRESPONSE, - serialized_options=b'\202\323\344\223\002$\022"/v1/{scope=*/*}:searchAllResources\332A\027scope,query,asset_types', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SearchAllIamPolicies", - full_name="google.cloud.asset.v1.AssetService.SearchAllIamPolicies", - index=8, - containing_service=None, - input_type=_SEARCHALLIAMPOLICIESREQUEST, - output_type=_SEARCHALLIAMPOLICIESRESPONSE, - serialized_options=b"\202\323\344\223\002&\022$/v1/{scope=*/*}:searchAllIamPolicies\332A\013scope,query", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_ASSETSERVICE) - -DESCRIPTOR.services_by_name["AssetService"] = _ASSETSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1/proto/asset_service_pb2_grpc.py b/google/cloud/asset_v1/proto/asset_service_pb2_grpc.py deleted file mode 100644 index 78708cc0..00000000 --- a/google/cloud/asset_v1/proto/asset_service_pb2_grpc.py +++ /dev/null @@ -1,462 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.asset_v1.proto import ( - asset_service_pb2 as google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class AssetServiceStub(object): - """Asset service definition. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ExportAssets = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/ExportAssets", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ExportAssetsRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.BatchGetAssetsHistory = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryResponse.FromString, - ) - self.CreateFeed = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/CreateFeed", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.CreateFeedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.FromString, - ) - self.GetFeed = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/GetFeed", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.GetFeedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.FromString, - ) - self.ListFeeds = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/ListFeeds", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ListFeedsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ListFeedsResponse.FromString, - ) - self.UpdateFeed = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/UpdateFeed", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.UpdateFeedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.FromString, - ) - self.DeleteFeed = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/DeleteFeed", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.DeleteFeedRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.SearchAllResources = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/SearchAllResources", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllResourcesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllResourcesResponse.FromString, - ) - self.SearchAllIamPolicies = channel.unary_unary( - "/google.cloud.asset.v1.AssetService/SearchAllIamPolicies", - request_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesResponse.FromString, - ) - - -class AssetServiceServicer(object): - """Asset service definition. - """ - - def ExportAssets(self, request, context): - """Exports assets with time and resource types to a given Cloud Storage - location/BigQuery table. For Cloud Storage location destinations, the - output format is newline-delimited JSON. Each line represents a - [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in the JSON - format; for BigQuery table destinations, the output table stores the fields - in asset proto as columns. This API implements the - [google.longrunning.Operation][google.longrunning.Operation] API , which - allows you to keep track of the export. We recommend intervals of at least - 2 seconds with exponential retry to poll the export operation result. For - regular-size resource parent, the export operation usually finishes within - 5 minutes. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def BatchGetAssetsHistory(self, request, context): - """Batch gets the update history of assets that overlap a time window. - For IAM_POLICY content, this API outputs history when the asset and its - attached IAM POLICY both exist. This can create gaps in the output history. - Otherwise, this API outputs history with asset in both non-delete or - deleted status. - If a specified asset does not exist, this API returns an INVALID_ARGUMENT - error. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateFeed(self, request, context): - """Creates a feed in a parent project/folder/organization to listen to its - asset updates. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetFeed(self, request, context): - """Gets details about an asset feed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListFeeds(self, request, context): - """Lists all asset feeds in a parent project/folder/organization. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateFeed(self, request, context): - """Updates an asset feed configuration. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteFeed(self, request, context): - """Deletes an asset feed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SearchAllResources(self, request, context): - """Searches all the resources within the given accessible scope (e.g., a - project, a folder or an organization). Callers should have - cloud.assets.SearchAllResources permission upon the requested scope, - otherwise the request will be rejected. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SearchAllIamPolicies(self, request, context): - """Searches all the IAM policies within the given accessible scope (e.g., a - project, a folder or an organization). Callers should have - cloud.assets.SearchAllIamPolicies permission upon the requested scope, - otherwise the request will be rejected. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_AssetServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "ExportAssets": grpc.unary_unary_rpc_method_handler( - servicer.ExportAssets, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ExportAssetsRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "BatchGetAssetsHistory": grpc.unary_unary_rpc_method_handler( - servicer.BatchGetAssetsHistory, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryResponse.SerializeToString, - ), - "CreateFeed": grpc.unary_unary_rpc_method_handler( - servicer.CreateFeed, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.CreateFeedRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.SerializeToString, - ), - "GetFeed": grpc.unary_unary_rpc_method_handler( - servicer.GetFeed, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.GetFeedRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.SerializeToString, - ), - "ListFeeds": grpc.unary_unary_rpc_method_handler( - servicer.ListFeeds, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ListFeedsRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ListFeedsResponse.SerializeToString, - ), - "UpdateFeed": grpc.unary_unary_rpc_method_handler( - servicer.UpdateFeed, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.UpdateFeedRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.SerializeToString, - ), - "DeleteFeed": grpc.unary_unary_rpc_method_handler( - servicer.DeleteFeed, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.DeleteFeedRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "SearchAllResources": grpc.unary_unary_rpc_method_handler( - servicer.SearchAllResources, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllResourcesRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllResourcesResponse.SerializeToString, - ), - "SearchAllIamPolicies": grpc.unary_unary_rpc_method_handler( - servicer.SearchAllIamPolicies, - request_deserializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.asset.v1.AssetService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class AssetService(object): - """Asset service definition. - """ - - @staticmethod - def ExportAssets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/ExportAssets", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ExportAssetsRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def BatchGetAssetsHistory( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryRequest.SerializeToString, - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateFeed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/CreateFeed", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.CreateFeedRequest.SerializeToString, - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetFeed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/GetFeed", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.GetFeedRequest.SerializeToString, - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListFeeds( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/ListFeeds", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ListFeedsRequest.SerializeToString, - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.ListFeedsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateFeed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/UpdateFeed", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.UpdateFeedRequest.SerializeToString, - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.Feed.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteFeed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/DeleteFeed", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.DeleteFeedRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SearchAllResources( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/SearchAllResources", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllResourcesRequest.SerializeToString, - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllResourcesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SearchAllIamPolicies( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1.AssetService/SearchAllIamPolicies", - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesRequest.SerializeToString, - google_dot_cloud_dot_asset__v1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/asset_v1/proto/assets.proto b/google/cloud/asset_v1/proto/assets.proto deleted file mode 100644 index 6a5c8cb8..00000000 --- a/google/cloud/asset_v1/proto/assets.proto +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.asset.v1; - -import "google/api/resource.proto"; -import "google/iam/v1/policy.proto"; -import "google/protobuf/any.proto"; -import "google/protobuf/struct.proto"; -import "google/protobuf/timestamp.proto"; -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option csharp_namespace = "Google.Cloud.Asset.V1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/asset/v1;asset"; -option java_multiple_files = true; -option java_outer_classname = "AssetProto"; -option java_package = "com.google.cloud.asset.v1"; -option php_namespace = "Google\\Cloud\\Asset\\V1"; - -// Temporal asset. In addition to the asset, the temporal asset includes the -// status of the asset and valid from and to time of it. -message TemporalAsset { - // The time window when the asset data and state was observed. - TimeWindow window = 1; - - // If the asset is deleted or not. - bool deleted = 2; - - // Asset. - Asset asset = 3; -} - -// A time window of (start_time, end_time]. -message TimeWindow { - // Start time of the time window (exclusive). - google.protobuf.Timestamp start_time = 1; - - // End time of the time window (inclusive). - // Current timestamp if not specified. - google.protobuf.Timestamp end_time = 2; -} - -// Cloud asset. This includes all Google Cloud Platform resources, -// Cloud IAM policies, and other non-GCP assets. -message Asset { - option (google.api.resource) = { - type: "cloudasset.googleapis.com/Asset" - pattern: "*" - }; - - // The full name of the asset. For example: - // `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - // See [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more information. - string name = 1; - - // Type of the asset. Example: "compute.googleapis.com/Disk". - string asset_type = 2; - - // Representation of the resource. - Resource resource = 3; - - // Representation of the actual Cloud IAM policy set on a cloud resource. For - // each resource, there must be at most one Cloud IAM policy set on it. - google.iam.v1.Policy iam_policy = 4; - - // Asset's ancestry path in Cloud Resource Manager (CRM) hierarchy, - // represented as a list of relative resource names. Ancestry path starts with - // the closest CRM ancestor and ends at root. If the asset is a CRM - // project/folder/organization, this starts from the asset itself. - // - // Example: ["projects/123456789", "folders/5432", "organizations/1234"] - repeated string ancestors = 10; -} - -// Representation of a cloud resource. -message Resource { - // The API version. Example: "v1". - string version = 1; - - // The URL of the discovery document containing the resource's JSON schema. - // For example: - // `"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"`. - // It will be left unspecified for resources without a discovery-based API, - // such as Cloud Bigtable. - string discovery_document_uri = 2; - - // The JSON schema name listed in the discovery document. - // Example: "Project". It will be left unspecified for resources (such as - // Cloud Bigtable) without a discovery-based API. - string discovery_name = 3; - - // The REST URL for accessing the resource. An HTTP GET operation using this - // URL returns the resource itself. - // Example: - // `https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`. - // It will be left unspecified for resources without a REST API. - string resource_url = 4; - - // The full name of the immediate parent of this resource. See - // [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more information. - // - // For GCP assets, it is the parent resource defined in the [Cloud IAM policy - // hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy). - // For example: - // `"//cloudresourcemanager.googleapis.com/projects/my_project_123"`. - // - // For third-party assets, it is up to the users to define. - string parent = 5; - - // The content of the resource, in which some sensitive fields are scrubbed - // away and may not be present. - google.protobuf.Struct data = 6; -} diff --git a/google/cloud/asset_v1/proto/assets_pb2.py b/google/cloud/asset_v1/proto/assets_pb2.py deleted file mode 100644 index 893a7349..00000000 --- a/google/cloud/asset_v1/proto/assets_pb2.py +++ /dev/null @@ -1,1629 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1/proto/assets.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.orgpolicy.v1 import ( - orgpolicy_pb2 as google_dot_cloud_dot_orgpolicy_dot_v1_dot_orgpolicy__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.identity.accesscontextmanager.v1 import ( - access_level_pb2 as google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__level__pb2, -) -from google.identity.accesscontextmanager.v1 import ( - access_policy_pb2 as google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__policy__pb2, -) -from google.identity.accesscontextmanager.v1 import ( - service_perimeter_pb2 as google_dot_identity_dot_accesscontextmanager_dot_v1_dot_service__perimeter__pb2, -) -from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import code_pb2 as google_dot_rpc_dot_code__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1/proto/assets.proto", - package="google.cloud.asset.v1", - syntax="proto3", - serialized_options=b"\n\031com.google.cloud.asset.v1B\nAssetProtoP\001Z:google.golang.org/genproto/googleapis/cloud/asset/v1;asset\370\001\001\252\002\025Google.Cloud.Asset.V1\312\002\025Google\\Cloud\\Asset\\V1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n(google/cloud/asset_v1/proto/assets.proto\x12\x15google.cloud.asset.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto\x1a)google/cloud/orgpolicy/v1/orgpolicy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a:google/identity/accesscontextmanager/v1/access_level.proto\x1a;google/identity/accesscontextmanager/v1/access_policy.proto\x1a?google/identity/accesscontextmanager/v1/service_perimeter.proto\x1a\x19google/protobuf/any.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x15google/rpc/code.proto"\xf5\x02\n\rTemporalAsset\x12\x31\n\x06window\x18\x01 \x01(\x0b\x32!.google.cloud.asset.v1.TimeWindow\x12\x0f\n\x07\x64\x65leted\x18\x02 \x01(\x08\x12+\n\x05\x61sset\x18\x03 \x01(\x0b\x32\x1c.google.cloud.asset.v1.Asset\x12O\n\x11prior_asset_state\x18\x04 \x01(\x0e\x32\x34.google.cloud.asset.v1.TemporalAsset.PriorAssetState\x12\x31\n\x0bprior_asset\x18\x05 \x01(\x0b\x32\x1c.google.cloud.asset.v1.Asset"o\n\x0fPriorAssetState\x12!\n\x1dPRIOR_ASSET_STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07PRESENT\x10\x01\x12\x0b\n\x07INVALID\x10\x02\x12\x12\n\x0e\x44OES_NOT_EXIST\x10\x03\x12\x0b\n\x07\x44\x45LETED\x10\x04"j\n\nTimeWindow\x12.\n\nstart_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\xba\x04\n\x05\x41sset\x12/\n\x0bupdate_time\x18\x0b \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\nasset_type\x18\x02 \x01(\t\x12\x31\n\x08resource\x18\x03 \x01(\x0b\x32\x1f.google.cloud.asset.v1.Resource\x12)\n\niam_policy\x18\x04 \x01(\x0b\x32\x15.google.iam.v1.Policy\x12\x35\n\norg_policy\x18\x06 \x03(\x0b\x32!.google.cloud.orgpolicy.v1.Policy\x12N\n\raccess_policy\x18\x07 \x01(\x0b\x32\x35.google.identity.accesscontextmanager.v1.AccessPolicyH\x00\x12L\n\x0c\x61\x63\x63\x65ss_level\x18\x08 \x01(\x0b\x32\x34.google.identity.accesscontextmanager.v1.AccessLevelH\x00\x12V\n\x11service_perimeter\x18\t \x01(\x0b\x32\x39.google.identity.accesscontextmanager.v1.ServicePerimeterH\x00\x12\x11\n\tancestors\x18\n \x03(\t:\'\xea\x41$\n\x1f\x63loudasset.googleapis.com/Asset\x12\x01*B\x17\n\x15\x61\x63\x63\x65ss_context_policy"\xb2\x01\n\x08Resource\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x1e\n\x16\x64iscovery_document_uri\x18\x02 \x01(\t\x12\x16\n\x0e\x64iscovery_name\x18\x03 \x01(\t\x12\x14\n\x0cresource_url\x18\x04 \x01(\t\x12\x0e\n\x06parent\x18\x05 \x01(\t\x12%\n\x04\x64\x61ta\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x10\n\x08location\x18\x08 \x01(\t"\xcc\x02\n\x14ResourceSearchResult\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\nasset_type\x18\x02 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x04 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x05 \x01(\t\x12\x10\n\x08location\x18\x06 \x01(\t\x12G\n\x06labels\x18\x07 \x03(\x0b\x32\x37.google.cloud.asset.v1.ResourceSearchResult.LabelsEntry\x12\x14\n\x0cnetwork_tags\x18\x08 \x03(\t\x12\x36\n\x15\x61\x64\x64itional_attributes\x18\t \x01(\x0b\x32\x17.google.protobuf.Struct\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\xd4\x03\n\x15IamPolicySearchResult\x12\x10\n\x08resource\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x02 \x01(\t\x12%\n\x06policy\x18\x03 \x01(\x0b\x32\x15.google.iam.v1.Policy\x12M\n\x0b\x65xplanation\x18\x04 \x01(\x0b\x32\x38.google.cloud.asset.v1.IamPolicySearchResult.Explanation\x1a\xa1\x02\n\x0b\x45xplanation\x12m\n\x13matched_permissions\x18\x01 \x03(\x0b\x32P.google.cloud.asset.v1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry\x1a"\n\x0bPermissions\x12\x13\n\x0bpermissions\x18\x01 \x03(\t\x1a\x7f\n\x17MatchedPermissionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12S\n\x05value\x18\x02 \x01(\x0b\x32\x44.google.cloud.asset.v1.IamPolicySearchResult.Explanation.Permissions:\x02\x38\x01\x42\x98\x01\n\x19\x63om.google.cloud.asset.v1B\nAssetProtoP\x01Z:google.golang.org/genproto/googleapis/cloud/asset/v1;asset\xf8\x01\x01\xaa\x02\x15Google.Cloud.Asset.V1\xca\x02\x15Google\\Cloud\\Asset\\V1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_orgpolicy_dot_v1_dot_orgpolicy__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__level__pb2.DESCRIPTOR, - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__policy__pb2.DESCRIPTOR, - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_service__perimeter__pb2.DESCRIPTOR, - google_dot_protobuf_dot_any__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_code__pb2.DESCRIPTOR, - ], -) - - -_TEMPORALASSET_PRIORASSETSTATE = _descriptor.EnumDescriptor( - name="PriorAssetState", - full_name="google.cloud.asset.v1.TemporalAsset.PriorAssetState", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="PRIOR_ASSET_STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PRESENT", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="INVALID", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DOES_NOT_EXIST", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DELETED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=757, - serialized_end=868, -) -_sym_db.RegisterEnumDescriptor(_TEMPORALASSET_PRIORASSETSTATE) - - -_TEMPORALASSET = _descriptor.Descriptor( - name="TemporalAsset", - full_name="google.cloud.asset.v1.TemporalAsset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="window", - full_name="google.cloud.asset.v1.TemporalAsset.window", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="deleted", - full_name="google.cloud.asset.v1.TemporalAsset.deleted", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset", - full_name="google.cloud.asset.v1.TemporalAsset.asset", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="prior_asset_state", - full_name="google.cloud.asset.v1.TemporalAsset.prior_asset_state", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="prior_asset", - full_name="google.cloud.asset.v1.TemporalAsset.prior_asset", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_TEMPORALASSET_PRIORASSETSTATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=495, - serialized_end=868, -) - - -_TIMEWINDOW = _descriptor.Descriptor( - name="TimeWindow", - full_name="google.cloud.asset.v1.TimeWindow", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.cloud.asset.v1.TimeWindow.start_time", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.asset.v1.TimeWindow.end_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=870, - serialized_end=976, -) - - -_ASSET = _descriptor.Descriptor( - name="Asset", - full_name="google.cloud.asset.v1.Asset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="update_time", - full_name="google.cloud.asset.v1.Asset.update_time", - index=0, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1.Asset.name", - index=1, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_type", - full_name="google.cloud.asset.v1.Asset.asset_type", - index=2, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.asset.v1.Asset.resource", - index=3, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="iam_policy", - full_name="google.cloud.asset.v1.Asset.iam_policy", - index=4, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="org_policy", - full_name="google.cloud.asset.v1.Asset.org_policy", - index=5, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="access_policy", - full_name="google.cloud.asset.v1.Asset.access_policy", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="access_level", - full_name="google.cloud.asset.v1.Asset.access_level", - index=7, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="service_perimeter", - full_name="google.cloud.asset.v1.Asset.service_perimeter", - index=8, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ancestors", - full_name="google.cloud.asset.v1.Asset.ancestors", - index=9, - number=10, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352A$\n\037cloudasset.googleapis.com/Asset\022\001*", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="access_context_policy", - full_name="google.cloud.asset.v1.Asset.access_context_policy", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=979, - serialized_end=1549, -) - - -_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.asset.v1.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="version", - full_name="google.cloud.asset.v1.Resource.version", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="discovery_document_uri", - full_name="google.cloud.asset.v1.Resource.discovery_document_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="discovery_name", - full_name="google.cloud.asset.v1.Resource.discovery_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_url", - full_name="google.cloud.asset.v1.Resource.resource_url", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1.Resource.parent", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="data", - full_name="google.cloud.asset.v1.Resource.data", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="location", - full_name="google.cloud.asset.v1.Resource.location", - index=6, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1552, - serialized_end=1730, -) - - -_RESOURCESEARCHRESULT_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.asset.v1.ResourceSearchResult.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.asset.v1.ResourceSearchResult.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.asset.v1.ResourceSearchResult.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2020, - serialized_end=2065, -) - -_RESOURCESEARCHRESULT = _descriptor.Descriptor( - name="ResourceSearchResult", - full_name="google.cloud.asset.v1.ResourceSearchResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1.ResourceSearchResult.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_type", - full_name="google.cloud.asset.v1.ResourceSearchResult.asset_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project", - full_name="google.cloud.asset.v1.ResourceSearchResult.project", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.asset.v1.ResourceSearchResult.display_name", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.asset.v1.ResourceSearchResult.description", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="location", - full_name="google.cloud.asset.v1.ResourceSearchResult.location", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.asset.v1.ResourceSearchResult.labels", - index=6, - number=7, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="network_tags", - full_name="google.cloud.asset.v1.ResourceSearchResult.network_tags", - index=7, - number=8, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="additional_attributes", - full_name="google.cloud.asset.v1.ResourceSearchResult.additional_attributes", - index=8, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_RESOURCESEARCHRESULT_LABELSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1733, - serialized_end=2065, -) - - -_IAMPOLICYSEARCHRESULT_EXPLANATION_PERMISSIONS = _descriptor.Descriptor( - name="Permissions", - full_name="google.cloud.asset.v1.IamPolicySearchResult.Explanation.Permissions", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="permissions", - full_name="google.cloud.asset.v1.IamPolicySearchResult.Explanation.Permissions.permissions", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2373, - serialized_end=2407, -) - -_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY = _descriptor.Descriptor( - name="MatchedPermissionsEntry", - full_name="google.cloud.asset.v1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.asset.v1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.asset.v1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2409, - serialized_end=2536, -) - -_IAMPOLICYSEARCHRESULT_EXPLANATION = _descriptor.Descriptor( - name="Explanation", - full_name="google.cloud.asset.v1.IamPolicySearchResult.Explanation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="matched_permissions", - full_name="google.cloud.asset.v1.IamPolicySearchResult.Explanation.matched_permissions", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _IAMPOLICYSEARCHRESULT_EXPLANATION_PERMISSIONS, - _IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2247, - serialized_end=2536, -) - -_IAMPOLICYSEARCHRESULT = _descriptor.Descriptor( - name="IamPolicySearchResult", - full_name="google.cloud.asset.v1.IamPolicySearchResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.asset.v1.IamPolicySearchResult.resource", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project", - full_name="google.cloud.asset.v1.IamPolicySearchResult.project", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="policy", - full_name="google.cloud.asset.v1.IamPolicySearchResult.policy", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="explanation", - full_name="google.cloud.asset.v1.IamPolicySearchResult.explanation", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_IAMPOLICYSEARCHRESULT_EXPLANATION,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2068, - serialized_end=2536, -) - -_TEMPORALASSET.fields_by_name["window"].message_type = _TIMEWINDOW -_TEMPORALASSET.fields_by_name["asset"].message_type = _ASSET -_TEMPORALASSET.fields_by_name[ - "prior_asset_state" -].enum_type = _TEMPORALASSET_PRIORASSETSTATE -_TEMPORALASSET.fields_by_name["prior_asset"].message_type = _ASSET -_TEMPORALASSET_PRIORASSETSTATE.containing_type = _TEMPORALASSET -_TIMEWINDOW.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_TIMEWINDOW.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name[ - "update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name["resource"].message_type = _RESOURCE -_ASSET.fields_by_name[ - "iam_policy" -].message_type = ( - google_dot_iam_dot_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._POLICY -) -_ASSET.fields_by_name[ - "org_policy" -].message_type = google_dot_cloud_dot_orgpolicy_dot_v1_dot_orgpolicy__pb2._POLICY -_ASSET.fields_by_name[ - "access_policy" -].message_type = ( - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__policy__pb2._ACCESSPOLICY -) -_ASSET.fields_by_name[ - "access_level" -].message_type = ( - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__level__pb2._ACCESSLEVEL -) -_ASSET.fields_by_name[ - "service_perimeter" -].message_type = ( - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_service__perimeter__pb2._SERVICEPERIMETER -) -_ASSET.oneofs_by_name["access_context_policy"].fields.append( - _ASSET.fields_by_name["access_policy"] -) -_ASSET.fields_by_name["access_policy"].containing_oneof = _ASSET.oneofs_by_name[ - "access_context_policy" -] -_ASSET.oneofs_by_name["access_context_policy"].fields.append( - _ASSET.fields_by_name["access_level"] -) -_ASSET.fields_by_name["access_level"].containing_oneof = _ASSET.oneofs_by_name[ - "access_context_policy" -] -_ASSET.oneofs_by_name["access_context_policy"].fields.append( - _ASSET.fields_by_name["service_perimeter"] -) -_ASSET.fields_by_name["service_perimeter"].containing_oneof = _ASSET.oneofs_by_name[ - "access_context_policy" -] -_RESOURCE.fields_by_name[ - "data" -].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_RESOURCESEARCHRESULT_LABELSENTRY.containing_type = _RESOURCESEARCHRESULT -_RESOURCESEARCHRESULT.fields_by_name[ - "labels" -].message_type = _RESOURCESEARCHRESULT_LABELSENTRY -_RESOURCESEARCHRESULT.fields_by_name[ - "additional_attributes" -].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -_IAMPOLICYSEARCHRESULT_EXPLANATION_PERMISSIONS.containing_type = ( - _IAMPOLICYSEARCHRESULT_EXPLANATION -) -_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY.fields_by_name[ - "value" -].message_type = _IAMPOLICYSEARCHRESULT_EXPLANATION_PERMISSIONS -_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY.containing_type = ( - _IAMPOLICYSEARCHRESULT_EXPLANATION -) -_IAMPOLICYSEARCHRESULT_EXPLANATION.fields_by_name[ - "matched_permissions" -].message_type = _IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY -_IAMPOLICYSEARCHRESULT_EXPLANATION.containing_type = _IAMPOLICYSEARCHRESULT -_IAMPOLICYSEARCHRESULT.fields_by_name[ - "policy" -].message_type = ( - google_dot_iam_dot_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._POLICY -) -_IAMPOLICYSEARCHRESULT.fields_by_name[ - "explanation" -].message_type = _IAMPOLICYSEARCHRESULT_EXPLANATION -DESCRIPTOR.message_types_by_name["TemporalAsset"] = _TEMPORALASSET -DESCRIPTOR.message_types_by_name["TimeWindow"] = _TIMEWINDOW -DESCRIPTOR.message_types_by_name["Asset"] = _ASSET -DESCRIPTOR.message_types_by_name["Resource"] = _RESOURCE -DESCRIPTOR.message_types_by_name["ResourceSearchResult"] = _RESOURCESEARCHRESULT -DESCRIPTOR.message_types_by_name["IamPolicySearchResult"] = _IAMPOLICYSEARCHRESULT -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TemporalAsset = _reflection.GeneratedProtocolMessageType( - "TemporalAsset", - (_message.Message,), - { - "DESCRIPTOR": _TEMPORALASSET, - "__module__": "google.cloud.asset_v1.proto.assets_pb2", - "__doc__": """An asset in Google Cloud and its temporal metadata, including the time - window when it was observed and its status during that window. - - Attributes: - window: - The time window when the asset data and state was observed. - deleted: - Whether the asset has been deleted or not. - asset: - An asset in Google Cloud. - prior_asset_state: - State of prior_asset. - prior_asset: - Prior copy of the asset. Populated if prior_asset_state is - PRESENT. Currently this is only set for responses in Real-Time - Feed. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.TemporalAsset) - }, -) -_sym_db.RegisterMessage(TemporalAsset) - -TimeWindow = _reflection.GeneratedProtocolMessageType( - "TimeWindow", - (_message.Message,), - { - "DESCRIPTOR": _TIMEWINDOW, - "__module__": "google.cloud.asset_v1.proto.assets_pb2", - "__doc__": """A time window specified by its ``start_time`` and ``end_time``. - - Attributes: - start_time: - Start time of the time window (exclusive). - end_time: - End time of the time window (inclusive). If not specified, the - current timestamp is used instead. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.TimeWindow) - }, -) -_sym_db.RegisterMessage(TimeWindow) - -Asset = _reflection.GeneratedProtocolMessageType( - "Asset", - (_message.Message,), - { - "DESCRIPTOR": _ASSET, - "__module__": "google.cloud.asset_v1.proto.assets_pb2", - "__doc__": """An asset in Google Cloud. An asset can be any resource in the Google - Cloud `resource hierarchy `__, a resource outside - the Google Cloud resource hierarchy (such as Google Kubernetes Engine - clusters and objects), or a policy (e.g. Cloud IAM policy). See - `Supported asset types `__ for more information. - - Attributes: - update_time: - The last update timestamp of an asset. update_time is updated - when create/update/delete operation is performed. - name: - The full name of the asset. Example: ``//compute.googleapis.co - m/projects/my_project_123/zones/zone1/instances/instance1`` - See `Resource names `__ for more information. - asset_type: - The type of the asset. Example: - ``compute.googleapis.com/Disk`` See `Supported asset types - `__ for more information. - resource: - A representation of the resource. - iam_policy: - A representation of the Cloud IAM policy set on a Google Cloud - resource. There can be a maximum of one Cloud IAM policy set - on any given resource. In addition, Cloud IAM policies inherit - their granted access scope from any policies set on parent - resources in the resource hierarchy. Therefore, the - effectively policy is the union of both the policy set on this - resource and each policy set on all of the resource’s ancestry - resource levels in the hierarchy. See `this topic - `__ - for more information. - org_policy: - A representation of an `organization policy - `__. There can be more - than one organization policy with different constraints set on - a given resource. - access_context_policy: - A representation of an `access policy - `__. - access_policy: - Please also refer to the `access policy user guide - `__. - access_level: - Please also refer to the `access level user guide - `__. - service_perimeter: - Please also refer to the `service perimeter user guide - `__. - ancestors: - The ancestry path of an asset in Google Cloud `resource - hierarchy `__, - represented as a list of relative resource names. An ancestry - path starts with the closest ancestor in the hierarchy and - ends at root. If the asset is a project, folder, or - organization, the ancestry path starts from the asset itself. - Example: ``["projects/123456789", "folders/5432", - "organizations/1234"]`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.Asset) - }, -) -_sym_db.RegisterMessage(Asset) - -Resource = _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _RESOURCE, - "__module__": "google.cloud.asset_v1.proto.assets_pb2", - "__doc__": """A representation of a Google Cloud resource. - - Attributes: - version: - The API version. Example: ``v1`` - discovery_document_uri: - The URL of the discovery document containing the resource’s - JSON schema. Example: ``https://www.googleapis.com/discovery/v - 1/apis/compute/v1/rest`` This value is unspecified for - resources that do not have an API based on a discovery - document, such as Cloud Bigtable. - discovery_name: - The JSON schema name listed in the discovery document. - Example: ``Project`` This value is unspecified for resources - that do not have an API based on a discovery document, such as - Cloud Bigtable. - resource_url: - The REST URL for accessing the resource. An HTTP ``GET`` - request using this URL returns the resource itself. Example: - ``https://cloudresourcemanager.googleapis.com/v1/projects/my- - project-123`` This value is unspecified for resources without - a REST API. - parent: - The full name of the immediate parent of this resource. See - `Resource Names `__ for more information. For - Google Cloud assets, this value is the parent resource defined - in the `Cloud IAM policy hierarchy `__. Example: ``//cloudresou - rcemanager.googleapis.com/projects/my_project_123`` For - third-party assets, this field may be set differently. - data: - The content of the resource, in which some sensitive fields - are removed and may not be present. - location: - The location of the resource in Google Cloud, such as its zone - and region. For more information, see - https://cloud.google.com/about/locations/. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.Resource) - }, -) -_sym_db.RegisterMessage(Resource) - -ResourceSearchResult = _reflection.GeneratedProtocolMessageType( - "ResourceSearchResult", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _RESOURCESEARCHRESULT_LABELSENTRY, - "__module__": "google.cloud.asset_v1.proto.assets_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.ResourceSearchResult.LabelsEntry) - }, - ), - "DESCRIPTOR": _RESOURCESEARCHRESULT, - "__module__": "google.cloud.asset_v1.proto.assets_pb2", - "__doc__": """A result of Resource Search, containing information of a cloud - resoure. - - Attributes: - name: - The full resource name of this resource. Example: ``//compute. - googleapis.com/projects/my_project_123/zones/zone1/instances/i - nstance1``. See `Cloud Asset Inventory Resource Name Format - `__ for more information. To search against the - ``name``: - use a field query. Example: ``name : - "instance1"`` - use a free text query. Example: - ``"instance1"`` - asset_type: - The type of this resource. Example: - ``compute.googleapis.com/Disk``. To search against the - ``asset_type``: - specify the ``asset_type`` field in your - search request. - project: - The project that this resource belongs to, in the form of - projects/{PROJECT_NUMBER}. To search against the ``project``: - - specify the ``scope`` field as this project in your search - request. - display_name: - The display name of this resource. To search against the - ``display_name``: - use a field query. Example: - ``displayName : "My Instance"`` - use a free text query. - Example: ``"My Instance"`` - description: - One or more paragraphs of text description of this resource. - Maximum length could be up to 1M bytes. To search against the - ``description``: - use a field query. Example: ``description - : "*important instance*"`` - use a free text query. Example: - ``"*important instance*"`` - location: - Location can be ``global``, regional like ``us-east1``, or - zonal like ``us-west1-b``. To search against the - ``location``: - use a field query. Example: ``location : - "us-west*"`` - use a free text query. Example: ``"us-west*"`` - labels: - Labels associated with this resource. See `Labelling and - grouping GCP resources - `__ for more - information. To search against the ``labels``: - use a - field query, as following: - query on any label’s key or - value. Example: ``labels : "prod"`` - query by a given - label. Example: ``labels.env : "prod"`` - query by a given - label’sexistence. Example: ``labels.env : *`` - use a free - text query. Example: ``"prod"`` - network_tags: - Network tags associated with this resource. Like labels, - network tags are a type of annotations used to group GCP - resources. See `Labelling GCP resources - `__ for more - information. To search against the ``network_tags``: - use - a field query. Example: ``networkTags : "internal"`` - use a - free text query. Example: ``"internal"`` - additional_attributes: - The additional attributes of this resource. The attributes may - vary from one resource type to another. Examples: - ``projectId`` for Project, ``dnsName`` for DNS ManagedZone. - To search against the ``additional_attributes``: - use a - free text query to match the attributes values. Example: to - search ``additional_attributes = { dnsName: "foobar" }``, you - can issue a query ``"foobar"``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.ResourceSearchResult) - }, -) -_sym_db.RegisterMessage(ResourceSearchResult) -_sym_db.RegisterMessage(ResourceSearchResult.LabelsEntry) - -IamPolicySearchResult = _reflection.GeneratedProtocolMessageType( - "IamPolicySearchResult", - (_message.Message,), - { - "Explanation": _reflection.GeneratedProtocolMessageType( - "Explanation", - (_message.Message,), - { - "Permissions": _reflection.GeneratedProtocolMessageType( - "Permissions", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYSEARCHRESULT_EXPLANATION_PERMISSIONS, - "__module__": "google.cloud.asset_v1.proto.assets_pb2", - "__doc__": """IAM permissions - - Attributes: - permissions: - A list of permissions. A sample permission string: - ``compute.disk.get``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.IamPolicySearchResult.Explanation.Permissions) - }, - ), - "MatchedPermissionsEntry": _reflection.GeneratedProtocolMessageType( - "MatchedPermissionsEntry", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY, - "__module__": "google.cloud.asset_v1.proto.assets_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry) - }, - ), - "DESCRIPTOR": _IAMPOLICYSEARCHRESULT_EXPLANATION, - "__module__": "google.cloud.asset_v1.proto.assets_pb2", - "__doc__": """Explanation about the IAM policy search result. - - Attributes: - matched_permissions: - The map from roles to their included permissions that match - the permission query (i.e., a query containing - ``policy.role.permissions:``). Example: if query - ``policy.role.permissions : "compute.disk.get"`` matches a - policy binding that contains owner role, the - matched_permissions will be ``{"roles/owner": - ["compute.disk.get"]}``. The roles can also be found in the - returned ``policy`` bindings. Note that the map is populated - only for requests with permission queries. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.IamPolicySearchResult.Explanation) - }, - ), - "DESCRIPTOR": _IAMPOLICYSEARCHRESULT, - "__module__": "google.cloud.asset_v1.proto.assets_pb2", - "__doc__": """A result of IAM Policy search, containing information of an IAM - policy. - - Attributes: - resource: - The full resource name of the resource associated with this - IAM policy. Example: ``//compute.googleapis.com/projects/my_pr - oject_123/zones/zone1/instances/instance1``. See `Cloud Asset - Inventory Resource Name Format - `__ for more information. To search against the - ``resource``: - use a field query. Example: ``resource : - "organizations/123"`` - project: - The project that the associated GCP resource belongs to, in - the form of projects/{PROJECT_NUMBER}. If an IAM policy is set - on a resource (like VM instance, Cloud Storage bucket), the - project field will indicate the project that contains the - resource. If an IAM policy is set on a folder or orgnization, - the project field will be empty. To search against the - ``project``: - specify the ``scope`` field as this project - in your search request. - policy: - The IAM policy directly set on the given resource. Note that - the original IAM policy can contain multiple bindings. This - only contains the bindings that match the given query. For - queries that don’t contain a constrain on policies (e.g., an - empty query), this contains all the bindings. To search - against the ``policy`` bindings: - use a field query, as - following: - query by the policy contained members. - Example: ``policy : "amy@gmail.com"`` - query by the - policy contained roles. Example: ``policy : - "roles/compute.admin"`` - query by the policy contained - roles’ implied permissions. Example: - ``policy.role.permissions : "compute.instances.create"`` - explanation: - Explanation about the IAM policy search result. It contains - additional information to explain why the search result - matches the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1.IamPolicySearchResult) - }, -) -_sym_db.RegisterMessage(IamPolicySearchResult) -_sym_db.RegisterMessage(IamPolicySearchResult.Explanation) -_sym_db.RegisterMessage(IamPolicySearchResult.Explanation.Permissions) -_sym_db.RegisterMessage(IamPolicySearchResult.Explanation.MatchedPermissionsEntry) - - -DESCRIPTOR._options = None -_ASSET._options = None -_RESOURCESEARCHRESULT_LABELSENTRY._options = None -_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1/proto/assets_pb2_grpc.py b/google/cloud/asset_v1/proto/assets_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/asset_v1/proto/assets_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/asset_v1/py.typed b/google/cloud/asset_v1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/google/cloud/asset_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/google/cloud/asset_v1/services/__init__.py b/google/cloud/asset_v1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/asset_v1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/__init__.py b/google/cloud/asset_v1/services/asset_service/__init__.py similarity index 71% rename from google/__init__.py rename to google/cloud/asset_v1/services/asset_service/__init__.py index 9a1b64a6..ec3c27d2 100644 --- a/google/__init__.py +++ b/google/cloud/asset_v1/services/asset_service/__init__.py @@ -1,24 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "AssetServiceClient", + "AssetServiceAsyncClient", +) diff --git a/google/cloud/asset_v1/services/asset_service/async_client.py b/google/cloud/asset_v1/services/asset_service/async_client.py new file mode 100644 index 00000000..43b5a6e0 --- /dev/null +++ b/google/cloud/asset_v1/services/asset_service/async_client.py @@ -0,0 +1,933 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.asset_v1.services.asset_service import pagers +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets +from google.type import expr_pb2 as expr # type: ignore + +from .transports.base import AssetServiceTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + feed_path = staticmethod(AssetServiceClient.feed_path) + + from_service_account_file = AssetServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(AssetServiceClient).get_transport_class, type(AssetServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = AssetServiceClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def export_assets( + self, + request: asset_service.ExportAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports assets with time and resource types to a given Cloud + Storage location/BigQuery table. For Cloud Storage location + destinations, the output format is newline-delimited JSON. Each + line represents a + [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in + the JSON format; for BigQuery table destinations, the output + table stores the fields in asset proto as columns. This API + implements the + [google.longrunning.Operation][google.longrunning.Operation] API + , which allows you to keep track of the export. We recommend + intervals of at least 2 seconds with exponential retry to poll + the export operation result. For regular-size resource parent, + the export operation usually finishes within 5 minutes. + + Args: + request (:class:`~.asset_service.ExportAssetsRequest`): + The request object. Export asset request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.asset_service.ExportAssetsResponse``: The + export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + + request = asset_service.ExportAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_assets, + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # 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, + asset_service.ExportAssetsResponse, + metadata_type=asset_service.ExportAssetsRequest, + ) + + # Done; return the response. + return response + + async def batch_get_assets_history( + self, + request: asset_service.BatchGetAssetsHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: + r"""Batch gets the update history of assets that overlap a time + window. For IAM_POLICY content, this API outputs history when + the asset and its attached IAM POLICY both exist. This can + create gaps in the output history. Otherwise, this API outputs + history with asset in both non-delete or deleted status. If a + specified asset does not exist, this API returns an + INVALID_ARGUMENT error. + + Args: + request (:class:`~.asset_service.BatchGetAssetsHistoryRequest`): + The request object. Batch get assets history request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.BatchGetAssetsHistoryResponse: + Batch get assets history response. + """ + # Create or coerce a protobuf request object. + + request = asset_service.BatchGetAssetsHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_get_assets_history, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_feed( + self, + request: asset_service.CreateFeedRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Args: + request (:class:`~.asset_service.CreateFeedRequest`): + The request object. Create asset feed request. + parent (:class:`str`): + Required. The name of the + project/folder/organization where this + feed should be created in. It can only + be an organization number (such as + "organizations/123"), a folder number + (such as "folders/123"), a project ID + (such as "projects/my-project-id")", or + a project number (such as + "projects/12345"). + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.CreateFeedRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_feed, + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_feed( + self, + request: asset_service.GetFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + Args: + request (:class:`~.asset_service.GetFeedRequest`): + The request object. Get asset feed request. + name (:class:`str`): + Required. The name of the Feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.GetFeedRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_feed, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_feeds( + self, + request: asset_service.ListFeedsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + Args: + request (:class:`~.asset_service.ListFeedsRequest`): + The request object. List asset feeds request. + parent (:class:`str`): + Required. The parent + project/folder/organization whose feeds + are to be listed. It can only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListFeedsResponse: + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.ListFeedsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_feeds, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_feed( + self, + request: asset_service.UpdateFeedRequest = None, + *, + feed: asset_service.Feed = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + Args: + request (:class:`~.asset_service.UpdateFeedRequest`): + The request object. Update asset feed request. + feed (:class:`~.asset_service.Feed`): + Required. The new values of feed details. It must match + an existing feed and the field ``name`` must be in the + format of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + This corresponds to the ``feed`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([feed]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.UpdateFeedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if feed is not None: + request.feed = feed + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_feed, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("feed.name", request.feed.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_feed( + self, + request: asset_service.DeleteFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an asset feed. + + Args: + request (:class:`~.asset_service.DeleteFeedRequest`): + The request object. + name (:class:`str`): + Required. The name of the feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.DeleteFeedRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_feed, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def search_all_resources( + self, + request: asset_service.SearchAllResourcesRequest = None, + *, + scope: str = None, + query: str = None, + asset_types: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesAsyncPager: + r"""Searches all the resources within the given + accessible scope (e.g., a project, a folder or an + organization). Callers should have + cloud.assets.SearchAllResources permission upon the + requested scope, otherwise the request will be rejected. + + Args: + request (:class:`~.asset_service.SearchAllResourcesRequest`): + The request object. Search all resources request. + scope (:class:`str`): + Required. A scope can be a project, a folder or an + organization. The search is limited to the resources + within the ``scope``. + + The allowed values are: + + - projects/{PROJECT_ID} + - projects/{PROJECT_NUMBER} + - folders/{FOLDER_NUMBER} + - organizations/{ORGANIZATION_NUMBER} + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. An empty query can be + specified to search all the resources of certain + ``asset_types`` within the given ``scope``. + + Examples: + + - ``name : "Important"`` to find Cloud resources whose + name contains "Important" as a word. + - ``displayName : "Impor*"`` to find Cloud resources + whose display name contains "Impor" as a word prefix. + - ``description : "*por*"`` to find Cloud resources + whose description contains "por" as a substring. + - ``location : "us-west*"`` to find Cloud resources + whose location is prefixed with "us-west". + - ``labels : "prod"`` to find Cloud resources whose + labels contain "prod" as a key or value. + - ``labels.env : "prod"`` to find Cloud resources which + have a label "env" and its value is "prod". + - ``labels.env : *`` to find Cloud resources which have + a label "env". + - ``"Important"`` to find Cloud resources which contain + "Important" as a word in any of the searchable + fields. + - ``"Impor*"`` to find Cloud resources which contain + "Impor" as a word prefix in any of the searchable + fields. + - ``"*por*"`` to find Cloud resources which contain + "por" as a substring in any of the searchable fields. + - ``("Important" AND location : ("us-west1" OR "global"))`` + to find Cloud resources which contain "Important" as + a word in any of the searchable fields and are also + located in the "us-west1" region or the "global" + location. + + See `how to construct a + query `__ + for more details. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_types (:class:`Sequence[str]`): + Optional. A list of asset types that this request + searches for. If empty, it will search all the + `searchable asset + types `__. + This corresponds to the ``asset_types`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.SearchAllResourcesAsyncPager: + Search all resources response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([scope, query, asset_types]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.SearchAllResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + if asset_types is not None: + request.asset_types = asset_types + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_all_resources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=15.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + ) + + # 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.SearchAllResourcesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_all_iam_policies( + self, + request: asset_service.SearchAllIamPoliciesRequest = None, + *, + scope: str = None, + query: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesAsyncPager: + r"""Searches all the IAM policies within the given + accessible scope (e.g., a project, a folder or an + organization). Callers should have + cloud.assets.SearchAllIamPolicies permission upon the + requested scope, otherwise the request will be rejected. + + Args: + request (:class:`~.asset_service.SearchAllIamPoliciesRequest`): + The request object. Search all IAM policies request. + scope (:class:`str`): + Required. A scope can be a project, a folder or an + organization. The search is limited to the IAM policies + within the ``scope``. + + The allowed values are: + + - projects/{PROJECT_ID} + - projects/{PROJECT_NUMBER} + - folders/{FOLDER_NUMBER} + - organizations/{ORGANIZATION_NUMBER} + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. An empty query can be + specified to search all the IAM policies within the + given ``scope``. + + Examples: + + - ``policy : "amy@gmail.com"`` to find Cloud IAM policy + bindings that specify user "amy@gmail.com". + - ``policy : "roles/compute.admin"`` to find Cloud IAM + policy bindings that specify the Compute Admin role. + - ``policy.role.permissions : "storage.buckets.update"`` + to find Cloud IAM policy bindings that specify a role + containing "storage.buckets.update" permission. + - ``resource : "organizations/123"`` to find Cloud IAM + policy bindings that are set on "organizations/123". + - ``(resource : ("organizations/123" OR "folders/1234") AND policy : "amy")`` + to find Cloud IAM policy bindings that are set on + "organizations/123" or "folders/1234", and also + specify user "amy". + + See `how to construct a + query `__ + for more details. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.SearchAllIamPoliciesAsyncPager: + Search all IAM policies response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([scope, query]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.SearchAllIamPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_all_iam_policies, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=15.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + ) + + # 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.SearchAllIamPoliciesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceAsyncClient",) diff --git a/google/cloud/asset_v1/services/asset_service/client.py b/google/cloud/asset_v1/services/asset_service/client.py new file mode 100644 index 00000000..78a19f13 --- /dev/null +++ b/google/cloud/asset_v1/services/asset_service/client.py @@ -0,0 +1,1034 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.asset_v1.services.asset_service import pagers +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets +from google.type import expr_pb2 as expr # type: ignore + +from .transports.base import AssetServiceTransport +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudasset.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def feed_path(project: str, feed: str,) -> str: + """Return a fully-qualified feed string.""" + return "projects/{project}/feeds/{feed}".format(project=project, feed=feed,) + + @staticmethod + def parse_feed_path(path: str) -> Dict[str, str]: + """Parse a feed path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AssetServiceTransport): + # transport is a AssetServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def export_assets( + self, + request: asset_service.ExportAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports assets with time and resource types to a given Cloud + Storage location/BigQuery table. For Cloud Storage location + destinations, the output format is newline-delimited JSON. Each + line represents a + [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in + the JSON format; for BigQuery table destinations, the output + table stores the fields in asset proto as columns. This API + implements the + [google.longrunning.Operation][google.longrunning.Operation] API + , which allows you to keep track of the export. We recommend + intervals of at least 2 seconds with exponential retry to poll + the export operation result. For regular-size resource parent, + the export operation usually finishes within 5 minutes. + + Args: + request (:class:`~.asset_service.ExportAssetsRequest`): + The request object. Export asset request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.asset_service.ExportAssetsResponse``: The + export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.ExportAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ExportAssetsRequest): + request = asset_service.ExportAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_assets] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + asset_service.ExportAssetsResponse, + metadata_type=asset_service.ExportAssetsRequest, + ) + + # Done; return the response. + return response + + def batch_get_assets_history( + self, + request: asset_service.BatchGetAssetsHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: + r"""Batch gets the update history of assets that overlap a time + window. For IAM_POLICY content, this API outputs history when + the asset and its attached IAM POLICY both exist. This can + create gaps in the output history. Otherwise, this API outputs + history with asset in both non-delete or deleted status. If a + specified asset does not exist, this API returns an + INVALID_ARGUMENT error. + + Args: + request (:class:`~.asset_service.BatchGetAssetsHistoryRequest`): + The request object. Batch get assets history request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.BatchGetAssetsHistoryResponse: + Batch get assets history response. + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.BatchGetAssetsHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.BatchGetAssetsHistoryRequest): + request = asset_service.BatchGetAssetsHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_get_assets_history] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_feed( + self, + request: asset_service.CreateFeedRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Args: + request (:class:`~.asset_service.CreateFeedRequest`): + The request object. Create asset feed request. + parent (:class:`str`): + Required. The name of the + project/folder/organization where this + feed should be created in. It can only + be an organization number (such as + "organizations/123"), a folder number + (such as "folders/123"), a project ID + (such as "projects/my-project-id")", or + a project number (such as + "projects/12345"). + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.CreateFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.CreateFeedRequest): + request = asset_service.CreateFeedRequest(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._transport._wrapped_methods[self._transport.create_feed] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_feed( + self, + request: asset_service.GetFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + Args: + request (:class:`~.asset_service.GetFeedRequest`): + The request object. Get asset feed request. + name (:class:`str`): + Required. The name of the Feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.GetFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.GetFeedRequest): + request = asset_service.GetFeedRequest(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._transport._wrapped_methods[self._transport.get_feed] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_feeds( + self, + request: asset_service.ListFeedsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + Args: + request (:class:`~.asset_service.ListFeedsRequest`): + The request object. List asset feeds request. + parent (:class:`str`): + Required. The parent + project/folder/organization whose feeds + are to be listed. It can only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListFeedsResponse: + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.ListFeedsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ListFeedsRequest): + request = asset_service.ListFeedsRequest(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._transport._wrapped_methods[self._transport.list_feeds] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_feed( + self, + request: asset_service.UpdateFeedRequest = None, + *, + feed: asset_service.Feed = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + Args: + request (:class:`~.asset_service.UpdateFeedRequest`): + The request object. Update asset feed request. + feed (:class:`~.asset_service.Feed`): + Required. The new values of feed details. It must match + an existing feed and the field ``name`` must be in the + format of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + This corresponds to the ``feed`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([feed]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.UpdateFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.UpdateFeedRequest): + request = asset_service.UpdateFeedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if feed is not None: + request.feed = feed + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_feed] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("feed.name", request.feed.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_feed( + self, + request: asset_service.DeleteFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an asset feed. + + Args: + request (:class:`~.asset_service.DeleteFeedRequest`): + The request object. + name (:class:`str`): + Required. The name of the feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.DeleteFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.DeleteFeedRequest): + request = asset_service.DeleteFeedRequest(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._transport._wrapped_methods[self._transport.delete_feed] + + # 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),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def search_all_resources( + self, + request: asset_service.SearchAllResourcesRequest = None, + *, + scope: str = None, + query: str = None, + asset_types: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesPager: + r"""Searches all the resources within the given + accessible scope (e.g., a project, a folder or an + organization). Callers should have + cloud.assets.SearchAllResources permission upon the + requested scope, otherwise the request will be rejected. + + Args: + request (:class:`~.asset_service.SearchAllResourcesRequest`): + The request object. Search all resources request. + scope (:class:`str`): + Required. A scope can be a project, a folder or an + organization. The search is limited to the resources + within the ``scope``. + + The allowed values are: + + - projects/{PROJECT_ID} + - projects/{PROJECT_NUMBER} + - folders/{FOLDER_NUMBER} + - organizations/{ORGANIZATION_NUMBER} + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. An empty query can be + specified to search all the resources of certain + ``asset_types`` within the given ``scope``. + + Examples: + + - ``name : "Important"`` to find Cloud resources whose + name contains "Important" as a word. + - ``displayName : "Impor*"`` to find Cloud resources + whose display name contains "Impor" as a word prefix. + - ``description : "*por*"`` to find Cloud resources + whose description contains "por" as a substring. + - ``location : "us-west*"`` to find Cloud resources + whose location is prefixed with "us-west". + - ``labels : "prod"`` to find Cloud resources whose + labels contain "prod" as a key or value. + - ``labels.env : "prod"`` to find Cloud resources which + have a label "env" and its value is "prod". + - ``labels.env : *`` to find Cloud resources which have + a label "env". + - ``"Important"`` to find Cloud resources which contain + "Important" as a word in any of the searchable + fields. + - ``"Impor*"`` to find Cloud resources which contain + "Impor" as a word prefix in any of the searchable + fields. + - ``"*por*"`` to find Cloud resources which contain + "por" as a substring in any of the searchable fields. + - ``("Important" AND location : ("us-west1" OR "global"))`` + to find Cloud resources which contain "Important" as + a word in any of the searchable fields and are also + located in the "us-west1" region or the "global" + location. + + See `how to construct a + query `__ + for more details. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_types (:class:`Sequence[str]`): + Optional. A list of asset types that this request + searches for. If empty, it will search all the + `searchable asset + types `__. + This corresponds to the ``asset_types`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.SearchAllResourcesPager: + Search all resources response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scope, query, asset_types]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.SearchAllResourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.SearchAllResourcesRequest): + request = asset_service.SearchAllResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + if asset_types is not None: + request.asset_types = asset_types + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_all_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchAllResourcesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def search_all_iam_policies( + self, + request: asset_service.SearchAllIamPoliciesRequest = None, + *, + scope: str = None, + query: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesPager: + r"""Searches all the IAM policies within the given + accessible scope (e.g., a project, a folder or an + organization). Callers should have + cloud.assets.SearchAllIamPolicies permission upon the + requested scope, otherwise the request will be rejected. + + Args: + request (:class:`~.asset_service.SearchAllIamPoliciesRequest`): + The request object. Search all IAM policies request. + scope (:class:`str`): + Required. A scope can be a project, a folder or an + organization. The search is limited to the IAM policies + within the ``scope``. + + The allowed values are: + + - projects/{PROJECT_ID} + - projects/{PROJECT_NUMBER} + - folders/{FOLDER_NUMBER} + - organizations/{ORGANIZATION_NUMBER} + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. An empty query can be + specified to search all the IAM policies within the + given ``scope``. + + Examples: + + - ``policy : "amy@gmail.com"`` to find Cloud IAM policy + bindings that specify user "amy@gmail.com". + - ``policy : "roles/compute.admin"`` to find Cloud IAM + policy bindings that specify the Compute Admin role. + - ``policy.role.permissions : "storage.buckets.update"`` + to find Cloud IAM policy bindings that specify a role + containing "storage.buckets.update" permission. + - ``resource : "organizations/123"`` to find Cloud IAM + policy bindings that are set on "organizations/123". + - ``(resource : ("organizations/123" OR "folders/1234") AND policy : "amy")`` + to find Cloud IAM policy bindings that are set on + "organizations/123" or "folders/1234", and also + specify user "amy". + + See `how to construct a + query `__ + for more details. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.SearchAllIamPoliciesPager: + Search all IAM policies response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scope, query]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.SearchAllIamPoliciesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.SearchAllIamPoliciesRequest): + request = asset_service.SearchAllIamPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_all_iam_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchAllIamPoliciesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceClient",) diff --git a/google/cloud/asset_v1/services/asset_service/pagers.py b/google/cloud/asset_v1/services/asset_service/pagers.py new file mode 100644 index 00000000..84531887 --- /dev/null +++ b/google/cloud/asset_v1/services/asset_service/pagers.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets + + +class SearchAllResourcesPager: + """A pager for iterating through ``search_all_resources`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.SearchAllResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAllResources`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.SearchAllResourcesResponse` + 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[..., asset_service.SearchAllResourcesResponse], + request: asset_service.SearchAllResourcesRequest, + response: asset_service.SearchAllResourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.SearchAllResourcesRequest`): + The initial request object. + response (:class:`~.asset_service.SearchAllResourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.SearchAllResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[asset_service.SearchAllResourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[assets.ResourceSearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchAllResourcesAsyncPager: + """A pager for iterating through ``search_all_resources`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.SearchAllResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAllResources`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.SearchAllResourcesResponse` + 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[asset_service.SearchAllResourcesResponse]], + request: asset_service.SearchAllResourcesRequest, + response: asset_service.SearchAllResourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.SearchAllResourcesRequest`): + The initial request object. + response (:class:`~.asset_service.SearchAllResourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.SearchAllResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[asset_service.SearchAllResourcesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[assets.ResourceSearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchAllIamPoliciesPager: + """A pager for iterating through ``search_all_iam_policies`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.SearchAllIamPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAllIamPolicies`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.SearchAllIamPoliciesResponse` + 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[..., asset_service.SearchAllIamPoliciesResponse], + request: asset_service.SearchAllIamPoliciesRequest, + response: asset_service.SearchAllIamPoliciesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.SearchAllIamPoliciesRequest`): + The initial request object. + response (:class:`~.asset_service.SearchAllIamPoliciesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.SearchAllIamPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[asset_service.SearchAllIamPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[assets.IamPolicySearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchAllIamPoliciesAsyncPager: + """A pager for iterating through ``search_all_iam_policies`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.SearchAllIamPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAllIamPolicies`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.SearchAllIamPoliciesResponse` + 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[asset_service.SearchAllIamPoliciesResponse]], + request: asset_service.SearchAllIamPoliciesRequest, + response: asset_service.SearchAllIamPoliciesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.SearchAllIamPoliciesRequest`): + The initial request object. + response (:class:`~.asset_service.SearchAllIamPoliciesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.SearchAllIamPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[asset_service.SearchAllIamPoliciesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[assets.IamPolicySearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/asset_v1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..624eab74 --- /dev/null +++ b/google/cloud/asset_v1/services/asset_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry["grpc"] = AssetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + +__all__ = ( + "AssetServiceTransport", + "AssetServiceGrpcTransport", + "AssetServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/asset_v1/services/asset_service/transports/base.py b/google/cloud/asset_v1/services/asset_service/transports/base.py new file mode 100644 index 00000000..63023b00 --- /dev/null +++ b/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -0,0 +1,292 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.asset_v1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.export_assets: gapic_v1.method.wrap_method( + self.export_assets, default_timeout=60.0, client_info=_client_info, + ), + self.batch_get_assets_history: gapic_v1.method.wrap_method( + self.batch_get_assets_history, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.create_feed: gapic_v1.method.wrap_method( + self.create_feed, default_timeout=60.0, client_info=_client_info, + ), + self.get_feed: gapic_v1.method.wrap_method( + self.get_feed, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.list_feeds: gapic_v1.method.wrap_method( + self.list_feeds, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_feed: gapic_v1.method.wrap_method( + self.update_feed, default_timeout=60.0, client_info=_client_info, + ), + self.delete_feed: gapic_v1.method.wrap_method( + self.delete_feed, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.search_all_resources: gapic_v1.method.wrap_method( + self.search_all_resources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=15.0, + client_info=_client_info, + ), + self.search_all_iam_policies: gapic_v1.method.wrap_method( + self.search_all_iam_policies, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=15.0, + client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def export_assets( + self, + ) -> typing.Callable[ + [asset_service.ExportAssetsRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def batch_get_assets_history( + self, + ) -> typing.Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + typing.Union[ + asset_service.BatchGetAssetsHistoryResponse, + typing.Awaitable[asset_service.BatchGetAssetsHistoryResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_feed( + self, + ) -> typing.Callable[ + [asset_service.CreateFeedRequest], + typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + ]: + raise NotImplementedError() + + @property + def get_feed( + self, + ) -> typing.Callable[ + [asset_service.GetFeedRequest], + typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + ]: + raise NotImplementedError() + + @property + def list_feeds( + self, + ) -> typing.Callable[ + [asset_service.ListFeedsRequest], + typing.Union[ + asset_service.ListFeedsResponse, + typing.Awaitable[asset_service.ListFeedsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_feed( + self, + ) -> typing.Callable[ + [asset_service.UpdateFeedRequest], + typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + ]: + raise NotImplementedError() + + @property + def delete_feed( + self, + ) -> typing.Callable[ + [asset_service.DeleteFeedRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def search_all_resources( + self, + ) -> typing.Callable[ + [asset_service.SearchAllResourcesRequest], + typing.Union[ + asset_service.SearchAllResourcesResponse, + typing.Awaitable[asset_service.SearchAllResourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def search_all_iam_policies( + self, + ) -> typing.Callable[ + [asset_service.SearchAllIamPoliciesRequest], + typing.Union[ + asset_service.SearchAllIamPoliciesResponse, + typing.Awaitable[asset_service.SearchAllIamPoliciesResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("AssetServiceTransport",) diff --git a/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..fb8f711c --- /dev/null +++ b/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -0,0 +1,494 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.asset_v1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import AssetServiceTransport + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + 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. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def export_assets( + self, + ) -> Callable[[asset_service.ExportAssetsRequest], operations.Operation]: + r"""Return a callable for the export assets method over gRPC. + + Exports assets with time and resource types to a given Cloud + Storage location/BigQuery table. For Cloud Storage location + destinations, the output format is newline-delimited JSON. Each + line represents a + [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in + the JSON format; for BigQuery table destinations, the output + table stores the fields in asset proto as columns. This API + implements the + [google.longrunning.Operation][google.longrunning.Operation] API + , which allows you to keep track of the export. We recommend + intervals of at least 2 seconds with exponential retry to poll + the export operation result. For regular-size resource parent, + the export operation usually finishes within 5 minutes. + + Returns: + Callable[[~.ExportAssetsRequest], + ~.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 "export_assets" not in self._stubs: + self._stubs["export_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/ExportAssets", + request_serializer=asset_service.ExportAssetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["export_assets"] + + @property + def batch_get_assets_history( + self, + ) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + asset_service.BatchGetAssetsHistoryResponse, + ]: + r"""Return a callable for the batch get assets history method over gRPC. + + Batch gets the update history of assets that overlap a time + window. For IAM_POLICY content, this API outputs history when + the asset and its attached IAM POLICY both exist. This can + create gaps in the output history. Otherwise, this API outputs + history with asset in both non-delete or deleted status. If a + specified asset does not exist, this API returns an + INVALID_ARGUMENT error. + + Returns: + Callable[[~.BatchGetAssetsHistoryRequest], + ~.BatchGetAssetsHistoryResponse]: + 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 "batch_get_assets_history" not in self._stubs: + self._stubs["batch_get_assets_history"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory", + request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, + response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, + ) + return self._stubs["batch_get_assets_history"] + + @property + def create_feed( + self, + ) -> Callable[[asset_service.CreateFeedRequest], asset_service.Feed]: + r"""Return a callable for the create feed method over gRPC. + + Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Returns: + Callable[[~.CreateFeedRequest], + ~.Feed]: + 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_feed" not in self._stubs: + self._stubs["create_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/CreateFeed", + request_serializer=asset_service.CreateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["create_feed"] + + @property + def get_feed(self) -> Callable[[asset_service.GetFeedRequest], asset_service.Feed]: + r"""Return a callable for the get feed method over gRPC. + + Gets details about an asset feed. + + Returns: + Callable[[~.GetFeedRequest], + ~.Feed]: + 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_feed" not in self._stubs: + self._stubs["get_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/GetFeed", + request_serializer=asset_service.GetFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["get_feed"] + + @property + def list_feeds( + self, + ) -> Callable[[asset_service.ListFeedsRequest], asset_service.ListFeedsResponse]: + r"""Return a callable for the list feeds method over gRPC. + + Lists all asset feeds in a parent + project/folder/organization. + + Returns: + Callable[[~.ListFeedsRequest], + ~.ListFeedsResponse]: + 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_feeds" not in self._stubs: + self._stubs["list_feeds"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/ListFeeds", + request_serializer=asset_service.ListFeedsRequest.serialize, + response_deserializer=asset_service.ListFeedsResponse.deserialize, + ) + return self._stubs["list_feeds"] + + @property + def update_feed( + self, + ) -> Callable[[asset_service.UpdateFeedRequest], asset_service.Feed]: + r"""Return a callable for the update feed method over gRPC. + + Updates an asset feed configuration. + + Returns: + Callable[[~.UpdateFeedRequest], + ~.Feed]: + 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_feed" not in self._stubs: + self._stubs["update_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/UpdateFeed", + request_serializer=asset_service.UpdateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["update_feed"] + + @property + def delete_feed(self) -> Callable[[asset_service.DeleteFeedRequest], empty.Empty]: + r"""Return a callable for the delete feed method over gRPC. + + Deletes an asset feed. + + Returns: + Callable[[~.DeleteFeedRequest], + ~.Empty]: + 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_feed" not in self._stubs: + self._stubs["delete_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/DeleteFeed", + request_serializer=asset_service.DeleteFeedRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_feed"] + + @property + def search_all_resources( + self, + ) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse, + ]: + r"""Return a callable for the search all resources method over gRPC. + + Searches all the resources within the given + accessible scope (e.g., a project, a folder or an + organization). Callers should have + cloud.assets.SearchAllResources permission upon the + requested scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllResourcesRequest], + ~.SearchAllResourcesResponse]: + 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_all_resources" not in self._stubs: + self._stubs["search_all_resources"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/SearchAllResources", + request_serializer=asset_service.SearchAllResourcesRequest.serialize, + response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, + ) + return self._stubs["search_all_resources"] + + @property + def search_all_iam_policies( + self, + ) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse, + ]: + r"""Return a callable for the search all iam policies method over gRPC. + + Searches all the IAM policies within the given + accessible scope (e.g., a project, a folder or an + organization). Callers should have + cloud.assets.SearchAllIamPolicies permission upon the + requested scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllIamPoliciesRequest], + ~.SearchAllIamPoliciesResponse]: + 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_all_iam_policies" not in self._stubs: + self._stubs["search_all_iam_policies"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/SearchAllIamPolicies", + request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, + response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, + ) + return self._stubs["search_all_iam_policies"] + + +__all__ = ("AssetServiceGrpcTransport",) diff --git a/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..871696a0 --- /dev/null +++ b/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,493 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: 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: + address (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 ignored if ``channel`` 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`. + 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # 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. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def export_assets( + self, + ) -> Callable[[asset_service.ExportAssetsRequest], Awaitable[operations.Operation]]: + r"""Return a callable for the export assets method over gRPC. + + Exports assets with time and resource types to a given Cloud + Storage location/BigQuery table. For Cloud Storage location + destinations, the output format is newline-delimited JSON. Each + line represents a + [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in + the JSON format; for BigQuery table destinations, the output + table stores the fields in asset proto as columns. This API + implements the + [google.longrunning.Operation][google.longrunning.Operation] API + , which allows you to keep track of the export. We recommend + intervals of at least 2 seconds with exponential retry to poll + the export operation result. For regular-size resource parent, + the export operation usually finishes within 5 minutes. + + Returns: + Callable[[~.ExportAssetsRequest], + 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 "export_assets" not in self._stubs: + self._stubs["export_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/ExportAssets", + request_serializer=asset_service.ExportAssetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["export_assets"] + + @property + def batch_get_assets_history( + self, + ) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + Awaitable[asset_service.BatchGetAssetsHistoryResponse], + ]: + r"""Return a callable for the batch get assets history method over gRPC. + + Batch gets the update history of assets that overlap a time + window. For IAM_POLICY content, this API outputs history when + the asset and its attached IAM POLICY both exist. This can + create gaps in the output history. Otherwise, this API outputs + history with asset in both non-delete or deleted status. If a + specified asset does not exist, this API returns an + INVALID_ARGUMENT error. + + Returns: + Callable[[~.BatchGetAssetsHistoryRequest], + Awaitable[~.BatchGetAssetsHistoryResponse]]: + 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 "batch_get_assets_history" not in self._stubs: + self._stubs["batch_get_assets_history"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory", + request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, + response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, + ) + return self._stubs["batch_get_assets_history"] + + @property + def create_feed( + self, + ) -> Callable[[asset_service.CreateFeedRequest], Awaitable[asset_service.Feed]]: + r"""Return a callable for the create feed method over gRPC. + + Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Returns: + Callable[[~.CreateFeedRequest], + Awaitable[~.Feed]]: + 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_feed" not in self._stubs: + self._stubs["create_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/CreateFeed", + request_serializer=asset_service.CreateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["create_feed"] + + @property + def get_feed( + self, + ) -> Callable[[asset_service.GetFeedRequest], Awaitable[asset_service.Feed]]: + r"""Return a callable for the get feed method over gRPC. + + Gets details about an asset feed. + + Returns: + Callable[[~.GetFeedRequest], + Awaitable[~.Feed]]: + 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_feed" not in self._stubs: + self._stubs["get_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/GetFeed", + request_serializer=asset_service.GetFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["get_feed"] + + @property + def list_feeds( + self, + ) -> Callable[ + [asset_service.ListFeedsRequest], Awaitable[asset_service.ListFeedsResponse] + ]: + r"""Return a callable for the list feeds method over gRPC. + + Lists all asset feeds in a parent + project/folder/organization. + + Returns: + Callable[[~.ListFeedsRequest], + Awaitable[~.ListFeedsResponse]]: + 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_feeds" not in self._stubs: + self._stubs["list_feeds"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/ListFeeds", + request_serializer=asset_service.ListFeedsRequest.serialize, + response_deserializer=asset_service.ListFeedsResponse.deserialize, + ) + return self._stubs["list_feeds"] + + @property + def update_feed( + self, + ) -> Callable[[asset_service.UpdateFeedRequest], Awaitable[asset_service.Feed]]: + r"""Return a callable for the update feed method over gRPC. + + Updates an asset feed configuration. + + Returns: + Callable[[~.UpdateFeedRequest], + Awaitable[~.Feed]]: + 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_feed" not in self._stubs: + self._stubs["update_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/UpdateFeed", + request_serializer=asset_service.UpdateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["update_feed"] + + @property + def delete_feed( + self, + ) -> Callable[[asset_service.DeleteFeedRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete feed method over gRPC. + + Deletes an asset feed. + + Returns: + Callable[[~.DeleteFeedRequest], + Awaitable[~.Empty]]: + 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_feed" not in self._stubs: + self._stubs["delete_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/DeleteFeed", + request_serializer=asset_service.DeleteFeedRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_feed"] + + @property + def search_all_resources( + self, + ) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Awaitable[asset_service.SearchAllResourcesResponse], + ]: + r"""Return a callable for the search all resources method over gRPC. + + Searches all the resources within the given + accessible scope (e.g., a project, a folder or an + organization). Callers should have + cloud.assets.SearchAllResources permission upon the + requested scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllResourcesRequest], + Awaitable[~.SearchAllResourcesResponse]]: + 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_all_resources" not in self._stubs: + self._stubs["search_all_resources"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/SearchAllResources", + request_serializer=asset_service.SearchAllResourcesRequest.serialize, + response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, + ) + return self._stubs["search_all_resources"] + + @property + def search_all_iam_policies( + self, + ) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Awaitable[asset_service.SearchAllIamPoliciesResponse], + ]: + r"""Return a callable for the search all iam policies method over gRPC. + + Searches all the IAM policies within the given + accessible scope (e.g., a project, a folder or an + organization). Callers should have + cloud.assets.SearchAllIamPolicies permission upon the + requested scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllIamPoliciesRequest], + Awaitable[~.SearchAllIamPoliciesResponse]]: + 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_all_iam_policies" not in self._stubs: + self._stubs["search_all_iam_policies"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1.AssetService/SearchAllIamPolicies", + request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, + response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, + ) + return self._stubs["search_all_iam_policies"] + + +__all__ = ("AssetServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/asset_v1/types.py b/google/cloud/asset_v1/types.py deleted file mode 100644 index dcb5e9e0..00000000 --- a/google/cloud/asset_v1/types.py +++ /dev/null @@ -1,74 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.identity.accesscontextmanager.v1 import access_level_pb2 -from google.identity.accesscontextmanager.v1 import access_policy_pb2 -from google.cloud.asset_v1.proto import asset_service_pb2 -from google.cloud.asset_v1.proto import assets_pb2 -from google.cloud.orgpolicy.v1 import orgpolicy_pb2 -from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import struct_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - access_level_pb2, - access_policy_pb2, - orgpolicy_pb2, - service_perimeter_pb2, - policy_pb2, - operations_pb2, - any_pb2, - empty_pb2, - field_mask_pb2, - struct_pb2, - timestamp_pb2, - status_pb2, - expr_pb2, -] - -_local_modules = [ - asset_service_pb2, - assets_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.asset_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/asset_v1/types/__init__.py b/google/cloud/asset_v1/types/__init__.py new file mode 100644 index 00000000..f8cb1cd8 --- /dev/null +++ b/google/cloud/asset_v1/types/__init__.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .assets import ( + TemporalAsset, + TimeWindow, + Asset, + Resource, + ResourceSearchResult, + IamPolicySearchResult, +) +from .asset_service import ( + ExportAssetsRequest, + ExportAssetsResponse, + BatchGetAssetsHistoryRequest, + BatchGetAssetsHistoryResponse, + CreateFeedRequest, + GetFeedRequest, + ListFeedsRequest, + ListFeedsResponse, + UpdateFeedRequest, + DeleteFeedRequest, + OutputConfig, + GcsDestination, + BigQueryDestination, + PubsubDestination, + FeedOutputConfig, + Feed, + SearchAllResourcesRequest, + SearchAllResourcesResponse, + SearchAllIamPoliciesRequest, + SearchAllIamPoliciesResponse, +) + + +__all__ = ( + "TemporalAsset", + "TimeWindow", + "Asset", + "Resource", + "ResourceSearchResult", + "IamPolicySearchResult", + "ExportAssetsRequest", + "ExportAssetsResponse", + "BatchGetAssetsHistoryRequest", + "BatchGetAssetsHistoryResponse", + "CreateFeedRequest", + "GetFeedRequest", + "ListFeedsRequest", + "ListFeedsResponse", + "UpdateFeedRequest", + "DeleteFeedRequest", + "OutputConfig", + "GcsDestination", + "BigQueryDestination", + "PubsubDestination", + "FeedOutputConfig", + "Feed", + "SearchAllResourcesRequest", + "SearchAllResourcesResponse", + "SearchAllIamPoliciesRequest", + "SearchAllIamPoliciesResponse", +) diff --git a/google/cloud/asset_v1/types/asset_service.py b/google/cloud/asset_v1/types/asset_service.py new file mode 100644 index 00000000..c537d665 --- /dev/null +++ b/google/cloud/asset_v1/types/asset_service.py @@ -0,0 +1,672 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.asset_v1.types import assets as gca_assets +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1", + manifest={ + "ContentType", + "ExportAssetsRequest", + "ExportAssetsResponse", + "BatchGetAssetsHistoryRequest", + "BatchGetAssetsHistoryResponse", + "CreateFeedRequest", + "GetFeedRequest", + "ListFeedsRequest", + "ListFeedsResponse", + "UpdateFeedRequest", + "DeleteFeedRequest", + "OutputConfig", + "GcsDestination", + "BigQueryDestination", + "PubsubDestination", + "FeedOutputConfig", + "Feed", + "SearchAllResourcesRequest", + "SearchAllResourcesResponse", + "SearchAllIamPoliciesRequest", + "SearchAllIamPoliciesResponse", + }, +) + + +class ContentType(proto.Enum): + r"""Asset content type.""" + CONTENT_TYPE_UNSPECIFIED = 0 + RESOURCE = 1 + IAM_POLICY = 2 + ORG_POLICY = 4 + ACCESS_POLICY = 5 + + +class ExportAssetsRequest(proto.Message): + r"""Export asset request. + + Attributes: + parent (str): + Required. The relative name of the root + asset. This can only be an organization number + (such as "organizations/123"), a project ID + (such as "projects/my-project-id"), or a project + number (such as "projects/12345"), or a folder + number (such as "folders/123"). + read_time (~.timestamp.Timestamp): + Timestamp to take an asset snapshot. This can + only be set to a timestamp between the current + time and the current time minus 35 days + (inclusive). If not specified, the current time + will be used. Due to delays in resource data + collection and indexing, there is a volatile + window during which running the same query may + get different results. + asset_types (Sequence[str]): + A list of asset types of which to take a snapshot for. + Example: "compute.googleapis.com/Disk". If specified, only + matching assets will be returned. See `Introduction to Cloud + Asset + Inventory `__ + for all supported asset types. + content_type (~.asset_service.ContentType): + Asset content type. If not specified, no + content but the asset name will be returned. + output_config (~.asset_service.OutputConfig): + Required. Output configuration indicating + where the results will be output to. + """ + + parent = proto.Field(proto.STRING, number=1) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + asset_types = proto.RepeatedField(proto.STRING, number=3) + + content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) + + output_config = proto.Field(proto.MESSAGE, number=5, message="OutputConfig",) + + +class ExportAssetsResponse(proto.Message): + r"""The export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + Attributes: + read_time (~.timestamp.Timestamp): + Time the snapshot was taken. + output_config (~.asset_service.OutputConfig): + Output configuration indicating where the + results were output to. + """ + + read_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + + output_config = proto.Field(proto.MESSAGE, number=2, message="OutputConfig",) + + +class BatchGetAssetsHistoryRequest(proto.Message): + r"""Batch get assets history request. + + Attributes: + parent (str): + Required. The relative name of the root + asset. It can only be an organization number + (such as "organizations/123"), a project ID + (such as "projects/my-project-id")", or a + project number (such as "projects/12345"). + asset_names (Sequence[str]): + A list of the full names of the assets. See: + https://cloud.google.com/asset-inventory/docs/resource-name-format + Example: + + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + + The request becomes a no-op if the asset name list is empty, + and the max size of the asset name list is 100 in one + request. + content_type (~.asset_service.ContentType): + Optional. The content type. + read_time_window (~.gca_assets.TimeWindow): + Optional. The time window for the asset history. Both + start_time and end_time are optional and if set, it must be + after the current time minus 35 days. If end_time is not + set, it is default to current timestamp. If start_time is + not set, the snapshot of the assets at end_time will be + returned. The returned results contain all temporal assets + whose time window overlap with read_time_window. + """ + + parent = proto.Field(proto.STRING, number=1) + + asset_names = proto.RepeatedField(proto.STRING, number=2) + + content_type = proto.Field(proto.ENUM, number=3, enum="ContentType",) + + read_time_window = proto.Field( + proto.MESSAGE, number=4, message=gca_assets.TimeWindow, + ) + + +class BatchGetAssetsHistoryResponse(proto.Message): + r"""Batch get assets history response. + + Attributes: + assets (Sequence[~.gca_assets.TemporalAsset]): + A list of assets with valid time windows. + """ + + assets = proto.RepeatedField( + proto.MESSAGE, number=1, message=gca_assets.TemporalAsset, + ) + + +class CreateFeedRequest(proto.Message): + r"""Create asset feed request. + + Attributes: + parent (str): + Required. The name of the + project/folder/organization where this feed + should be created in. It can only be an + organization number (such as + "organizations/123"), a folder number (such as + "folders/123"), a project ID (such as + "projects/my-project-id")", or a project number + (such as "projects/12345"). + feed_id (str): + Required. This is the client-assigned asset + feed identifier and it needs to be unique under + a specific parent project/folder/organization. + feed (~.asset_service.Feed): + Required. The feed details. The field ``name`` must be empty + and it will be generated in the format of: + projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + parent = proto.Field(proto.STRING, number=1) + + feed_id = proto.Field(proto.STRING, number=2) + + feed = proto.Field(proto.MESSAGE, number=3, message="Feed",) + + +class GetFeedRequest(proto.Message): + r"""Get asset feed request. + + Attributes: + name (str): + Required. The name of the Feed and it must be in the format + of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + name = proto.Field(proto.STRING, number=1) + + +class ListFeedsRequest(proto.Message): + r"""List asset feeds request. + + Attributes: + parent (str): + Required. The parent + project/folder/organization whose feeds are to + be listed. It can only be using + project/folder/organization number (such as + "folders/12345")", or a project ID (such as + "projects/my-project-id"). + """ + + parent = proto.Field(proto.STRING, number=1) + + +class ListFeedsResponse(proto.Message): + r""" + + Attributes: + feeds (Sequence[~.asset_service.Feed]): + A list of feeds. + """ + + feeds = proto.RepeatedField(proto.MESSAGE, number=1, message="Feed",) + + +class UpdateFeedRequest(proto.Message): + r"""Update asset feed request. + + Attributes: + feed (~.asset_service.Feed): + Required. The new values of feed details. It must match an + existing feed and the field ``name`` must be in the format + of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + update_mask (~.field_mask.FieldMask): + Required. Only updates the ``feed`` fields indicated by this + mask. The field mask must not be empty, and it must not + contain fields that are immutable or only set by the server. + """ + + feed = proto.Field(proto.MESSAGE, number=1, message="Feed",) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteFeedRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the feed and it must be in the format + of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + name = proto.Field(proto.STRING, number=1) + + +class OutputConfig(proto.Message): + r"""Output configuration for export assets destination. + + Attributes: + gcs_destination (~.asset_service.GcsDestination): + Destination on Cloud Storage. + bigquery_destination (~.asset_service.BigQueryDestination): + Destination on BigQuery. The output table + stores the fields in asset proto as columns in + BigQuery. + """ + + gcs_destination = proto.Field( + proto.MESSAGE, number=1, oneof="destination", message="GcsDestination", + ) + + bigquery_destination = proto.Field( + proto.MESSAGE, number=2, oneof="destination", message="BigQueryDestination", + ) + + +class GcsDestination(proto.Message): + r"""A Cloud Storage location. + + Attributes: + uri (str): + The uri of the Cloud Storage object. It's the same uri that + is used by gsutil. Example: "gs://bucket_name/object_name". + See `Viewing and Editing Object + Metadata `__ + for more information. + uri_prefix (str): + The uri prefix of all generated Cloud Storage objects. + Example: "gs://bucket_name/object_name_prefix". Each object + uri is in format: "gs://bucket_name/object_name_prefix// and + only contains assets for that type. starts from 0. Example: + "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" + is the first shard of output objects containing all + compute.googleapis.com/Disk assets. An INVALID_ARGUMENT + error will be returned if file with the same name + "gs://bucket_name/object_name_prefix" already exists. + """ + + uri = proto.Field(proto.STRING, number=1, oneof="object_uri") + + uri_prefix = proto.Field(proto.STRING, number=2, oneof="object_uri") + + +class BigQueryDestination(proto.Message): + r"""A BigQuery destination for exporting assets to. + + Attributes: + dataset (str): + Required. The BigQuery dataset in format + "projects/projectId/datasets/datasetId", to which the + snapshot result should be exported. If this dataset does not + exist, the export call returns an INVALID_ARGUMENT error. + table (str): + Required. The BigQuery table to which the + snapshot result should be written. If this table + does not exist, a new table with the given name + will be created. + force (bool): + If the destination table already exists and this flag is + ``TRUE``, the table will be overwritten by the contents of + assets snapshot. If the flag is ``FALSE`` or unset and the + destination table already exists, the export call returns an + INVALID_ARGUMEMT error. + """ + + dataset = proto.Field(proto.STRING, number=1) + + table = proto.Field(proto.STRING, number=2) + + force = proto.Field(proto.BOOL, number=3) + + +class PubsubDestination(proto.Message): + r"""A Pub/Sub destination. + + Attributes: + topic (str): + The name of the Pub/Sub topic to publish to. Example: + ``projects/PROJECT_ID/topics/TOPIC_ID``. + """ + + topic = proto.Field(proto.STRING, number=1) + + +class FeedOutputConfig(proto.Message): + r"""Output configuration for asset feed destination. + + Attributes: + pubsub_destination (~.asset_service.PubsubDestination): + Destination on Pub/Sub. + """ + + pubsub_destination = proto.Field( + proto.MESSAGE, number=1, oneof="destination", message=PubsubDestination, + ) + + +class Feed(proto.Message): + r"""An asset feed used to export asset updates to a destinations. + An asset feed filter controls what updates are exported. The + asset feed must be created within a project, organization, or + folder. Supported destinations are: + Pub/Sub topics. + + Attributes: + name (str): + Required. The format will be + projects/{project_number}/feeds/{client-assigned_feed_identifier} + or + folders/{folder_number}/feeds/{client-assigned_feed_identifier} + or + organizations/{organization_number}/feeds/{client-assigned_feed_identifier} + + The client-assigned feed identifier must be unique within + the parent project/folder/organization. + asset_names (Sequence[str]): + A list of the full names of the assets to receive updates. + You must specify either or both of asset_names and + asset_types. Only asset updates matching specified + asset_names or asset_types are exported to the feed. + Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more info. + asset_types (Sequence[str]): + A list of types of the assets to receive updates. You must + specify either or both of asset_names and asset_types. Only + asset updates matching specified asset_names or asset_types + are exported to the feed. Example: + ``"compute.googleapis.com/Disk"`` + + See `this + topic `__ + for a list of all supported asset types. + content_type (~.asset_service.ContentType): + Asset content type. If not specified, no + content but the asset name and type will be + returned. + feed_output_config (~.asset_service.FeedOutputConfig): + Required. Feed output configuration defining + where the asset updates are published to. + condition (~.expr.Expr): + A condition which determines whether an asset update should + be published. If specified, an asset will be returned only + when the expression evaluates to true. When set, + ``expression`` field in the ``Expr`` must be a valid [CEL + expression] (https://github.com/google/cel-spec) on a + TemporalAsset with name ``temporal_asset``. Example: a Feed + with expression ("temporal_asset.deleted == true") will only + publish Asset deletions. Other fields in ``Expr`` are + optional. + """ + + name = proto.Field(proto.STRING, number=1) + + asset_names = proto.RepeatedField(proto.STRING, number=2) + + asset_types = proto.RepeatedField(proto.STRING, number=3) + + content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) + + feed_output_config = proto.Field(proto.MESSAGE, number=5, message=FeedOutputConfig,) + + condition = proto.Field(proto.MESSAGE, number=6, message=expr.Expr,) + + +class SearchAllResourcesRequest(proto.Message): + r"""Search all resources request. + + Attributes: + scope (str): + Required. A scope can be a project, a folder or an + organization. The search is limited to the resources within + the ``scope``. + + The allowed values are: + + - projects/{PROJECT_ID} + - projects/{PROJECT_NUMBER} + - folders/{FOLDER_NUMBER} + - organizations/{ORGANIZATION_NUMBER} + query (str): + Optional. The query statement. An empty query can be + specified to search all the resources of certain + ``asset_types`` within the given ``scope``. + + Examples: + + - ``name : "Important"`` to find Cloud resources whose name + contains "Important" as a word. + - ``displayName : "Impor*"`` to find Cloud resources whose + display name contains "Impor" as a word prefix. + - ``description : "*por*"`` to find Cloud resources whose + description contains "por" as a substring. + - ``location : "us-west*"`` to find Cloud resources whose + location is prefixed with "us-west". + - ``labels : "prod"`` to find Cloud resources whose labels + contain "prod" as a key or value. + - ``labels.env : "prod"`` to find Cloud resources which + have a label "env" and its value is "prod". + - ``labels.env : *`` to find Cloud resources which have a + label "env". + - ``"Important"`` to find Cloud resources which contain + "Important" as a word in any of the searchable fields. + - ``"Impor*"`` to find Cloud resources which contain + "Impor" as a word prefix in any of the searchable fields. + - ``"*por*"`` to find Cloud resources which contain "por" + as a substring in any of the searchable fields. + - ``("Important" AND location : ("us-west1" OR "global"))`` + to find Cloud resources which contain "Important" as a + word in any of the searchable fields and are also located + in the "us-west1" region or the "global" location. + + See `how to construct a + query `__ + for more details. + asset_types (Sequence[str]): + Optional. A list of asset types that this request searches + for. If empty, it will search all the `searchable asset + types `__. + page_size (int): + Optional. The page size for search result pagination. Page + size is capped at 500 even if a larger value is given. If + set to zero, server will pick an appropriate default. + Returned results may be fewer than requested. When this + happens, there could be more results as long as + ``next_page_token`` is returned. + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``page_token`` must be the value of ``next_page_token`` from + the previous response. The values of all other method + parameters, must be identical to those in the previous call. + order_by (str): + Optional. A comma separated list of fields specifying the + sorting order of the results. The default order is + ascending. Add " DESC" after the field name to indicate + descending order. Redundant space characters are ignored. + Example: "location DESC, name". See `supported resource + metadata + fields `__ + for more details. + """ + + scope = proto.Field(proto.STRING, number=1) + + query = proto.Field(proto.STRING, number=2) + + asset_types = proto.RepeatedField(proto.STRING, number=3) + + page_size = proto.Field(proto.INT32, number=4) + + page_token = proto.Field(proto.STRING, number=5) + + order_by = proto.Field(proto.STRING, number=6) + + +class SearchAllResourcesResponse(proto.Message): + r"""Search all resources response. + + Attributes: + results (Sequence[~.gca_assets.ResourceSearchResult]): + A list of Resources that match the search + query. It contains the resource standard + metadata information. + next_page_token (str): + If there are more results than those appearing in this + response, then ``next_page_token`` is included. To get the + next set of results, call this method again using the value + of ``next_page_token`` as ``page_token``. + """ + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, number=1, message=gca_assets.ResourceSearchResult, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class SearchAllIamPoliciesRequest(proto.Message): + r"""Search all IAM policies request. + + Attributes: + scope (str): + Required. A scope can be a project, a folder or an + organization. The search is limited to the IAM policies + within the ``scope``. + + The allowed values are: + + - projects/{PROJECT_ID} + - projects/{PROJECT_NUMBER} + - folders/{FOLDER_NUMBER} + - organizations/{ORGANIZATION_NUMBER} + query (str): + Optional. The query statement. An empty query can be + specified to search all the IAM policies within the given + ``scope``. + + Examples: + + - ``policy : "amy@gmail.com"`` to find Cloud IAM policy + bindings that specify user "amy@gmail.com". + - ``policy : "roles/compute.admin"`` to find Cloud IAM + policy bindings that specify the Compute Admin role. + - ``policy.role.permissions : "storage.buckets.update"`` to + find Cloud IAM policy bindings that specify a role + containing "storage.buckets.update" permission. + - ``resource : "organizations/123"`` to find Cloud IAM + policy bindings that are set on "organizations/123". + - ``(resource : ("organizations/123" OR "folders/1234") AND policy : "amy")`` + to find Cloud IAM policy bindings that are set on + "organizations/123" or "folders/1234", and also specify + user "amy". + + See `how to construct a + query `__ + for more details. + page_size (int): + Optional. The page size for search result pagination. Page + size is capped at 500 even if a larger value is given. If + set to zero, server will pick an appropriate default. + Returned results may be fewer than requested. When this + happens, there could be more results as long as + ``next_page_token`` is returned. + page_token (str): + Optional. If present, retrieve the next batch of results + from the preceding call to this method. ``page_token`` must + be the value of ``next_page_token`` from the previous + response. The values of all other method parameters must be + identical to those in the previous call. + """ + + scope = proto.Field(proto.STRING, number=1) + + query = proto.Field(proto.STRING, number=2) + + page_size = proto.Field(proto.INT32, number=3) + + page_token = proto.Field(proto.STRING, number=4) + + +class SearchAllIamPoliciesResponse(proto.Message): + r"""Search all IAM policies response. + + Attributes: + results (Sequence[~.gca_assets.IamPolicySearchResult]): + A list of IamPolicy that match the search + query. Related information such as the + associated resource is returned along with the + policy. + next_page_token (str): + Set if there are more results than those appearing in this + response; to get the next set of results, call this method + again, using this value as the ``page_token``. + """ + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, number=1, message=gca_assets.IamPolicySearchResult, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1/types/assets.py b/google/cloud/asset_v1/types/assets.py new file mode 100644 index 00000000..b14c748e --- /dev/null +++ b/google/cloud/asset_v1/types/assets.py @@ -0,0 +1,484 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.orgpolicy.v1 import orgpolicy_pb2 as orgpolicy # type: ignore +from google.iam.v1 import policy_pb2 as gi_policy # type: ignore +from google.identity.accesscontextmanager.v1 import access_level_pb2 as gia_access_level # type: ignore +from google.identity.accesscontextmanager.v1 import access_policy_pb2 as gia_access_policy # type: ignore +from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 as gia_service_perimeter # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1", + manifest={ + "TemporalAsset", + "TimeWindow", + "Asset", + "Resource", + "ResourceSearchResult", + "IamPolicySearchResult", + }, +) + + +class TemporalAsset(proto.Message): + r"""An asset in Google Cloud and its temporal metadata, including + the time window when it was observed and its status during that + window. + + Attributes: + window (~.assets.TimeWindow): + The time window when the asset data and state + was observed. + deleted (bool): + Whether the asset has been deleted or not. + asset (~.assets.Asset): + An asset in Google Cloud. + prior_asset_state (~.assets.TemporalAsset.PriorAssetState): + State of prior_asset. + prior_asset (~.assets.Asset): + Prior copy of the asset. Populated if prior_asset_state is + PRESENT. Currently this is only set for responses in + Real-Time Feed. + """ + + class PriorAssetState(proto.Enum): + r"""State of prior asset.""" + PRIOR_ASSET_STATE_UNSPECIFIED = 0 + PRESENT = 1 + INVALID = 2 + DOES_NOT_EXIST = 3 + DELETED = 4 + + window = proto.Field(proto.MESSAGE, number=1, message="TimeWindow",) + + deleted = proto.Field(proto.BOOL, number=2) + + asset = proto.Field(proto.MESSAGE, number=3, message="Asset",) + + prior_asset_state = proto.Field(proto.ENUM, number=4, enum=PriorAssetState,) + + prior_asset = proto.Field(proto.MESSAGE, number=5, message="Asset",) + + +class TimeWindow(proto.Message): + r"""A time window specified by its ``start_time`` and ``end_time``. + + Attributes: + start_time (~.timestamp.Timestamp): + Start time of the time window (exclusive). + end_time (~.timestamp.Timestamp): + End time of the time window (inclusive). If + not specified, the current timestamp is used + instead. + """ + + start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + +class Asset(proto.Message): + r"""An asset in Google Cloud. An asset can be any resource in the Google + Cloud `resource + hierarchy `__, + a resource outside the Google Cloud resource hierarchy (such as + Google Kubernetes Engine clusters and objects), or a policy (e.g. + Cloud IAM policy). See `Supported asset + types `__ + for more information. + + Attributes: + update_time (~.timestamp.Timestamp): + The last update timestamp of an asset. update_time is + updated when create/update/delete operation is performed. + name (str): + The full name of the asset. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`` + + See `Resource + names `__ + for more information. + asset_type (str): + The type of the asset. Example: + ``compute.googleapis.com/Disk`` + + See `Supported asset + types `__ + for more information. + resource (~.assets.Resource): + A representation of the resource. + iam_policy (~.gi_policy.Policy): + A representation of the Cloud IAM policy set on a Google + Cloud resource. There can be a maximum of one Cloud IAM + policy set on any given resource. In addition, Cloud IAM + policies inherit their granted access scope from any + policies set on parent resources in the resource hierarchy. + Therefore, the effectively policy is the union of both the + policy set on this resource and each policy set on all of + the resource's ancestry resource levels in the hierarchy. + See `this + topic `__ + for more information. + org_policy (Sequence[~.orgpolicy.Policy]): + A representation of an `organization + policy `__. + There can be more than one organization policy with + different constraints set on a given resource. + access_policy (~.gia_access_policy.AccessPolicy): + Please also refer to the `access policy user + guide `__. + access_level (~.gia_access_level.AccessLevel): + Please also refer to the `access level user + guide `__. + service_perimeter (~.gia_service_perimeter.ServicePerimeter): + Please also refer to the `service perimeter user + guide `__. + ancestors (Sequence[str]): + The ancestry path of an asset in Google Cloud `resource + hierarchy `__, + represented as a list of relative resource names. An + ancestry path starts with the closest ancestor in the + hierarchy and ends at root. If the asset is a project, + folder, or organization, the ancestry path starts from the + asset itself. + + Example: + ``["projects/123456789", "folders/5432", "organizations/1234"]`` + """ + + update_time = proto.Field(proto.MESSAGE, number=11, message=timestamp.Timestamp,) + + name = proto.Field(proto.STRING, number=1) + + asset_type = proto.Field(proto.STRING, number=2) + + resource = proto.Field(proto.MESSAGE, number=3, message="Resource",) + + iam_policy = proto.Field(proto.MESSAGE, number=4, message=gi_policy.Policy,) + + org_policy = proto.RepeatedField(proto.MESSAGE, number=6, message=orgpolicy.Policy,) + + access_policy = proto.Field( + proto.MESSAGE, + number=7, + oneof="access_context_policy", + message=gia_access_policy.AccessPolicy, + ) + + access_level = proto.Field( + proto.MESSAGE, + number=8, + oneof="access_context_policy", + message=gia_access_level.AccessLevel, + ) + + service_perimeter = proto.Field( + proto.MESSAGE, + number=9, + oneof="access_context_policy", + message=gia_service_perimeter.ServicePerimeter, + ) + + ancestors = proto.RepeatedField(proto.STRING, number=10) + + +class Resource(proto.Message): + r"""A representation of a Google Cloud resource. + + Attributes: + version (str): + The API version. Example: ``v1`` + discovery_document_uri (str): + The URL of the discovery document containing the resource's + JSON schema. Example: + ``https://www.googleapis.com/discovery/v1/apis/compute/v1/rest`` + + This value is unspecified for resources that do not have an + API based on a discovery document, such as Cloud Bigtable. + discovery_name (str): + The JSON schema name listed in the discovery document. + Example: ``Project`` + + This value is unspecified for resources that do not have an + API based on a discovery document, such as Cloud Bigtable. + resource_url (str): + The REST URL for accessing the resource. An HTTP ``GET`` + request using this URL returns the resource itself. Example: + ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`` + + This value is unspecified for resources without a REST API. + parent (str): + The full name of the immediate parent of this resource. See + `Resource + Names `__ + for more information. + + For Google Cloud assets, this value is the parent resource + defined in the `Cloud IAM policy + hierarchy `__. + Example: + ``//cloudresourcemanager.googleapis.com/projects/my_project_123`` + + For third-party assets, this field may be set differently. + data (~.struct.Struct): + The content of the resource, in which some + sensitive fields are removed and may not be + present. + location (str): + The location of the resource in Google Cloud, + such as its zone and region. For more + information, see + https://cloud.google.com/about/locations/. + """ + + version = proto.Field(proto.STRING, number=1) + + discovery_document_uri = proto.Field(proto.STRING, number=2) + + discovery_name = proto.Field(proto.STRING, number=3) + + resource_url = proto.Field(proto.STRING, number=4) + + parent = proto.Field(proto.STRING, number=5) + + data = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) + + location = proto.Field(proto.STRING, number=8) + + +class ResourceSearchResult(proto.Message): + r"""A result of Resource Search, containing information of a + cloud resoure. + + Attributes: + name (str): + The full resource name of this resource. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Cloud Asset Inventory Resource Name + Format `__ + for more information. + + To search against the ``name``: + + - use a field query. Example: ``name : "instance1"`` + - use a free text query. Example: ``"instance1"`` + asset_type (str): + The type of this resource. Example: + ``compute.googleapis.com/Disk``. + + To search against the ``asset_type``: + + - specify the ``asset_type`` field in your search request. + project (str): + The project that this resource belongs to, in the form of + projects/{PROJECT_NUMBER}. + + To search against the ``project``: + + - specify the ``scope`` field as this project in your + search request. + display_name (str): + The display name of this resource. + + To search against the ``display_name``: + + - use a field query. Example: + ``displayName : "My Instance"`` + - use a free text query. Example: ``"My Instance"`` + description (str): + One or more paragraphs of text description of this resource. + Maximum length could be up to 1M bytes. + + To search against the ``description``: + + - use a field query. Example: + ``description : "*important instance*"`` + - use a free text query. Example: + ``"*important instance*"`` + location (str): + Location can be ``global``, regional like ``us-east1``, or + zonal like ``us-west1-b``. + + To search against the ``location``: + + - use a field query. Example: ``location : "us-west*"`` + - use a free text query. Example: ``"us-west*"`` + labels (Sequence[~.assets.ResourceSearchResult.LabelsEntry]): + Labels associated with this resource. See `Labelling and + grouping GCP + resources `__ + for more information. + + To search against the ``labels``: + + - use a field query, as following: + + - query on any label's key or value. Example: + ``labels : "prod"`` + - query by a given label. Example: + ``labels.env : "prod"`` + - query by a given label'sexistence. Example: + ``labels.env : *`` + + - use a free text query. Example: ``"prod"`` + network_tags (Sequence[str]): + Network tags associated with this resource. Like labels, + network tags are a type of annotations used to group GCP + resources. See `Labelling GCP + resources `__ + for more information. + + To search against the ``network_tags``: + + - use a field query. Example: ``networkTags : "internal"`` + - use a free text query. Example: ``"internal"`` + additional_attributes (~.struct.Struct): + The additional attributes of this resource. The attributes + may vary from one resource type to another. Examples: + ``projectId`` for Project, ``dnsName`` for DNS ManagedZone. + + To search against the ``additional_attributes``: + + - use a free text query to match the attributes values. + Example: to search + ``additional_attributes = { dnsName: "foobar" }``, you + can issue a query ``"foobar"``. + """ + + name = proto.Field(proto.STRING, number=1) + + asset_type = proto.Field(proto.STRING, number=2) + + project = proto.Field(proto.STRING, number=3) + + display_name = proto.Field(proto.STRING, number=4) + + description = proto.Field(proto.STRING, number=5) + + location = proto.Field(proto.STRING, number=6) + + labels = proto.MapField(proto.STRING, proto.STRING, number=7) + + network_tags = proto.RepeatedField(proto.STRING, number=8) + + additional_attributes = proto.Field(proto.MESSAGE, number=9, message=struct.Struct,) + + +class IamPolicySearchResult(proto.Message): + r"""A result of IAM Policy search, containing information of an + IAM policy. + + Attributes: + resource (str): + The full resource name of the resource associated with this + IAM policy. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Cloud Asset Inventory Resource Name + Format `__ + for more information. + + To search against the ``resource``: + + - use a field query. Example: + ``resource : "organizations/123"`` + project (str): + The project that the associated GCP resource belongs to, in + the form of projects/{PROJECT_NUMBER}. If an IAM policy is + set on a resource (like VM instance, Cloud Storage bucket), + the project field will indicate the project that contains + the resource. If an IAM policy is set on a folder or + orgnization, the project field will be empty. + + To search against the ``project``: + + - specify the ``scope`` field as this project in your + search request. + policy (~.gi_policy.Policy): + The IAM policy directly set on the given resource. Note that + the original IAM policy can contain multiple bindings. This + only contains the bindings that match the given query. For + queries that don't contain a constrain on policies (e.g., an + empty query), this contains all the bindings. + + To search against the ``policy`` bindings: + + - use a field query, as following: + + - query by the policy contained members. Example: + ``policy : "amy@gmail.com"`` + - query by the policy contained roles. Example: + ``policy : "roles/compute.admin"`` + - query by the policy contained roles' implied + permissions. Example: + ``policy.role.permissions : "compute.instances.create"`` + explanation (~.assets.IamPolicySearchResult.Explanation): + Explanation about the IAM policy search + result. It contains additional information to + explain why the search result matches the query. + """ + + class Explanation(proto.Message): + r"""Explanation about the IAM policy search result. + + Attributes: + matched_permissions (Sequence[~.assets.IamPolicySearchResult.Explanation.MatchedPermissionsEntry]): + The map from roles to their included permissions that match + the permission query (i.e., a query containing + ``policy.role.permissions:``). Example: if query + ``policy.role.permissions : "compute.disk.get"`` matches a + policy binding that contains owner role, the + matched_permissions will be + ``{"roles/owner": ["compute.disk.get"]}``. The roles can + also be found in the returned ``policy`` bindings. Note that + the map is populated only for requests with permission + queries. + """ + + class Permissions(proto.Message): + r"""IAM permissions + + Attributes: + permissions (Sequence[str]): + A list of permissions. A sample permission string: + ``compute.disk.get``. + """ + + permissions = proto.RepeatedField(proto.STRING, number=1) + + matched_permissions = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="IamPolicySearchResult.Explanation.Permissions", + ) + + resource = proto.Field(proto.STRING, number=1) + + project = proto.Field(proto.STRING, number=2) + + policy = proto.Field(proto.MESSAGE, number=3, message=gi_policy.Policy,) + + explanation = proto.Field(proto.MESSAGE, number=4, message=Explanation,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1beta1/__init__.py b/google/cloud/asset_v1beta1/__init__.py index d060c1ae..49e794c1 100644 --- a/google/cloud/asset_v1beta1/__init__.py +++ b/google/cloud/asset_v1beta1/__init__.py @@ -1,45 +1,45 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.asset_v1beta1 import types -from google.cloud.asset_v1beta1.gapic import asset_service_client -from google.cloud.asset_v1beta1.gapic import enums - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class AssetServiceClient(asset_service_client.AssetServiceClient): - __doc__ = asset_service_client.AssetServiceClient.__doc__ - enums = enums +from .services.asset_service import AssetServiceClient +from .types.asset_service import BatchGetAssetsHistoryRequest +from .types.asset_service import BatchGetAssetsHistoryResponse +from .types.asset_service import ContentType +from .types.asset_service import ExportAssetsRequest +from .types.asset_service import ExportAssetsResponse +from .types.asset_service import GcsDestination +from .types.asset_service import OutputConfig +from .types.assets import Asset +from .types.assets import Resource +from .types.assets import TemporalAsset +from .types.assets import TimeWindow __all__ = ( - "enums", - "types", + "Asset", + "BatchGetAssetsHistoryRequest", + "BatchGetAssetsHistoryResponse", + "ContentType", + "ExportAssetsRequest", + "ExportAssetsResponse", + "GcsDestination", + "OutputConfig", + "Resource", + "TemporalAsset", + "TimeWindow", "AssetServiceClient", ) diff --git a/google/cloud/asset_v1beta1/gapic/__init__.py b/google/cloud/asset_v1beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1beta1/gapic/asset_service_client.py b/google/cloud/asset_v1beta1/gapic/asset_service_client.py deleted file mode 100644 index 3da195da..00000000 --- a/google/cloud/asset_v1beta1/gapic/asset_service_client.py +++ /dev/null @@ -1,421 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Accesses the google.cloud.asset.v1beta1 AssetService API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import grpc - -from google.cloud.asset_v1beta1.gapic import asset_service_client_config -from google.cloud.asset_v1beta1.gapic import enums -from google.cloud.asset_v1beta1.gapic.transports import asset_service_grpc_transport -from google.cloud.asset_v1beta1.proto import asset_service_pb2 -from google.cloud.asset_v1beta1.proto import asset_service_pb2_grpc -from google.cloud.asset_v1beta1.proto import assets_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import timestamp_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-asset",).version - - -class AssetServiceClient(object): - """Asset service definition.""" - - SERVICE_ADDRESS = "cloudasset.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.asset.v1beta1.AssetService" - - @classmethod - def from_service_account_file(cls, filename, *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: - AssetServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def project_path(cls, project): - """Return a fully-qualified project string.""" - return google.api_core.path_template.expand( - "projects/{project}", project=project - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.AssetServiceGrpcTransport, - Callable[[~.Credentials, type], ~.AssetServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = asset_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=asset_service_grpc_transport.AssetServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = asset_service_grpc_transport.AssetServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def export_assets( - self, - parent, - output_config, - read_time=None, - asset_types=None, - content_type=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Exports assets with time and resource types to a given Cloud Storage - location. The output format is newline-delimited JSON. This API - implements the ``google.longrunning.Operation`` API allowing you to keep - track of the export. - - Example: - >>> from google.cloud import asset_v1beta1 - >>> - >>> client = asset_v1beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.export_assets(parent, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The relative name of the root asset. This can only be an - organization number (such as "organizations/123"), a project ID (such as - "projects/my-project-id"), a project number (such as "projects/12345"), or - a folder number (such as "folders/123"). - output_config (Union[dict, ~google.cloud.asset_v1beta1.types.OutputConfig]): Required. Output configuration indicating where the results will be output - to. All results will be in newline delimited JSON format. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1beta1.types.OutputConfig` - read_time (Union[dict, ~google.cloud.asset_v1beta1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp - between 2018-10-02 UTC (inclusive) and the current time. If not specified, - the current time will be used. Due to delays in resource data collection - and indexing, there is a volatile window during which running the same - query may get different results. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1beta1.types.Timestamp` - asset_types (list[str]): A list of asset types of which to take a snapshot for. For example: - "google.compute.Disk". If specified, only matching assets will be - returned. See `Introduction to Cloud Asset - Inventory `__ - for all supported asset types. - content_type (~google.cloud.asset_v1beta1.types.ContentType): Asset content type. If not specified, no content but the asset name will be - returned. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "export_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "export_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.export_assets, - default_retry=self._method_configs["ExportAssets"].retry, - default_timeout=self._method_configs["ExportAssets"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.ExportAssetsRequest( - parent=parent, - output_config=output_config, - read_time=read_time, - asset_types=asset_types, - content_type=content_type, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["export_assets"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - asset_service_pb2.ExportAssetsResponse, - metadata_type=asset_service_pb2.ExportAssetsRequest, - ) - - def batch_get_assets_history( - self, - parent, - content_type=None, - read_time_window=None, - asset_names=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Batch gets the update history of assets that overlap a time window. - For RESOURCE content, this API outputs history with asset in both - non-delete or deleted status. For IAM_POLICY content, this API outputs - history when the asset and its attached IAM POLICY both exist. This can - create gaps in the output history. If a specified asset does not exist, - this API returns an INVALID_ARGUMENT error. - - Example: - >>> from google.cloud import asset_v1beta1 - >>> - >>> client = asset_v1beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> response = client.batch_get_assets_history(parent) - - Args: - parent (str): Required. The relative name of the root asset. It can only be an - organization number (such as "organizations/123"), a project ID (such as - "projects/my-project-id")", or a project number (such as "projects/12345"). - asset_names (list[str]): A list of the full names of the assets. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Resource - Names `__ - for more info. - - The request becomes a no-op if the asset name list is empty, and the max - size of the asset name list is 100 in one request. - content_type (~google.cloud.asset_v1beta1.types.ContentType): Optional. The content type. - read_time_window (Union[dict, ~google.cloud.asset_v1beta1.types.TimeWindow]): Optional. The time window for the asset history. Both start_time and - end_time are optional and if set, it must be after 2018-10-02 UTC. If - end_time is not set, it is default to current timestamp. If start_time - is not set, the snapshot of the assets at end_time will be returned. The - returned results contain all temporal assets whose time window overlap - with read_time_window. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1beta1.types.TimeWindow` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1beta1.types.BatchGetAssetsHistoryResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_get_assets_history" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_get_assets_history" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_get_assets_history, - default_retry=self._method_configs["BatchGetAssetsHistory"].retry, - default_timeout=self._method_configs["BatchGetAssetsHistory"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.BatchGetAssetsHistoryRequest( - parent=parent, - asset_names=asset_names, - content_type=content_type, - read_time_window=read_time_window, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["batch_get_assets_history"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/asset_v1beta1/gapic/asset_service_client_config.py b/google/cloud/asset_v1beta1/gapic/asset_service_client_config.py deleted file mode 100644 index a6eb0a51..00000000 --- a/google/cloud/asset_v1beta1/gapic/asset_service_client_config.py +++ /dev/null @@ -1,52 +0,0 @@ -config = { - "interfaces": { - "google.cloud.asset.v1beta1.AssetService": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - }, - "methods": { - "ExportAssets": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "BatchGetAssetsHistory": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/asset_v1beta1/gapic/enums.py b/google/cloud/asset_v1beta1/gapic/enums.py deleted file mode 100644 index 272f5f3a..00000000 --- a/google/cloud/asset_v1beta1/gapic/enums.py +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class ContentType(enum.IntEnum): - """ - Asset content type. - - Attributes: - CONTENT_TYPE_UNSPECIFIED (int): Unspecified content type. - RESOURCE (int): Resource metadata. - IAM_POLICY (int): The actual IAM policy set on a resource. - """ - - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 - - -class NullValue(enum.IntEnum): - """ - ``NullValue`` is a singleton enumeration to represent the null value - for the ``Value`` type union. - - The JSON representation for ``NullValue`` is JSON ``null``. - - Attributes: - NULL_VALUE (int): Null value. - """ - - NULL_VALUE = 0 diff --git a/google/cloud/asset_v1beta1/gapic/transports/__init__.py b/google/cloud/asset_v1beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1beta1/gapic/transports/asset_service_grpc_transport.py b/google/cloud/asset_v1beta1/gapic/transports/asset_service_grpc_transport.py deleted file mode 100644 index 26dc3c3e..00000000 --- a/google/cloud/asset_v1beta1/gapic/transports/asset_service_grpc_transport.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.asset_v1beta1.proto import asset_service_pb2_grpc - - -class AssetServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.asset.v1beta1 AssetService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="cloudasset.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "asset_service_stub": asset_service_pb2_grpc.AssetServiceStub(channel), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="cloudasset.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def export_assets(self): - """Return the gRPC stub for :meth:`AssetServiceClient.export_assets`. - - Exports assets with time and resource types to a given Cloud Storage - location. The output format is newline-delimited JSON. This API - implements the ``google.longrunning.Operation`` API allowing you to keep - track of the export. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].ExportAssets - - @property - def batch_get_assets_history(self): - """Return the gRPC stub for :meth:`AssetServiceClient.batch_get_assets_history`. - - Batch gets the update history of assets that overlap a time window. - For RESOURCE content, this API outputs history with asset in both - non-delete or deleted status. For IAM_POLICY content, this API outputs - history when the asset and its attached IAM POLICY both exist. This can - create gaps in the output history. If a specified asset does not exist, - this API returns an INVALID_ARGUMENT error. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].BatchGetAssetsHistory diff --git a/google/cloud/asset_v1beta1/proto/__init__.py b/google/cloud/asset_v1beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1beta1/proto/asset_service.proto b/google/cloud/asset_v1beta1/proto/asset_service.proto deleted file mode 100644 index 956c6a76..00000000 --- a/google/cloud/asset_v1beta1/proto/asset_service.proto +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.asset.v1beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/cloud/asset/v1beta1/assets.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/timestamp.proto"; - -option csharp_namespace = "Google.Cloud.Asset.V1Beta1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/asset/v1beta1;asset"; -option java_multiple_files = true; -option java_outer_classname = "AssetServiceProto"; -option java_package = "com.google.cloud.asset.v1beta1"; -option php_namespace = "Google\\Cloud\\Asset\\V1beta1"; - -// Asset service definition. -service AssetService { - option (google.api.default_host) = "cloudasset.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform"; - - // Exports assets with time and resource types to a given Cloud Storage - // location. The output format is newline-delimited JSON. - // This API implements the - // [google.longrunning.Operation][google.longrunning.Operation] API allowing - // you to keep track of the export. - rpc ExportAssets(ExportAssetsRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1beta1/{parent=projects/*}:exportAssets" - body: "*" - additional_bindings { - post: "/v1beta1/{parent=folders/*}:exportAssets" - body: "*" - } - additional_bindings { - post: "/v1beta1/{parent=organizations/*}:exportAssets" - body: "*" - } - }; - option (google.longrunning.operation_info) = { - response_type: "google.cloud.asset.v1beta1.ExportAssetsResponse" - metadata_type: "google.cloud.asset.v1beta1.ExportAssetsRequest" - }; - } - - // Batch gets the update history of assets that overlap a time window. - // For RESOURCE content, this API outputs history with asset in both - // non-delete or deleted status. - // For IAM_POLICY content, this API outputs history when the asset and its - // attached IAM POLICY both exist. This can create gaps in the output history. - // If a specified asset does not exist, this API returns an INVALID_ARGUMENT - // error. - rpc BatchGetAssetsHistory(BatchGetAssetsHistoryRequest) - returns (BatchGetAssetsHistoryResponse) { - option (google.api.http) = { - get: "/v1beta1/{parent=projects/*}:batchGetAssetsHistory" - additional_bindings { - get: "/v1beta1/{parent=organizations/*}:batchGetAssetsHistory" - } - }; - } -} - -// Export asset request. -message ExportAssetsRequest { - // Required. The relative name of the root asset. This can only be an - // organization number (such as "organizations/123"), a project ID (such as - // "projects/my-project-id"), a project number (such as "projects/12345"), or - // a folder number (such as "folders/123"). - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - child_type: "cloudasset.googleapis.com/Asset" - } - ]; - - // Timestamp to take an asset snapshot. This can only be set to a timestamp - // between 2018-10-02 UTC (inclusive) and the current time. If not specified, - // the current time will be used. Due to delays in resource data collection - // and indexing, there is a volatile window during which running the same - // query may get different results. - google.protobuf.Timestamp read_time = 2; - - // A list of asset types of which to take a snapshot for. For example: - // "google.compute.Disk". If specified, only matching assets will be returned. - // See [Introduction to Cloud Asset - // Inventory](https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview) - // for all supported asset types. - repeated string asset_types = 3; - - // Asset content type. If not specified, no content but the asset name will be - // returned. - ContentType content_type = 4; - - // Required. Output configuration indicating where the results will be output - // to. All results will be in newline delimited JSON format. - OutputConfig output_config = 5 [(google.api.field_behavior) = REQUIRED]; -} - -// The export asset response. This message is returned by the -// [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] -// method in the returned -// [google.longrunning.Operation.response][google.longrunning.Operation.response] -// field. -message ExportAssetsResponse { - // Time the snapshot was taken. - google.protobuf.Timestamp read_time = 1; - - // Output configuration indicating where the results were output to. - // All results are in JSON format. - OutputConfig output_config = 2; -} - -// Batch get assets history request. -message BatchGetAssetsHistoryRequest { - // Required. The relative name of the root asset. It can only be an - // organization number (such as "organizations/123"), a project ID (such as - // "projects/my-project-id")", or a project number (such as "projects/12345"). - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - child_type: "cloudasset.googleapis.com/Asset" - } - ]; - - // A list of the full names of the assets. For example: - // `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - // See [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more info. - // - // The request becomes a no-op if the asset name list is empty, and the max - // size of the asset name list is 100 in one request. - repeated string asset_names = 2; - - // Optional. The content type. - ContentType content_type = 3 [(google.api.field_behavior) = OPTIONAL]; - - // Optional. The time window for the asset history. Both start_time and - // end_time are optional and if set, it must be after 2018-10-02 UTC. If - // end_time is not set, it is default to current timestamp. If start_time is - // not set, the snapshot of the assets at end_time will be returned. The - // returned results contain all temporal assets whose time window overlap with - // read_time_window. - TimeWindow read_time_window = 4 [(google.api.field_behavior) = OPTIONAL]; -} - -// Batch get assets history response. -message BatchGetAssetsHistoryResponse { - // A list of assets with valid time windows. - repeated TemporalAsset assets = 1; -} - -// Output configuration for export assets destination. -message OutputConfig { - // Asset export destination. - oneof destination { - // Destination on Cloud Storage. - GcsDestination gcs_destination = 1; - } -} - -// A Cloud Storage location. -message GcsDestination { - // Required. - oneof object_uri { - // The uri of the Cloud Storage object. It's the same uri that is used by - // gsutil. For example: "gs://bucket_name/object_name". See [Viewing and - // Editing Object - // Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) - // for more information. - string uri = 1; - - // The uri prefix of all generated Cloud Storage objects. For example: - // "gs://bucket_name/object_name_prefix". Each object uri is in format: - // "gs://bucket_name/object_name_prefix// and only - // contains assets for that type. starts from 0. For example: - // "gs://bucket_name/object_name_prefix/google.compute.disk/0" is the first - // shard of output objects containing all google.compute.disk assets. - // An INVALID_ARGUMENT error will be returned if file with the same name - // "gs://bucket_name/object_name_prefix" already exists. - string uri_prefix = 2; - } -} - -// Asset content type. -enum ContentType { - // Unspecified content type. - CONTENT_TYPE_UNSPECIFIED = 0; - - // Resource metadata. - RESOURCE = 1; - - // The actual IAM policy set on a resource. - IAM_POLICY = 2; -} diff --git a/google/cloud/asset_v1beta1/proto/asset_service_pb2.py b/google/cloud/asset_v1beta1/proto/asset_service_pb2.py deleted file mode 100644 index fa374525..00000000 --- a/google/cloud/asset_v1beta1/proto/asset_service_pb2.py +++ /dev/null @@ -1,794 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1beta1/proto/asset_service.proto -"""Generated protocol buffer code.""" -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.asset_v1beta1.proto import ( - assets_pb2 as google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_assets__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1beta1/proto/asset_service.proto", - package="google.cloud.asset.v1beta1", - syntax="proto3", - serialized_options=b"\n\036com.google.cloud.asset.v1beta1B\021AssetServiceProtoP\001Z?google.golang.org/genproto/googleapis/cloud/asset/v1beta1;asset\252\002\032Google.Cloud.Asset.V1Beta1\312\002\032Google\\Cloud\\Asset\\V1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n4google/cloud/asset_v1beta1/proto/asset_service.proto\x12\x1agoogle.cloud.asset.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a-google/cloud/asset_v1beta1/proto/assets.proto\x1a#google/longrunning/operations.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\x97\x02\n\x13\x45xportAssetsRequest\x12\x37\n\x06parent\x18\x01 \x01(\tB\'\xe0\x41\x02\xfa\x41!\x12\x1f\x63loudasset.googleapis.com/Asset\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x13\n\x0b\x61sset_types\x18\x03 \x03(\t\x12=\n\x0c\x63ontent_type\x18\x04 \x01(\x0e\x32\'.google.cloud.asset.v1beta1.ContentType\x12\x44\n\routput_config\x18\x05 \x01(\x0b\x32(.google.cloud.asset.v1beta1.OutputConfigB\x03\xe0\x41\x02"\x86\x01\n\x14\x45xportAssetsResponse\x12-\n\tread_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12?\n\routput_config\x18\x02 \x01(\x0b\x32(.google.cloud.asset.v1beta1.OutputConfig"\xf7\x01\n\x1c\x42\x61tchGetAssetsHistoryRequest\x12\x37\n\x06parent\x18\x01 \x01(\tB\'\xe0\x41\x02\xfa\x41!\x12\x1f\x63loudasset.googleapis.com/Asset\x12\x13\n\x0b\x61sset_names\x18\x02 \x03(\t\x12\x42\n\x0c\x63ontent_type\x18\x03 \x01(\x0e\x32\'.google.cloud.asset.v1beta1.ContentTypeB\x03\xe0\x41\x01\x12\x45\n\x10read_time_window\x18\x04 \x01(\x0b\x32&.google.cloud.asset.v1beta1.TimeWindowB\x03\xe0\x41\x01"Z\n\x1d\x42\x61tchGetAssetsHistoryResponse\x12\x39\n\x06\x61ssets\x18\x01 \x03(\x0b\x32).google.cloud.asset.v1beta1.TemporalAsset"d\n\x0cOutputConfig\x12\x45\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32*.google.cloud.asset.v1beta1.GcsDestinationH\x00\x42\r\n\x0b\x64\x65stination"C\n\x0eGcsDestination\x12\r\n\x03uri\x18\x01 \x01(\tH\x00\x12\x14\n\nuri_prefix\x18\x02 \x01(\tH\x00\x42\x0c\n\nobject_uri*I\n\x0b\x43ontentType\x12\x1c\n\x18\x43ONTENT_TYPE_UNSPECIFIED\x10\x00\x12\x0c\n\x08RESOURCE\x10\x01\x12\x0e\n\nIAM_POLICY\x10\x02\x32\xc4\x05\n\x0c\x41ssetService\x12\xde\x02\n\x0c\x45xportAssets\x12/.google.cloud.asset.v1beta1.ExportAssetsRequest\x1a\x1d.google.longrunning.Operation"\xfd\x01\x82\xd3\xe4\x93\x02\x92\x01")/v1beta1/{parent=projects/*}:exportAssets:\x01*Z-"(/v1beta1/{parent=folders/*}:exportAssets:\x01*Z3"./v1beta1/{parent=organizations/*}:exportAssets:\x01*\xca\x41\x61\n/google.cloud.asset.v1beta1.ExportAssetsResponse\x12.google.cloud.asset.v1beta1.ExportAssetsRequest\x12\x83\x02\n\x15\x42\x61tchGetAssetsHistory\x12\x38.google.cloud.asset.v1beta1.BatchGetAssetsHistoryRequest\x1a\x39.google.cloud.asset.v1beta1.BatchGetAssetsHistoryResponse"u\x82\xd3\xe4\x93\x02o\x12\x32/v1beta1/{parent=projects/*}:batchGetAssetsHistoryZ9\x12\x37/v1beta1/{parent=organizations/*}:batchGetAssetsHistory\x1aM\xca\x41\x19\x63loudasset.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xb0\x01\n\x1e\x63om.google.cloud.asset.v1beta1B\x11\x41ssetServiceProtoP\x01Z?google.golang.org/genproto/googleapis/cloud/asset/v1beta1;asset\xaa\x02\x1aGoogle.Cloud.Asset.V1Beta1\xca\x02\x1aGoogle\\Cloud\\Asset\\V1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_assets__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - -_CONTENTTYPE = _descriptor.EnumDescriptor( - name="ContentType", - full_name="google.cloud.asset.v1beta1.ContentType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="CONTENT_TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RESOURCE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="IAM_POLICY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1248, - serialized_end=1321, -) -_sym_db.RegisterEnumDescriptor(_CONTENTTYPE) - -ContentType = enum_type_wrapper.EnumTypeWrapper(_CONTENTTYPE) -CONTENT_TYPE_UNSPECIFIED = 0 -RESOURCE = 1 -IAM_POLICY = 2 - - -_EXPORTASSETSREQUEST = _descriptor.Descriptor( - name="ExportAssetsRequest", - full_name="google.cloud.asset.v1beta1.ExportAssetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1beta1.ExportAssetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A!\022\037cloudasset.googleapis.com/Asset", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.asset.v1beta1.ExportAssetsRequest.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_types", - full_name="google.cloud.asset.v1beta1.ExportAssetsRequest.asset_types", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content_type", - full_name="google.cloud.asset.v1beta1.ExportAssetsRequest.content_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.asset.v1beta1.ExportAssetsRequest.output_config", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=317, - serialized_end=596, -) - - -_EXPORTASSETSRESPONSE = _descriptor.Descriptor( - name="ExportAssetsResponse", - full_name="google.cloud.asset.v1beta1.ExportAssetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.asset.v1beta1.ExportAssetsResponse.read_time", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.asset.v1beta1.ExportAssetsResponse.output_config", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=599, - serialized_end=733, -) - - -_BATCHGETASSETSHISTORYREQUEST = _descriptor.Descriptor( - name="BatchGetAssetsHistoryRequest", - full_name="google.cloud.asset.v1beta1.BatchGetAssetsHistoryRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1beta1.BatchGetAssetsHistoryRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A!\022\037cloudasset.googleapis.com/Asset", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_names", - full_name="google.cloud.asset.v1beta1.BatchGetAssetsHistoryRequest.asset_names", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content_type", - full_name="google.cloud.asset.v1beta1.BatchGetAssetsHistoryRequest.content_type", - index=2, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time_window", - full_name="google.cloud.asset.v1beta1.BatchGetAssetsHistoryRequest.read_time_window", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=736, - serialized_end=983, -) - - -_BATCHGETASSETSHISTORYRESPONSE = _descriptor.Descriptor( - name="BatchGetAssetsHistoryResponse", - full_name="google.cloud.asset.v1beta1.BatchGetAssetsHistoryResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="assets", - full_name="google.cloud.asset.v1beta1.BatchGetAssetsHistoryResponse.assets", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=985, - serialized_end=1075, -) - - -_OUTPUTCONFIG = _descriptor.Descriptor( - name="OutputConfig", - full_name="google.cloud.asset.v1beta1.OutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_destination", - full_name="google.cloud.asset.v1beta1.OutputConfig.gcs_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="destination", - full_name="google.cloud.asset.v1beta1.OutputConfig.destination", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1077, - serialized_end=1177, -) - - -_GCSDESTINATION = _descriptor.Descriptor( - name="GcsDestination", - full_name="google.cloud.asset.v1beta1.GcsDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.asset.v1beta1.GcsDestination.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uri_prefix", - full_name="google.cloud.asset.v1beta1.GcsDestination.uri_prefix", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="object_uri", - full_name="google.cloud.asset.v1beta1.GcsDestination.object_uri", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1179, - serialized_end=1246, -) - -_EXPORTASSETSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_EXPORTASSETSREQUEST.fields_by_name["content_type"].enum_type = _CONTENTTYPE -_EXPORTASSETSREQUEST.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_EXPORTASSETSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_EXPORTASSETSRESPONSE.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_BATCHGETASSETSHISTORYREQUEST.fields_by_name["content_type"].enum_type = _CONTENTTYPE -_BATCHGETASSETSHISTORYREQUEST.fields_by_name[ - "read_time_window" -].message_type = ( - google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_assets__pb2._TIMEWINDOW -) -_BATCHGETASSETSHISTORYRESPONSE.fields_by_name[ - "assets" -].message_type = ( - google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_assets__pb2._TEMPORALASSET -) -_OUTPUTCONFIG.fields_by_name["gcs_destination"].message_type = _GCSDESTINATION -_OUTPUTCONFIG.oneofs_by_name["destination"].fields.append( - _OUTPUTCONFIG.fields_by_name["gcs_destination"] -) -_OUTPUTCONFIG.fields_by_name[ - "gcs_destination" -].containing_oneof = _OUTPUTCONFIG.oneofs_by_name["destination"] -_GCSDESTINATION.oneofs_by_name["object_uri"].fields.append( - _GCSDESTINATION.fields_by_name["uri"] -) -_GCSDESTINATION.fields_by_name["uri"].containing_oneof = _GCSDESTINATION.oneofs_by_name[ - "object_uri" -] -_GCSDESTINATION.oneofs_by_name["object_uri"].fields.append( - _GCSDESTINATION.fields_by_name["uri_prefix"] -) -_GCSDESTINATION.fields_by_name[ - "uri_prefix" -].containing_oneof = _GCSDESTINATION.oneofs_by_name["object_uri"] -DESCRIPTOR.message_types_by_name["ExportAssetsRequest"] = _EXPORTASSETSREQUEST -DESCRIPTOR.message_types_by_name["ExportAssetsResponse"] = _EXPORTASSETSRESPONSE -DESCRIPTOR.message_types_by_name[ - "BatchGetAssetsHistoryRequest" -] = _BATCHGETASSETSHISTORYREQUEST -DESCRIPTOR.message_types_by_name[ - "BatchGetAssetsHistoryResponse" -] = _BATCHGETASSETSHISTORYRESPONSE -DESCRIPTOR.message_types_by_name["OutputConfig"] = _OUTPUTCONFIG -DESCRIPTOR.message_types_by_name["GcsDestination"] = _GCSDESTINATION -DESCRIPTOR.enum_types_by_name["ContentType"] = _CONTENTTYPE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ExportAssetsRequest = _reflection.GeneratedProtocolMessageType( - "ExportAssetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _EXPORTASSETSREQUEST, - "__module__": "google.cloud.asset_v1beta1.proto.asset_service_pb2", - "__doc__": """Export asset request. - - Attributes: - parent: - Required. The relative name of the root asset. This can only - be an organization number (such as “organizations/123”), a - project ID (such as “projects/my-project-id”), a project - number (such as “projects/12345”), or a folder number (such as - “folders/123”). - read_time: - Timestamp to take an asset snapshot. This can only be set to a - timestamp between 2018-10-02 UTC (inclusive) and the current - time. If not specified, the current time will be used. Due to - delays in resource data collection and indexing, there is a - volatile window during which running the same query may get - different results. - asset_types: - A list of asset types of which to take a snapshot for. For - example: “google.compute.Disk”. If specified, only matching - assets will be returned. See `Introduction to Cloud Asset - Inventory `__ for all - supported asset types. - content_type: - Asset content type. If not specified, no content but the asset - name will be returned. - output_config: - Required. Output configuration indicating where the results - will be output to. All results will be in newline delimited - JSON format. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.ExportAssetsRequest) - }, -) -_sym_db.RegisterMessage(ExportAssetsRequest) - -ExportAssetsResponse = _reflection.GeneratedProtocolMessageType( - "ExportAssetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _EXPORTASSETSRESPONSE, - "__module__": "google.cloud.asset_v1beta1.proto.asset_service_pb2", - "__doc__": """The export asset response. This message is returned by the [google.lon - grunning.Operations.GetOperation][google.longrunning.Operations.GetOpe - ration] method in the returned [google.longrunning.Operation.response] - [google.longrunning.Operation.response] field. - - Attributes: - read_time: - Time the snapshot was taken. - output_config: - Output configuration indicating where the results were output - to. All results are in JSON format. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.ExportAssetsResponse) - }, -) -_sym_db.RegisterMessage(ExportAssetsResponse) - -BatchGetAssetsHistoryRequest = _reflection.GeneratedProtocolMessageType( - "BatchGetAssetsHistoryRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHGETASSETSHISTORYREQUEST, - "__module__": "google.cloud.asset_v1beta1.proto.asset_service_pb2", - "__doc__": """Batch get assets history request. - - Attributes: - parent: - Required. The relative name of the root asset. It can only be - an organization number (such as “organizations/123”), a - project ID (such as “projects/my-project-id”)“, or a project - number (such as”projects/12345"). - asset_names: - A list of the full names of the assets. For example: ``//compu - te.googleapis.com/projects/my_project_123/zones/zone1/instance - s/instance1``. See `Resource Names `__ for more - info. The request becomes a no-op if the asset name list is - empty, and the max size of the asset name list is 100 in one - request. - content_type: - Optional. The content type. - read_time_window: - Optional. The time window for the asset history. Both - start_time and end_time are optional and if set, it must be - after 2018-10-02 UTC. If end_time is not set, it is default to - current timestamp. If start_time is not set, the snapshot of - the assets at end_time will be returned. The returned results - contain all temporal assets whose time window overlap with - read_time_window. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.BatchGetAssetsHistoryRequest) - }, -) -_sym_db.RegisterMessage(BatchGetAssetsHistoryRequest) - -BatchGetAssetsHistoryResponse = _reflection.GeneratedProtocolMessageType( - "BatchGetAssetsHistoryResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHGETASSETSHISTORYRESPONSE, - "__module__": "google.cloud.asset_v1beta1.proto.asset_service_pb2", - "__doc__": """Batch get assets history response. - - Attributes: - assets: - A list of assets with valid time windows. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.BatchGetAssetsHistoryResponse) - }, -) -_sym_db.RegisterMessage(BatchGetAssetsHistoryResponse) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.asset_v1beta1.proto.asset_service_pb2", - "__doc__": """Output configuration for export assets destination. - - Attributes: - destination: - Asset export destination. - gcs_destination: - Destination on Cloud Storage. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.asset_v1beta1.proto.asset_service_pb2", - "__doc__": """A Cloud Storage location. - - Attributes: - object_uri: - Required. - uri: - The uri of the Cloud Storage object. It’s the same uri that is - used by gsutil. For example: “gs://bucket_name/object_name”. - See `Viewing and Editing Object Metadata - `__ for more information. - uri_prefix: - The uri prefix of all generated Cloud Storage objects. For - example: “gs://bucket_name/object_name_prefix”. Each object - uri is in format: “gs://bucket_name/object_name_prefix// and - only contains assets for that type. starts from 0. For example - :”gs://bucket_name/object_name_prefix/google.compute.disk/0" - is the first shard of output objects containing all - google.compute.disk assets. An INVALID_ARGUMENT error will be - returned if file with the same name - “gs://bucket_name/object_name_prefix” already exists. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - - -DESCRIPTOR._options = None -_EXPORTASSETSREQUEST.fields_by_name["parent"]._options = None -_EXPORTASSETSREQUEST.fields_by_name["output_config"]._options = None -_BATCHGETASSETSHISTORYREQUEST.fields_by_name["parent"]._options = None -_BATCHGETASSETSHISTORYREQUEST.fields_by_name["content_type"]._options = None -_BATCHGETASSETSHISTORYREQUEST.fields_by_name["read_time_window"]._options = None - -_ASSETSERVICE = _descriptor.ServiceDescriptor( - name="AssetService", - full_name="google.cloud.asset.v1beta1.AssetService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\031cloudasset.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=1324, - serialized_end=2032, - methods=[ - _descriptor.MethodDescriptor( - name="ExportAssets", - full_name="google.cloud.asset.v1beta1.AssetService.ExportAssets", - index=0, - containing_service=None, - input_type=_EXPORTASSETSREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002\222\001")/v1beta1/{parent=projects/*}:exportAssets:\001*Z-"(/v1beta1/{parent=folders/*}:exportAssets:\001*Z3"./v1beta1/{parent=organizations/*}:exportAssets:\001*\312Aa\n/google.cloud.asset.v1beta1.ExportAssetsResponse\022.google.cloud.asset.v1beta1.ExportAssetsRequest', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="BatchGetAssetsHistory", - full_name="google.cloud.asset.v1beta1.AssetService.BatchGetAssetsHistory", - index=1, - containing_service=None, - input_type=_BATCHGETASSETSHISTORYREQUEST, - output_type=_BATCHGETASSETSHISTORYRESPONSE, - serialized_options=b"\202\323\344\223\002o\0222/v1beta1/{parent=projects/*}:batchGetAssetsHistoryZ9\0227/v1beta1/{parent=organizations/*}:batchGetAssetsHistory", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_ASSETSERVICE) - -DESCRIPTOR.services_by_name["AssetService"] = _ASSETSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1beta1/proto/asset_service_pb2_grpc.py b/google/cloud/asset_v1beta1/proto/asset_service_pb2_grpc.py deleted file mode 100644 index 1038401b..00000000 --- a/google/cloud/asset_v1beta1/proto/asset_service_pb2_grpc.py +++ /dev/null @@ -1,140 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.asset_v1beta1.proto import ( - asset_service_pb2 as google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) - - -class AssetServiceStub(object): - """Asset service definition. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ExportAssets = channel.unary_unary( - "/google.cloud.asset.v1beta1.AssetService/ExportAssets", - request_serializer=google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.ExportAssetsRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.BatchGetAssetsHistory = channel.unary_unary( - "/google.cloud.asset.v1beta1.AssetService/BatchGetAssetsHistory", - request_serializer=google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryResponse.FromString, - ) - - -class AssetServiceServicer(object): - """Asset service definition. - """ - - def ExportAssets(self, request, context): - """Exports assets with time and resource types to a given Cloud Storage - location. The output format is newline-delimited JSON. - This API implements the - [google.longrunning.Operation][google.longrunning.Operation] API allowing - you to keep track of the export. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def BatchGetAssetsHistory(self, request, context): - """Batch gets the update history of assets that overlap a time window. - For RESOURCE content, this API outputs history with asset in both - non-delete or deleted status. - For IAM_POLICY content, this API outputs history when the asset and its - attached IAM POLICY both exist. This can create gaps in the output history. - If a specified asset does not exist, this API returns an INVALID_ARGUMENT - error. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_AssetServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "ExportAssets": grpc.unary_unary_rpc_method_handler( - servicer.ExportAssets, - request_deserializer=google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.ExportAssetsRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "BatchGetAssetsHistory": grpc.unary_unary_rpc_method_handler( - servicer.BatchGetAssetsHistory, - request_deserializer=google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.asset.v1beta1.AssetService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class AssetService(object): - """Asset service definition. - """ - - @staticmethod - def ExportAssets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1beta1.AssetService/ExportAssets", - google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.ExportAssetsRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def BatchGetAssetsHistory( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1beta1.AssetService/BatchGetAssetsHistory", - google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryRequest.SerializeToString, - google_dot_cloud_dot_asset__v1beta1_dot_proto_dot_asset__service__pb2.BatchGetAssetsHistoryResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/asset_v1beta1/proto/assets.proto b/google/cloud/asset_v1beta1/proto/assets.proto deleted file mode 100644 index 4bb1438c..00000000 --- a/google/cloud/asset_v1beta1/proto/assets.proto +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.asset.v1beta1; - -import "google/api/annotations.proto"; -import "google/api/resource.proto"; -import "google/iam/v1/policy.proto"; -import "google/protobuf/any.proto"; -import "google/protobuf/struct.proto"; -import "google/protobuf/timestamp.proto"; - -option cc_enable_arenas = true; -option csharp_namespace = "Google.Cloud.Asset.V1Beta1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/asset/v1beta1;asset"; -option java_multiple_files = true; -option java_outer_classname = "AssetProto"; -option java_package = "com.google.cloud.asset.v1beta1"; -option php_namespace = "Google\\Cloud\\Asset\\V1beta1"; - -// Temporal asset. In addition to the asset, the temporal asset includes the -// status of the asset and valid from and to time of it. -message TemporalAsset { - // The time window when the asset data and state was observed. - TimeWindow window = 1; - - // If the asset is deleted or not. - bool deleted = 2; - - // Asset. - Asset asset = 3; -} - -// A time window of (start_time, end_time]. -message TimeWindow { - // Start time of the time window (exclusive). - google.protobuf.Timestamp start_time = 1; - - // End time of the time window (inclusive). - // Current timestamp if not specified. - google.protobuf.Timestamp end_time = 2; -} - -// Cloud asset. This includes all Google Cloud Platform resources, -// Cloud IAM policies, and other non-GCP assets. -message Asset { - option (google.api.resource) = { - type: "cloudasset.googleapis.com/Asset" - pattern: "*" - }; - - // The full name of the asset. For example: - // `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - // See [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more information. - string name = 1; - - // Type of the asset. Example: "google.compute.Disk". - string asset_type = 2; - - // Representation of the resource. - Resource resource = 3; - - // Representation of the actual Cloud IAM policy set on a cloud resource. For - // each resource, there must be at most one Cloud IAM policy set on it. - google.iam.v1.Policy iam_policy = 4; -} - -// Representation of a cloud resource. -message Resource { - // The API version. Example: "v1". - string version = 1; - - // The URL of the discovery document containing the resource's JSON schema. - // For example: - // `"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"`. - // It will be left unspecified for resources without a discovery-based API, - // such as Cloud Bigtable. - string discovery_document_uri = 2; - - // The JSON schema name listed in the discovery document. - // Example: "Project". It will be left unspecified for resources (such as - // Cloud Bigtable) without a discovery-based API. - string discovery_name = 3; - - // The REST URL for accessing the resource. An HTTP GET operation using this - // URL returns the resource itself. - // Example: - // `https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`. - // It will be left unspecified for resources without a REST API. - string resource_url = 4; - - // The full name of the immediate parent of this resource. See - // [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more information. - // - // For GCP assets, it is the parent resource defined in the [Cloud IAM policy - // hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy). - // For example: - // `"//cloudresourcemanager.googleapis.com/projects/my_project_123"`. - // - // For third-party assets, it is up to the users to define. - string parent = 5; - - // The content of the resource, in which some sensitive fields are scrubbed - // away and may not be present. - google.protobuf.Struct data = 6; -} diff --git a/google/cloud/asset_v1beta1/proto/assets_pb2.py b/google/cloud/asset_v1beta1/proto/assets_pb2.py deleted file mode 100644 index 781eeca1..00000000 --- a/google/cloud/asset_v1beta1/proto/assets_pb2.py +++ /dev/null @@ -1,556 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1beta1/proto/assets.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1beta1/proto/assets.proto", - package="google.cloud.asset.v1beta1", - syntax="proto3", - serialized_options=b"\n\036com.google.cloud.asset.v1beta1B\nAssetProtoP\001Z?google.golang.org/genproto/googleapis/cloud/asset/v1beta1;asset\370\001\001\252\002\032Google.Cloud.Asset.V1Beta1\312\002\032Google\\Cloud\\Asset\\V1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n-google/cloud/asset_v1beta1/proto/assets.proto\x12\x1agoogle.cloud.asset.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a\x19google/protobuf/any.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\x8a\x01\n\rTemporalAsset\x12\x36\n\x06window\x18\x01 \x01(\x0b\x32&.google.cloud.asset.v1beta1.TimeWindow\x12\x0f\n\x07\x64\x65leted\x18\x02 \x01(\x08\x12\x30\n\x05\x61sset\x18\x03 \x01(\x0b\x32!.google.cloud.asset.v1beta1.Asset"j\n\nTimeWindow\x12.\n\nstart_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\xb5\x01\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\nasset_type\x18\x02 \x01(\t\x12\x36\n\x08resource\x18\x03 \x01(\x0b\x32$.google.cloud.asset.v1beta1.Resource\x12)\n\niam_policy\x18\x04 \x01(\x0b\x32\x15.google.iam.v1.Policy:\'\xea\x41$\n\x1f\x63loudasset.googleapis.com/Asset\x12\x01*"\xa0\x01\n\x08Resource\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x1e\n\x16\x64iscovery_document_uri\x18\x02 \x01(\t\x12\x16\n\x0e\x64iscovery_name\x18\x03 \x01(\t\x12\x14\n\x0cresource_url\x18\x04 \x01(\t\x12\x0e\n\x06parent\x18\x05 \x01(\t\x12%\n\x04\x64\x61ta\x18\x06 \x01(\x0b\x32\x17.google.protobuf.StructB\xac\x01\n\x1e\x63om.google.cloud.asset.v1beta1B\nAssetProtoP\x01Z?google.golang.org/genproto/googleapis/cloud/asset/v1beta1;asset\xf8\x01\x01\xaa\x02\x1aGoogle.Cloud.Asset.V1Beta1\xca\x02\x1aGoogle\\Cloud\\Asset\\V1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_protobuf_dot_any__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_TEMPORALASSET = _descriptor.Descriptor( - name="TemporalAsset", - full_name="google.cloud.asset.v1beta1.TemporalAsset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="window", - full_name="google.cloud.asset.v1beta1.TemporalAsset.window", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="deleted", - full_name="google.cloud.asset.v1beta1.TemporalAsset.deleted", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset", - full_name="google.cloud.asset.v1beta1.TemporalAsset.asset", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=253, - serialized_end=391, -) - - -_TIMEWINDOW = _descriptor.Descriptor( - name="TimeWindow", - full_name="google.cloud.asset.v1beta1.TimeWindow", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.cloud.asset.v1beta1.TimeWindow.start_time", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.asset.v1beta1.TimeWindow.end_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=393, - serialized_end=499, -) - - -_ASSET = _descriptor.Descriptor( - name="Asset", - full_name="google.cloud.asset.v1beta1.Asset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1beta1.Asset.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_type", - full_name="google.cloud.asset.v1beta1.Asset.asset_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.asset.v1beta1.Asset.resource", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="iam_policy", - full_name="google.cloud.asset.v1beta1.Asset.iam_policy", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352A$\n\037cloudasset.googleapis.com/Asset\022\001*", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=502, - serialized_end=683, -) - - -_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.asset.v1beta1.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="version", - full_name="google.cloud.asset.v1beta1.Resource.version", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="discovery_document_uri", - full_name="google.cloud.asset.v1beta1.Resource.discovery_document_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="discovery_name", - full_name="google.cloud.asset.v1beta1.Resource.discovery_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_url", - full_name="google.cloud.asset.v1beta1.Resource.resource_url", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1beta1.Resource.parent", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="data", - full_name="google.cloud.asset.v1beta1.Resource.data", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=686, - serialized_end=846, -) - -_TEMPORALASSET.fields_by_name["window"].message_type = _TIMEWINDOW -_TEMPORALASSET.fields_by_name["asset"].message_type = _ASSET -_TIMEWINDOW.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_TIMEWINDOW.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name["resource"].message_type = _RESOURCE -_ASSET.fields_by_name[ - "iam_policy" -].message_type = ( - google_dot_iam_dot_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._POLICY -) -_RESOURCE.fields_by_name[ - "data" -].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -DESCRIPTOR.message_types_by_name["TemporalAsset"] = _TEMPORALASSET -DESCRIPTOR.message_types_by_name["TimeWindow"] = _TIMEWINDOW -DESCRIPTOR.message_types_by_name["Asset"] = _ASSET -DESCRIPTOR.message_types_by_name["Resource"] = _RESOURCE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TemporalAsset = _reflection.GeneratedProtocolMessageType( - "TemporalAsset", - (_message.Message,), - { - "DESCRIPTOR": _TEMPORALASSET, - "__module__": "google.cloud.asset_v1beta1.proto.assets_pb2", - "__doc__": """Temporal asset. In addition to the asset, the temporal asset includes - the status of the asset and valid from and to time of it. - - Attributes: - window: - The time window when the asset data and state was observed. - deleted: - If the asset is deleted or not. - asset: - Asset. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.TemporalAsset) - }, -) -_sym_db.RegisterMessage(TemporalAsset) - -TimeWindow = _reflection.GeneratedProtocolMessageType( - "TimeWindow", - (_message.Message,), - { - "DESCRIPTOR": _TIMEWINDOW, - "__module__": "google.cloud.asset_v1beta1.proto.assets_pb2", - "__doc__": """A time window of (start_time, end_time]. - - Attributes: - start_time: - Start time of the time window (exclusive). - end_time: - End time of the time window (inclusive). Current timestamp if - not specified. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.TimeWindow) - }, -) -_sym_db.RegisterMessage(TimeWindow) - -Asset = _reflection.GeneratedProtocolMessageType( - "Asset", - (_message.Message,), - { - "DESCRIPTOR": _ASSET, - "__module__": "google.cloud.asset_v1beta1.proto.assets_pb2", - "__doc__": """Cloud asset. This includes all Google Cloud Platform resources, Cloud - IAM policies, and other non-GCP assets. - - Attributes: - name: - - The full name of the asset. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See https://cloud.google.com/apis/design/resource_names#full_resource_name - for more information. - asset_type: - Type of the asset. Example: “google.compute.Disk”. - resource: - Representation of the resource. - iam_policy: - Representation of the actual Cloud IAM policy set on a cloud - resource. For each resource, there must be at most one Cloud - IAM policy set on it. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.Asset) - }, -) -_sym_db.RegisterMessage(Asset) - -Resource = _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _RESOURCE, - "__module__": "google.cloud.asset_v1beta1.proto.assets_pb2", - "__doc__": """Representation of a cloud resource. - - Attributes: - version: - The API version. Example: “v1”. - discovery_document_uri: - The URL of the discovery document containing the resource’s - JSON schema. For example: ``"https://www.googleapis.com/discov - ery/v1/apis/compute/v1/rest"``. It will be left unspecified - for resources without a discovery-based API, such as Cloud - Bigtable. - discovery_name: - The JSON schema name listed in the discovery document. - Example: “Project”. It will be left unspecified for resources - (such as Cloud Bigtable) without a discovery-based API. - resource_url: - The REST URL for accessing the resource. An HTTP GET operation - using this URL returns the resource itself. Example: - ``https://cloudresourcemanager.googleapis.com/v1/projects/my- - project-123``. It will be left unspecified for resources - without a REST API. - parent: - The full name of the immediate parent of this resource. See - `Resource Names `__ for more information. For GCP - assets, it is the parent resource defined in the `Cloud IAM - policy hierarchy `__. For example: ``"//cloudresourcemanager.go - ogleapis.com/projects/my_project_123"``. For third-party - assets, it is up to the users to define. - data: - The content of the resource, in which some sensitive fields - are scrubbed away and may not be present. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1beta1.Resource) - }, -) -_sym_db.RegisterMessage(Resource) - - -DESCRIPTOR._options = None -_ASSET._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1beta1/proto/assets_pb2_grpc.py b/google/cloud/asset_v1beta1/proto/assets_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/asset_v1beta1/proto/assets_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/asset_v1beta1/py.typed b/google/cloud/asset_v1beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/google/cloud/asset_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/google/cloud/asset_v1beta1/services/__init__.py b/google/cloud/asset_v1beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/asset_v1beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/cloud/__init__.py b/google/cloud/asset_v1beta1/services/asset_service/__init__.py similarity index 71% rename from google/cloud/__init__.py rename to google/cloud/asset_v1beta1/services/asset_service/__init__.py index 9a1b64a6..ec3c27d2 100644 --- a/google/cloud/__init__.py +++ b/google/cloud/asset_v1beta1/services/asset_service/__init__.py @@ -1,24 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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. +# -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil +from .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient - __path__ = pkgutil.extend_path(__path__, __name__) +__all__ = ( + "AssetServiceClient", + "AssetServiceAsyncClient", +) diff --git a/google/cloud/asset_v1beta1/services/asset_service/async_client.py b/google/cloud/asset_v1beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..9e34f84d --- /dev/null +++ b/google/cloud/asset_v1beta1/services/asset_service/async_client.py @@ -0,0 +1,237 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.asset_v1beta1.types import asset_service +from google.cloud.asset_v1beta1.types import assets + +from .transports.base import AssetServiceTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = AssetServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(AssetServiceClient).get_transport_class, type(AssetServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = AssetServiceClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def export_assets( + self, + request: asset_service.ExportAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports assets with time and resource types to a given Cloud + Storage location. The output format is newline-delimited JSON. + This API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. + + Args: + request (:class:`~.asset_service.ExportAssetsRequest`): + The request object. Export asset request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.asset_service.ExportAssetsResponse``: The + export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + + request = asset_service.ExportAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_assets, + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # 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, + asset_service.ExportAssetsResponse, + metadata_type=asset_service.ExportAssetsRequest, + ) + + # Done; return the response. + return response + + async def batch_get_assets_history( + self, + request: asset_service.BatchGetAssetsHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: + r"""Batch gets the update history of assets that overlap a time + window. For RESOURCE content, this API outputs history with + asset in both non-delete or deleted status. For IAM_POLICY + content, this API outputs history when the asset and its + attached IAM POLICY both exist. This can create gaps in the + output history. If a specified asset does not exist, this API + returns an INVALID_ARGUMENT error. + + Args: + request (:class:`~.asset_service.BatchGetAssetsHistoryRequest`): + The request object. Batch get assets history request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.BatchGetAssetsHistoryResponse: + Batch get assets history response. + """ + # Create or coerce a protobuf request object. + + request = asset_service.BatchGetAssetsHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_get_assets_history, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceAsyncClient",) diff --git a/google/cloud/asset_v1beta1/services/asset_service/client.py b/google/cloud/asset_v1beta1/services/asset_service/client.py new file mode 100644 index 00000000..532c3fa8 --- /dev/null +++ b/google/cloud/asset_v1beta1/services/asset_service/client.py @@ -0,0 +1,355 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.asset_v1beta1.types import asset_service +from google.cloud.asset_v1beta1.types import assets + +from .transports.base import AssetServiceTransport +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudasset.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AssetServiceTransport): + # transport is a AssetServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def export_assets( + self, + request: asset_service.ExportAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports assets with time and resource types to a given Cloud + Storage location. The output format is newline-delimited JSON. + This API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. + + Args: + request (:class:`~.asset_service.ExportAssetsRequest`): + The request object. Export asset request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.asset_service.ExportAssetsResponse``: The + export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.ExportAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ExportAssetsRequest): + request = asset_service.ExportAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_assets] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + asset_service.ExportAssetsResponse, + metadata_type=asset_service.ExportAssetsRequest, + ) + + # Done; return the response. + return response + + def batch_get_assets_history( + self, + request: asset_service.BatchGetAssetsHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: + r"""Batch gets the update history of assets that overlap a time + window. For RESOURCE content, this API outputs history with + asset in both non-delete or deleted status. For IAM_POLICY + content, this API outputs history when the asset and its + attached IAM POLICY both exist. This can create gaps in the + output history. If a specified asset does not exist, this API + returns an INVALID_ARGUMENT error. + + Args: + request (:class:`~.asset_service.BatchGetAssetsHistoryRequest`): + The request object. Batch get assets history request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.BatchGetAssetsHistoryResponse: + Batch get assets history response. + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.BatchGetAssetsHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.BatchGetAssetsHistoryRequest): + request = asset_service.BatchGetAssetsHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_get_assets_history] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceClient",) diff --git a/google/cloud/asset_v1beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..624eab74 --- /dev/null +++ b/google/cloud/asset_v1beta1/services/asset_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry["grpc"] = AssetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + +__all__ = ( + "AssetServiceTransport", + "AssetServiceGrpcTransport", + "AssetServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/asset_v1beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..fa8dec6e --- /dev/null +++ b/google/cloud/asset_v1beta1/services/asset_service/transports/base.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.asset_v1beta1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.export_assets: gapic_v1.method.wrap_method( + self.export_assets, default_timeout=60.0, client_info=_client_info, + ), + self.batch_get_assets_history: gapic_v1.method.wrap_method( + self.batch_get_assets_history, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def export_assets( + self, + ) -> typing.Callable[ + [asset_service.ExportAssetsRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def batch_get_assets_history( + self, + ) -> typing.Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + typing.Union[ + asset_service.BatchGetAssetsHistoryResponse, + typing.Awaitable[asset_service.BatchGetAssetsHistoryResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("AssetServiceTransport",) diff --git a/google/cloud/asset_v1beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..ead88415 --- /dev/null +++ b/google/cloud/asset_v1beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,290 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.asset_v1beta1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import AssetServiceTransport + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + 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. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def export_assets( + self, + ) -> Callable[[asset_service.ExportAssetsRequest], operations.Operation]: + r"""Return a callable for the export assets method over gRPC. + + Exports assets with time and resource types to a given Cloud + Storage location. The output format is newline-delimited JSON. + This API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. + + Returns: + Callable[[~.ExportAssetsRequest], + ~.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 "export_assets" not in self._stubs: + self._stubs["export_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1beta1.AssetService/ExportAssets", + request_serializer=asset_service.ExportAssetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["export_assets"] + + @property + def batch_get_assets_history( + self, + ) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + asset_service.BatchGetAssetsHistoryResponse, + ]: + r"""Return a callable for the batch get assets history method over gRPC. + + Batch gets the update history of assets that overlap a time + window. For RESOURCE content, this API outputs history with + asset in both non-delete or deleted status. For IAM_POLICY + content, this API outputs history when the asset and its + attached IAM POLICY both exist. This can create gaps in the + output history. If a specified asset does not exist, this API + returns an INVALID_ARGUMENT error. + + Returns: + Callable[[~.BatchGetAssetsHistoryRequest], + ~.BatchGetAssetsHistoryResponse]: + 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 "batch_get_assets_history" not in self._stubs: + self._stubs["batch_get_assets_history"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1beta1.AssetService/BatchGetAssetsHistory", + request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, + response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, + ) + return self._stubs["batch_get_assets_history"] + + +__all__ = ("AssetServiceGrpcTransport",) diff --git a/google/cloud/asset_v1beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..2f7fef7a --- /dev/null +++ b/google/cloud/asset_v1beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,283 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1beta1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: 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: + address (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 ignored if ``channel`` 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`. + 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # 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. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def export_assets( + self, + ) -> Callable[[asset_service.ExportAssetsRequest], Awaitable[operations.Operation]]: + r"""Return a callable for the export assets method over gRPC. + + Exports assets with time and resource types to a given Cloud + Storage location. The output format is newline-delimited JSON. + This API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. + + Returns: + Callable[[~.ExportAssetsRequest], + 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 "export_assets" not in self._stubs: + self._stubs["export_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1beta1.AssetService/ExportAssets", + request_serializer=asset_service.ExportAssetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["export_assets"] + + @property + def batch_get_assets_history( + self, + ) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + Awaitable[asset_service.BatchGetAssetsHistoryResponse], + ]: + r"""Return a callable for the batch get assets history method over gRPC. + + Batch gets the update history of assets that overlap a time + window. For RESOURCE content, this API outputs history with + asset in both non-delete or deleted status. For IAM_POLICY + content, this API outputs history when the asset and its + attached IAM POLICY both exist. This can create gaps in the + output history. If a specified asset does not exist, this API + returns an INVALID_ARGUMENT error. + + Returns: + Callable[[~.BatchGetAssetsHistoryRequest], + Awaitable[~.BatchGetAssetsHistoryResponse]]: + 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 "batch_get_assets_history" not in self._stubs: + self._stubs["batch_get_assets_history"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1beta1.AssetService/BatchGetAssetsHistory", + request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, + response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, + ) + return self._stubs["batch_get_assets_history"] + + +__all__ = ("AssetServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/asset_v1beta1/types.py b/google/cloud/asset_v1beta1/types.py deleted file mode 100644 index b2daa8ff..00000000 --- a/google/cloud/asset_v1beta1/types.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.asset_v1beta1.proto import asset_service_pb2 -from google.cloud.asset_v1beta1.proto import assets_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import struct_pb2 -from google.protobuf import timestamp_pb2 -from google.rpc import status_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - policy_pb2, - operations_pb2, - any_pb2, - struct_pb2, - timestamp_pb2, - status_pb2, - expr_pb2, -] - -_local_modules = [ - asset_service_pb2, - assets_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.asset_v1beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/asset_v1beta1/types/__init__.py b/google/cloud/asset_v1beta1/types/__init__.py new file mode 100644 index 00000000..1269a393 --- /dev/null +++ b/google/cloud/asset_v1beta1/types/__init__.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .assets import ( + TemporalAsset, + TimeWindow, + Asset, + Resource, +) +from .asset_service import ( + ExportAssetsRequest, + ExportAssetsResponse, + BatchGetAssetsHistoryRequest, + BatchGetAssetsHistoryResponse, + OutputConfig, + GcsDestination, +) + + +__all__ = ( + "TemporalAsset", + "TimeWindow", + "Asset", + "Resource", + "ExportAssetsRequest", + "ExportAssetsResponse", + "BatchGetAssetsHistoryRequest", + "BatchGetAssetsHistoryResponse", + "OutputConfig", + "GcsDestination", +) diff --git a/google/cloud/asset_v1beta1/types/asset_service.py b/google/cloud/asset_v1beta1/types/asset_service.py new file mode 100644 index 00000000..6294f3e7 --- /dev/null +++ b/google/cloud/asset_v1beta1/types/asset_service.py @@ -0,0 +1,210 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.asset_v1beta1.types import assets as gca_assets +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1beta1", + manifest={ + "ContentType", + "ExportAssetsRequest", + "ExportAssetsResponse", + "BatchGetAssetsHistoryRequest", + "BatchGetAssetsHistoryResponse", + "OutputConfig", + "GcsDestination", + }, +) + + +class ContentType(proto.Enum): + r"""Asset content type.""" + CONTENT_TYPE_UNSPECIFIED = 0 + RESOURCE = 1 + IAM_POLICY = 2 + + +class ExportAssetsRequest(proto.Message): + r"""Export asset request. + + Attributes: + parent (str): + Required. The relative name of the root + asset. This can only be an organization number + (such as "organizations/123"), a project ID + (such as "projects/my-project-id"), a project + number (such as "projects/12345"), or a folder + number (such as "folders/123"). + read_time (~.timestamp.Timestamp): + Timestamp to take an asset snapshot. This can + only be set to a timestamp between 2018-10-02 + UTC (inclusive) and the current time. If not + specified, the current time will be used. Due to + delays in resource data collection and indexing, + there is a volatile window during which running + the same query may get different results. + asset_types (Sequence[str]): + A list of asset types of which to take a snapshot for. For + example: "google.compute.Disk". If specified, only matching + assets will be returned. See `Introduction to Cloud Asset + Inventory `__ + for all supported asset types. + content_type (~.asset_service.ContentType): + Asset content type. If not specified, no + content but the asset name will be returned. + output_config (~.asset_service.OutputConfig): + Required. Output configuration indicating + where the results will be output to. All results + will be in newline delimited JSON format. + """ + + parent = proto.Field(proto.STRING, number=1) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + asset_types = proto.RepeatedField(proto.STRING, number=3) + + content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) + + output_config = proto.Field(proto.MESSAGE, number=5, message="OutputConfig",) + + +class ExportAssetsResponse(proto.Message): + r"""The export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + Attributes: + read_time (~.timestamp.Timestamp): + Time the snapshot was taken. + output_config (~.asset_service.OutputConfig): + Output configuration indicating where the + results were output to. All results are in JSON + format. + """ + + read_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + + output_config = proto.Field(proto.MESSAGE, number=2, message="OutputConfig",) + + +class BatchGetAssetsHistoryRequest(proto.Message): + r"""Batch get assets history request. + + Attributes: + parent (str): + Required. The relative name of the root + asset. It can only be an organization number + (such as "organizations/123"), a project ID + (such as "projects/my-project-id")", or a + project number (such as "projects/12345"). + asset_names (Sequence[str]): + A list of the full names of the assets. For example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more info. + + The request becomes a no-op if the asset name list is empty, + and the max size of the asset name list is 100 in one + request. + content_type (~.asset_service.ContentType): + Optional. The content type. + read_time_window (~.gca_assets.TimeWindow): + Optional. The time window for the asset history. Both + start_time and end_time are optional and if set, it must be + after 2018-10-02 UTC. If end_time is not set, it is default + to current timestamp. If start_time is not set, the snapshot + of the assets at end_time will be returned. The returned + results contain all temporal assets whose time window + overlap with read_time_window. + """ + + parent = proto.Field(proto.STRING, number=1) + + asset_names = proto.RepeatedField(proto.STRING, number=2) + + content_type = proto.Field(proto.ENUM, number=3, enum="ContentType",) + + read_time_window = proto.Field( + proto.MESSAGE, number=4, message=gca_assets.TimeWindow, + ) + + +class BatchGetAssetsHistoryResponse(proto.Message): + r"""Batch get assets history response. + + Attributes: + assets (Sequence[~.gca_assets.TemporalAsset]): + A list of assets with valid time windows. + """ + + assets = proto.RepeatedField( + proto.MESSAGE, number=1, message=gca_assets.TemporalAsset, + ) + + +class OutputConfig(proto.Message): + r"""Output configuration for export assets destination. + + Attributes: + gcs_destination (~.asset_service.GcsDestination): + Destination on Cloud Storage. + """ + + gcs_destination = proto.Field( + proto.MESSAGE, number=1, oneof="destination", message="GcsDestination", + ) + + +class GcsDestination(proto.Message): + r"""A Cloud Storage location. + + Attributes: + uri (str): + The uri of the Cloud Storage object. It's the same uri that + is used by gsutil. For example: + "gs://bucket_name/object_name". See `Viewing and Editing + Object + Metadata `__ + for more information. + uri_prefix (str): + The uri prefix of all generated Cloud Storage objects. For + example: "gs://bucket_name/object_name_prefix". Each object + uri is in format: "gs://bucket_name/object_name_prefix// and + only contains assets for that type. starts from 0. For + example: + "gs://bucket_name/object_name_prefix/google.compute.disk/0" + is the first shard of output objects containing all + google.compute.disk assets. An INVALID_ARGUMENT error will + be returned if file with the same name + "gs://bucket_name/object_name_prefix" already exists. + """ + + uri = proto.Field(proto.STRING, number=1, oneof="object_uri") + + uri_prefix = proto.Field(proto.STRING, number=2, oneof="object_uri") + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1beta1/types/assets.py b/google/cloud/asset_v1beta1/types/assets.py new file mode 100644 index 00000000..6f06635b --- /dev/null +++ b/google/cloud/asset_v1beta1/types/assets.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1beta1", + manifest={"TemporalAsset", "TimeWindow", "Asset", "Resource",}, +) + + +class TemporalAsset(proto.Message): + r"""Temporal asset. In addition to the asset, the temporal asset + includes the status of the asset and valid from and to time of + it. + + Attributes: + window (~.assets.TimeWindow): + The time window when the asset data and state + was observed. + deleted (bool): + If the asset is deleted or not. + asset (~.assets.Asset): + Asset. + """ + + window = proto.Field(proto.MESSAGE, number=1, message="TimeWindow",) + + deleted = proto.Field(proto.BOOL, number=2) + + asset = proto.Field(proto.MESSAGE, number=3, message="Asset",) + + +class TimeWindow(proto.Message): + r"""A time window of (start_time, end_time]. + + Attributes: + start_time (~.timestamp.Timestamp): + Start time of the time window (exclusive). + end_time (~.timestamp.Timestamp): + End time of the time window (inclusive). + Current timestamp if not specified. + """ + + start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + +class Asset(proto.Message): + r"""Cloud asset. This includes all Google Cloud Platform + resources, Cloud IAM policies, and other non-GCP assets. + + Attributes: + name (str): + The full name of the asset. For example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more information. + asset_type (str): + Type of the asset. Example: + "google.compute.Disk". + resource (~.assets.Resource): + Representation of the resource. + iam_policy (~.policy.Policy): + Representation of the actual Cloud IAM policy + set on a cloud resource. For each resource, + there must be at most one Cloud IAM policy set + on it. + """ + + name = proto.Field(proto.STRING, number=1) + + asset_type = proto.Field(proto.STRING, number=2) + + resource = proto.Field(proto.MESSAGE, number=3, message="Resource",) + + iam_policy = proto.Field(proto.MESSAGE, number=4, message=policy.Policy,) + + +class Resource(proto.Message): + r"""Representation of a cloud resource. + + Attributes: + version (str): + The API version. Example: "v1". + discovery_document_uri (str): + The URL of the discovery document containing the resource's + JSON schema. For example: + ``"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"``. + It will be left unspecified for resources without a + discovery-based API, such as Cloud Bigtable. + discovery_name (str): + The JSON schema name listed in the discovery + document. Example: "Project". It will be left + unspecified for resources (such as Cloud + Bigtable) without a discovery-based API. + resource_url (str): + The REST URL for accessing the resource. An HTTP GET + operation using this URL returns the resource itself. + Example: + ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123``. + It will be left unspecified for resources without a REST + API. + parent (str): + The full name of the immediate parent of this resource. See + `Resource + Names `__ + for more information. + + For GCP assets, it is the parent resource defined in the + `Cloud IAM policy + hierarchy `__. + For example: + ``"//cloudresourcemanager.googleapis.com/projects/my_project_123"``. + + For third-party assets, it is up to the users to define. + data (~.struct.Struct): + The content of the resource, in which some + sensitive fields are scrubbed away and may not + be present. + """ + + version = proto.Field(proto.STRING, number=1) + + discovery_document_uri = proto.Field(proto.STRING, number=2) + + discovery_name = proto.Field(proto.STRING, number=3) + + resource_url = proto.Field(proto.STRING, number=4) + + parent = proto.Field(proto.STRING, number=5) + + data = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p1beta1/__init__.py b/google/cloud/asset_v1p1beta1/__init__.py index dbcb4243..05b10389 100644 --- a/google/cloud/asset_v1p1beta1/__init__.py +++ b/google/cloud/asset_v1p1beta1/__init__.py @@ -1,42 +1,37 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.asset_v1p1beta1 import types -from google.cloud.asset_v1p1beta1.gapic import asset_service_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class AssetServiceClient(asset_service_client.AssetServiceClient): - __doc__ = asset_service_client.AssetServiceClient.__doc__ +from .services.asset_service import AssetServiceClient +from .types.asset_service import SearchAllIamPoliciesRequest +from .types.asset_service import SearchAllIamPoliciesResponse +from .types.asset_service import SearchAllResourcesRequest +from .types.asset_service import SearchAllResourcesResponse +from .types.assets import IamPolicySearchResult +from .types.assets import Permissions +from .types.assets import StandardResourceMetadata __all__ = ( - "types", + "IamPolicySearchResult", + "Permissions", + "SearchAllIamPoliciesRequest", + "SearchAllIamPoliciesResponse", + "SearchAllResourcesRequest", + "SearchAllResourcesResponse", + "StandardResourceMetadata", "AssetServiceClient", ) diff --git a/google/cloud/asset_v1p1beta1/gapic/__init__.py b/google/cloud/asset_v1p1beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p1beta1/gapic/asset_service_client.py b/google/cloud/asset_v1p1beta1/gapic/asset_service_client.py deleted file mode 100644 index 1c5a93df..00000000 --- a/google/cloud/asset_v1p1beta1/gapic/asset_service_client.py +++ /dev/null @@ -1,432 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Accesses the google.cloud.asset.v1p1beta1 AssetService API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import grpc - -from google.cloud.asset_v1p1beta1.gapic import asset_service_client_config -from google.cloud.asset_v1p1beta1.gapic.transports import asset_service_grpc_transport -from google.cloud.asset_v1p1beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p1beta1.proto import asset_service_pb2_grpc - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-asset",).version - - -class AssetServiceClient(object): - """Asset service definition.""" - - SERVICE_ADDRESS = "cloudasset.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.asset.v1p1beta1.AssetService" - - @classmethod - def from_service_account_file(cls, filename, *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: - AssetServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.AssetServiceGrpcTransport, - Callable[[~.Credentials, type], ~.AssetServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = asset_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=asset_service_grpc_transport.AssetServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = asset_service_grpc_transport.AssetServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def search_all_resources( - self, - scope, - query=None, - asset_types=None, - page_size=None, - order_by=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Searches all the resources under a given accessible CRM scope - (project/folder/organization). This RPC gives callers - especially admins the ability to search all the resources under a scope, - even if they don't have .get permission of all the resources. Callers - should have cloud.assets.SearchAllResources permission on the requested - scope, otherwise it will be rejected. - - Example: - >>> from google.cloud import asset_v1p1beta1 - >>> - >>> client = asset_v1p1beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `scope`: - >>> scope = '' - >>> - >>> # Iterate over all results - >>> for element in client.search_all_resources(scope): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.search_all_resources(scope).pages: - ... for element in page: - ... # process element - ... pass - - Args: - scope (str): Required. The relative name of an asset. The search is limited to - the resources within the ``scope``. The allowed value must be: - - - Organization number (such as "organizations/123") - - Folder number(such as "folders/1234") - - Project number (such as "projects/12345") - - Project id (such as "projects/abc") - query (str): Optional. The query statement. - asset_types (list[str]): Optional. A list of asset types that this request searches for. If empty, it will - search all the supported asset types. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - order_by (str): Optional. A comma separated list of fields specifying the sorting order of the - results. The default order is ascending. Add " desc" after the field name - to indicate descending order. Redundant space characters are ignored. For - example, " foo , bar desc ". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.asset_v1p1beta1.types.StandardResourceMetadata` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "search_all_resources" not in self._inner_api_calls: - self._inner_api_calls[ - "search_all_resources" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.search_all_resources, - default_retry=self._method_configs["SearchAllResources"].retry, - default_timeout=self._method_configs["SearchAllResources"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.SearchAllResourcesRequest( - scope=scope, - query=query, - asset_types=asset_types, - page_size=page_size, - order_by=order_by, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("scope", scope)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["search_all_resources"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def search_all_iam_policies( - self, - scope, - query=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Searches all the IAM policies under a given accessible CRM scope - (project/folder/organization). This RPC gives callers - especially admins the ability to search all the IAM policies under a scope, - even if they don't have .getIamPolicy permission of all the IAM policies. - Callers should have cloud.assets.SearchAllIamPolicies permission on the - requested scope, otherwise it will be rejected. - - Example: - >>> from google.cloud import asset_v1p1beta1 - >>> - >>> client = asset_v1p1beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `scope`: - >>> scope = '' - >>> - >>> # Iterate over all results - >>> for element in client.search_all_iam_policies(scope): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.search_all_iam_policies(scope).pages: - ... for element in page: - ... # process element - ... pass - - Args: - scope (str): Required. The relative name of an asset. The search is limited to - the resources within the ``scope``. The allowed value must be: - - - Organization number (such as "organizations/123") - - Folder number(such as "folders/1234") - - Project number (such as "projects/12345") - - Project id (such as "projects/abc") - query (str): Optional. The query statement. Examples: - - - "policy:myuser@mydomain.com" - - "policy:(myuser@mydomain.com viewer)" - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.asset_v1p1beta1.types.IamPolicySearchResult` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "search_all_iam_policies" not in self._inner_api_calls: - self._inner_api_calls[ - "search_all_iam_policies" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.search_all_iam_policies, - default_retry=self._method_configs["SearchAllIamPolicies"].retry, - default_timeout=self._method_configs["SearchAllIamPolicies"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.SearchAllIamPoliciesRequest( - scope=scope, query=query, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("scope", scope)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["search_all_iam_policies"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator diff --git a/google/cloud/asset_v1p1beta1/gapic/asset_service_client_config.py b/google/cloud/asset_v1p1beta1/gapic/asset_service_client_config.py deleted file mode 100644 index 82814615..00000000 --- a/google/cloud/asset_v1p1beta1/gapic/asset_service_client_config.py +++ /dev/null @@ -1,42 +0,0 @@ -config = { - "interfaces": { - "google.cloud.asset.v1p1beta1.AssetService": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 15000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 15000, - "total_timeout_millis": 15000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "SearchAllResources": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "SearchAllIamPolicies": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/asset_v1p1beta1/gapic/transports/__init__.py b/google/cloud/asset_v1p1beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p1beta1/gapic/transports/asset_service_grpc_transport.py b/google/cloud/asset_v1p1beta1/gapic/transports/asset_service_grpc_transport.py deleted file mode 100644 index 5bffbf51..00000000 --- a/google/cloud/asset_v1p1beta1/gapic/transports/asset_service_grpc_transport.py +++ /dev/null @@ -1,144 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 google.api_core.grpc_helpers - -from google.cloud.asset_v1p1beta1.proto import asset_service_pb2_grpc - - -class AssetServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.asset.v1p1beta1 AssetService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="cloudasset.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "asset_service_stub": asset_service_pb2_grpc.AssetServiceStub(channel), - } - - @classmethod - def create_channel( - cls, address="cloudasset.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def search_all_resources(self): - """Return the gRPC stub for :meth:`AssetServiceClient.search_all_resources`. - - Searches all the resources under a given accessible CRM scope - (project/folder/organization). This RPC gives callers - especially admins the ability to search all the resources under a scope, - even if they don't have .get permission of all the resources. Callers - should have cloud.assets.SearchAllResources permission on the requested - scope, otherwise it will be rejected. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].SearchAllResources - - @property - def search_all_iam_policies(self): - """Return the gRPC stub for :meth:`AssetServiceClient.search_all_iam_policies`. - - Searches all the IAM policies under a given accessible CRM scope - (project/folder/organization). This RPC gives callers - especially admins the ability to search all the IAM policies under a scope, - even if they don't have .getIamPolicy permission of all the IAM policies. - Callers should have cloud.assets.SearchAllIamPolicies permission on the - requested scope, otherwise it will be rejected. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].SearchAllIamPolicies diff --git a/google/cloud/asset_v1p1beta1/proto/__init__.py b/google/cloud/asset_v1p1beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p1beta1/proto/asset_service_pb2.py b/google/cloud/asset_v1p1beta1/proto/asset_service_pb2.py deleted file mode 100644 index 22dc8014..00000000 --- a/google/cloud/asset_v1p1beta1/proto/asset_service_pb2.py +++ /dev/null @@ -1,593 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1p1beta1/proto/asset_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.cloud.asset_v1p1beta1.proto import ( - assets_pb2 as google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_assets__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1p1beta1/proto/asset_service.proto", - package="google.cloud.asset.v1p1beta1", - syntax="proto3", - serialized_options=b"\n com.google.cloud.asset.v1p1beta1B\021AssetServiceProtoP\001ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p1beta1;asset\252\002\034Google.Cloud.Asset.V1P1Beta1\312\002\034Google\\Cloud\\Asset\\V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n6google/cloud/asset_v1p1beta1/proto/asset_service.proto\x12\x1cgoogle.cloud.asset.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a/google/cloud/asset_v1p1beta1/proto/assets.proto"\xa5\x01\n\x19SearchAllResourcesRequest\x12\x12\n\x05scope\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x12\n\x05query\x18\x02 \x01(\tB\x03\xe0\x41\x01\x12\x18\n\x0b\x61sset_types\x18\x03 \x03(\tB\x03\xe0\x41\x01\x12\x16\n\tpage_size\x18\x04 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x05 \x01(\tB\x03\xe0\x41\x01\x12\x15\n\x08order_by\x18\n \x01(\tB\x03\xe0\x41\x01"~\n\x1aSearchAllResourcesResponse\x12G\n\x07results\x18\x01 \x03(\x0b\x32\x36.google.cloud.asset.v1p1beta1.StandardResourceMetadata\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"v\n\x1bSearchAllIamPoliciesRequest\x12\x12\n\x05scope\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x12\n\x05query\x18\x02 \x01(\tB\x03\xe0\x41\x01\x12\x16\n\tpage_size\x18\x03 \x01(\x05\x42\x03\xe0\x41\x01\x12\x17\n\npage_token\x18\x04 \x01(\tB\x03\xe0\x41\x01"}\n\x1cSearchAllIamPoliciesResponse\x12\x44\n\x07results\x18\x01 \x03(\x0b\x32\x33.google.cloud.asset.v1p1beta1.IamPolicySearchResult\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t2\x89\x04\n\x0c\x41ssetService\x12\xd5\x01\n\x12SearchAllResources\x12\x37.google.cloud.asset.v1p1beta1.SearchAllResourcesRequest\x1a\x38.google.cloud.asset.v1p1beta1.SearchAllResourcesResponse"L\x82\xd3\xe4\x93\x02,\x12*/v1p1beta1/{scope=*/*}/resources:searchAll\xda\x41\x17scope,query,asset_types\x12\xd1\x01\n\x14SearchAllIamPolicies\x12\x39.google.cloud.asset.v1p1beta1.SearchAllIamPoliciesRequest\x1a:.google.cloud.asset.v1p1beta1.SearchAllIamPoliciesResponse"B\x82\xd3\xe4\x93\x02.\x12,/v1p1beta1/{scope=*/*}/iamPolicies:searchAll\xda\x41\x0bscope,query\x1aM\xca\x41\x19\x63loudasset.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xb8\x01\n com.google.cloud.asset.v1p1beta1B\x11\x41ssetServiceProtoP\x01ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p1beta1;asset\xaa\x02\x1cGoogle.Cloud.Asset.V1P1Beta1\xca\x02\x1cGoogle\\Cloud\\Asset\\V1p1beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_assets__pb2.DESCRIPTOR, - ], -) - - -_SEARCHALLRESOURCESREQUEST = _descriptor.Descriptor( - name="SearchAllResourcesRequest", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="scope", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesRequest.scope", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="query", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesRequest.query", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_types", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesRequest.asset_types", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesRequest.page_size", - index=3, - number=4, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesRequest.page_token", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="order_by", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesRequest.order_by", - index=5, - number=10, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=226, - serialized_end=391, -) - - -_SEARCHALLRESOURCESRESPONSE = _descriptor.Descriptor( - name="SearchAllResourcesResponse", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="results", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesResponse.results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.asset.v1p1beta1.SearchAllResourcesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=393, - serialized_end=519, -) - - -_SEARCHALLIAMPOLICIESREQUEST = _descriptor.Descriptor( - name="SearchAllIamPoliciesRequest", - full_name="google.cloud.asset.v1p1beta1.SearchAllIamPoliciesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="scope", - full_name="google.cloud.asset.v1p1beta1.SearchAllIamPoliciesRequest.scope", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="query", - full_name="google.cloud.asset.v1p1beta1.SearchAllIamPoliciesRequest.query", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.asset.v1p1beta1.SearchAllIamPoliciesRequest.page_size", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.asset.v1p1beta1.SearchAllIamPoliciesRequest.page_token", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=521, - serialized_end=639, -) - - -_SEARCHALLIAMPOLICIESRESPONSE = _descriptor.Descriptor( - name="SearchAllIamPoliciesResponse", - full_name="google.cloud.asset.v1p1beta1.SearchAllIamPoliciesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="results", - full_name="google.cloud.asset.v1p1beta1.SearchAllIamPoliciesResponse.results", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.asset.v1p1beta1.SearchAllIamPoliciesResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=641, - serialized_end=766, -) - -_SEARCHALLRESOURCESRESPONSE.fields_by_name[ - "results" -].message_type = ( - google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_assets__pb2._STANDARDRESOURCEMETADATA -) -_SEARCHALLIAMPOLICIESRESPONSE.fields_by_name[ - "results" -].message_type = ( - google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_assets__pb2._IAMPOLICYSEARCHRESULT -) -DESCRIPTOR.message_types_by_name[ - "SearchAllResourcesRequest" -] = _SEARCHALLRESOURCESREQUEST -DESCRIPTOR.message_types_by_name[ - "SearchAllResourcesResponse" -] = _SEARCHALLRESOURCESRESPONSE -DESCRIPTOR.message_types_by_name[ - "SearchAllIamPoliciesRequest" -] = _SEARCHALLIAMPOLICIESREQUEST -DESCRIPTOR.message_types_by_name[ - "SearchAllIamPoliciesResponse" -] = _SEARCHALLIAMPOLICIESRESPONSE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -SearchAllResourcesRequest = _reflection.GeneratedProtocolMessageType( - "SearchAllResourcesRequest", - (_message.Message,), - { - "DESCRIPTOR": _SEARCHALLRESOURCESREQUEST, - "__module__": "google.cloud.asset_v1p1beta1.proto.asset_service_pb2", - "__doc__": """Search all resources request. - - Attributes: - scope: - Required. The relative name of an asset. The search is limited - to the resources within the ``scope``. The allowed value must - be: \* Organization number (such as “organizations/123”) \* - Folder number(such as “folders/1234”) \* Project number (such - as “projects/12345”) \* Project id (such as “projects/abc”) - query: - Optional. The query statement. - asset_types: - Optional. A list of asset types that this request searches - for. If empty, it will search all the supported asset types. - page_size: - Optional. The page size for search result pagination. Page - size is capped at 500 even if a larger value is given. If set - to zero, server will pick an appropriate default. Returned - results may be fewer than requested. When this happens, there - could be more results as long as ``next_page_token`` is - returned. - page_token: - Optional. If present, then retrieve the next batch of results - from the preceding call to this method. ``page_token`` must be - the value of ``next_page_token`` from the previous response. - The values of all other method parameters, must be identical - to those in the previous call. - order_by: - Optional. A comma separated list of fields specifying the - sorting order of the results. The default order is ascending. - Add " desc" after the field name to indicate descending order. - Redundant space characters are ignored. For example, " foo , - bar desc ". - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.SearchAllResourcesRequest) - }, -) -_sym_db.RegisterMessage(SearchAllResourcesRequest) - -SearchAllResourcesResponse = _reflection.GeneratedProtocolMessageType( - "SearchAllResourcesResponse", - (_message.Message,), - { - "DESCRIPTOR": _SEARCHALLRESOURCESRESPONSE, - "__module__": "google.cloud.asset_v1p1beta1.proto.asset_service_pb2", - "__doc__": """Search all resources response. - - Attributes: - results: - A list of resource that match the search query. - next_page_token: - If there are more results than those appearing in this - response, then ``next_page_token`` is included. To get the - next set of results, call this method again using the value of - ``next_page_token`` as ``page_token``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.SearchAllResourcesResponse) - }, -) -_sym_db.RegisterMessage(SearchAllResourcesResponse) - -SearchAllIamPoliciesRequest = _reflection.GeneratedProtocolMessageType( - "SearchAllIamPoliciesRequest", - (_message.Message,), - { - "DESCRIPTOR": _SEARCHALLIAMPOLICIESREQUEST, - "__module__": "google.cloud.asset_v1p1beta1.proto.asset_service_pb2", - "__doc__": """Search all IAM policies request. - - Attributes: - scope: - Required. The relative name of an asset. The search is limited - to the resources within the ``scope``. The allowed value must - be: \* Organization number (such as “organizations/123”) \* - Folder number(such as “folders/1234”) \* Project number (such - as “projects/12345”) \* Project id (such as “projects/abc”) - query: - Optional. The query statement. Examples: \* - “policy:myuser@mydomain.com” \* “policy:(myuser@mydomain.com - viewer)” - page_size: - Optional. The page size for search result pagination. Page - size is capped at 500 even if a larger value is given. If set - to zero, server will pick an appropriate default. Returned - results may be fewer than requested. When this happens, there - could be more results as long as ``next_page_token`` is - returned. - page_token: - Optional. If present, retrieve the next batch of results from - the preceding call to this method. ``page_token`` must be the - value of ``next_page_token`` from the previous response. The - values of all other method parameters must be identical to - those in the previous call. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.SearchAllIamPoliciesRequest) - }, -) -_sym_db.RegisterMessage(SearchAllIamPoliciesRequest) - -SearchAllIamPoliciesResponse = _reflection.GeneratedProtocolMessageType( - "SearchAllIamPoliciesResponse", - (_message.Message,), - { - "DESCRIPTOR": _SEARCHALLIAMPOLICIESRESPONSE, - "__module__": "google.cloud.asset_v1p1beta1.proto.asset_service_pb2", - "__doc__": """Search all IAM policies response. - - Attributes: - results: - A list of IamPolicy that match the search query. Related - information such as the associated resource is returned along - with the policy. - next_page_token: - Set if there are more results than those appearing in this - response; to get the next set of results, call this method - again, using this value as the ``page_token``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.SearchAllIamPoliciesResponse) - }, -) -_sym_db.RegisterMessage(SearchAllIamPoliciesResponse) - - -DESCRIPTOR._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["scope"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["query"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["asset_types"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["page_size"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["page_token"]._options = None -_SEARCHALLRESOURCESREQUEST.fields_by_name["order_by"]._options = None -_SEARCHALLIAMPOLICIESREQUEST.fields_by_name["scope"]._options = None -_SEARCHALLIAMPOLICIESREQUEST.fields_by_name["query"]._options = None -_SEARCHALLIAMPOLICIESREQUEST.fields_by_name["page_size"]._options = None -_SEARCHALLIAMPOLICIESREQUEST.fields_by_name["page_token"]._options = None - -_ASSETSERVICE = _descriptor.ServiceDescriptor( - name="AssetService", - full_name="google.cloud.asset.v1p1beta1.AssetService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\031cloudasset.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=769, - serialized_end=1290, - methods=[ - _descriptor.MethodDescriptor( - name="SearchAllResources", - full_name="google.cloud.asset.v1p1beta1.AssetService.SearchAllResources", - index=0, - containing_service=None, - input_type=_SEARCHALLRESOURCESREQUEST, - output_type=_SEARCHALLRESOURCESRESPONSE, - serialized_options=b"\202\323\344\223\002,\022*/v1p1beta1/{scope=*/*}/resources:searchAll\332A\027scope,query,asset_types", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="SearchAllIamPolicies", - full_name="google.cloud.asset.v1p1beta1.AssetService.SearchAllIamPolicies", - index=1, - containing_service=None, - input_type=_SEARCHALLIAMPOLICIESREQUEST, - output_type=_SEARCHALLIAMPOLICIESRESPONSE, - serialized_options=b"\202\323\344\223\002.\022,/v1p1beta1/{scope=*/*}/iamPolicies:searchAll\332A\013scope,query", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_ASSETSERVICE) - -DESCRIPTOR.services_by_name["AssetService"] = _ASSETSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1p1beta1/proto/asset_service_pb2_grpc.py b/google/cloud/asset_v1p1beta1/proto/asset_service_pb2_grpc.py deleted file mode 100644 index 42767655..00000000 --- a/google/cloud/asset_v1p1beta1/proto/asset_service_pb2_grpc.py +++ /dev/null @@ -1,137 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.asset_v1p1beta1.proto import ( - asset_service_pb2 as google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2, -) - - -class AssetServiceStub(object): - """Asset service definition. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.SearchAllResources = channel.unary_unary( - "/google.cloud.asset.v1p1beta1.AssetService/SearchAllResources", - request_serializer=google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllResourcesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllResourcesResponse.FromString, - ) - self.SearchAllIamPolicies = channel.unary_unary( - "/google.cloud.asset.v1p1beta1.AssetService/SearchAllIamPolicies", - request_serializer=google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesResponse.FromString, - ) - - -class AssetServiceServicer(object): - """Asset service definition. - """ - - def SearchAllResources(self, request, context): - """Searches all the resources under a given accessible CRM scope - (project/folder/organization). This RPC gives callers - especially admins the ability to search all the resources under a scope, - even if they don't have .get permission of all the resources. Callers - should have cloud.assets.SearchAllResources permission on the requested - scope, otherwise it will be rejected. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def SearchAllIamPolicies(self, request, context): - """Searches all the IAM policies under a given accessible CRM scope - (project/folder/organization). This RPC gives callers - especially admins the ability to search all the IAM policies under a scope, - even if they don't have .getIamPolicy permission of all the IAM policies. - Callers should have cloud.assets.SearchAllIamPolicies permission on the - requested scope, otherwise it will be rejected. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_AssetServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "SearchAllResources": grpc.unary_unary_rpc_method_handler( - servicer.SearchAllResources, - request_deserializer=google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllResourcesRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllResourcesResponse.SerializeToString, - ), - "SearchAllIamPolicies": grpc.unary_unary_rpc_method_handler( - servicer.SearchAllIamPolicies, - request_deserializer=google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.asset.v1p1beta1.AssetService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class AssetService(object): - """Asset service definition. - """ - - @staticmethod - def SearchAllResources( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1p1beta1.AssetService/SearchAllResources", - google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllResourcesRequest.SerializeToString, - google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllResourcesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def SearchAllIamPolicies( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1p1beta1.AssetService/SearchAllIamPolicies", - google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesRequest.SerializeToString, - google_dot_cloud_dot_asset__v1p1beta1_dot_proto_dot_asset__service__pb2.SearchAllIamPoliciesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/asset_v1p1beta1/proto/assets_pb2.py b/google/cloud/asset_v1p1beta1/proto/assets_pb2.py deleted file mode 100644 index 8186024e..00000000 --- a/google/cloud/asset_v1p1beta1/proto/assets_pb2.py +++ /dev/null @@ -1,699 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1p1beta1/proto/assets.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1p1beta1/proto/assets.proto", - package="google.cloud.asset.v1p1beta1", - syntax="proto3", - serialized_options=b"\n com.google.cloud.asset.v1p1beta1B\nAssetProtoP\001ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p1beta1;asset\370\001\001\252\002\034Google.Cloud.Asset.V1P1Beta1\312\002\034Google\\Cloud\\Asset\\V1p1beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n/google/cloud/asset_v1p1beta1/proto/assets.proto\x12\x1cgoogle.cloud.asset.v1p1beta1\x1a\x1agoogle/iam/v1/policy.proto\x1a\x1cgoogle/api/annotations.proto"\xc2\x02\n\x18StandardResourceMetadata\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\nasset_type\x18\x02 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x04 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x05 \x01(\t\x12\x1d\n\x15\x61\x64\x64itional_attributes\x18\n \x03(\t\x12\x10\n\x08location\x18\x0b \x01(\t\x12R\n\x06labels\x18\x0c \x03(\x0b\x32\x42.google.cloud.asset.v1p1beta1.StandardResourceMetadata.LabelsEntry\x12\x14\n\x0cnetwork_tags\x18\r \x03(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01"\xa3\x03\n\x15IamPolicySearchResult\x12\x10\n\x08resource\x18\x01 \x01(\t\x12\x0f\n\x07project\x18\x03 \x01(\t\x12%\n\x06policy\x18\x04 \x01(\x0b\x32\x15.google.iam.v1.Policy\x12T\n\x0b\x65xplanation\x18\x05 \x01(\x0b\x32?.google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation\x1a\xe9\x01\n\x0b\x45xplanation\x12t\n\x13matched_permissions\x18\x01 \x03(\x0b\x32W.google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry\x1a\x64\n\x17MatchedPermissionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x01(\x0b\x32).google.cloud.asset.v1p1beta1.Permissions:\x02\x38\x01""\n\x0bPermissions\x12\x13\n\x0bpermissions\x18\x01 \x03(\tB\xb4\x01\n com.google.cloud.asset.v1p1beta1B\nAssetProtoP\x01ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p1beta1;asset\xf8\x01\x01\xaa\x02\x1cGoogle.Cloud.Asset.V1P1Beta1\xca\x02\x1cGoogle\\Cloud\\Asset\\V1p1beta1b\x06proto3', - dependencies=[ - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_STANDARDRESOURCEMETADATA_LABELSENTRY = _descriptor.Descriptor( - name="LabelsEntry", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.LabelsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.LabelsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.LabelsEntry.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=417, - serialized_end=462, -) - -_STANDARDRESOURCEMETADATA = _descriptor.Descriptor( - name="StandardResourceMetadata", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_type", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.asset_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.project", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.display_name", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.description", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="additional_attributes", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.additional_attributes", - index=5, - number=10, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="location", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.location", - index=6, - number=11, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="labels", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.labels", - index=7, - number=12, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="network_tags", - full_name="google.cloud.asset.v1p1beta1.StandardResourceMetadata.network_tags", - index=8, - number=13, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_STANDARDRESOURCEMETADATA_LABELSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=140, - serialized_end=462, -) - - -_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY = _descriptor.Descriptor( - name="MatchedPermissionsEntry", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry.value", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"8\001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=784, - serialized_end=884, -) - -_IAMPOLICYSEARCHRESULT_EXPLANATION = _descriptor.Descriptor( - name="Explanation", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="matched_permissions", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation.matched_permissions", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=651, - serialized_end=884, -) - -_IAMPOLICYSEARCHRESULT = _descriptor.Descriptor( - name="IamPolicySearchResult", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.resource", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="project", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.project", - index=1, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="policy", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.policy", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="explanation", - full_name="google.cloud.asset.v1p1beta1.IamPolicySearchResult.explanation", - index=3, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_IAMPOLICYSEARCHRESULT_EXPLANATION,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=465, - serialized_end=884, -) - - -_PERMISSIONS = _descriptor.Descriptor( - name="Permissions", - full_name="google.cloud.asset.v1p1beta1.Permissions", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="permissions", - full_name="google.cloud.asset.v1p1beta1.Permissions.permissions", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=886, - serialized_end=920, -) - -_STANDARDRESOURCEMETADATA_LABELSENTRY.containing_type = _STANDARDRESOURCEMETADATA -_STANDARDRESOURCEMETADATA.fields_by_name[ - "labels" -].message_type = _STANDARDRESOURCEMETADATA_LABELSENTRY -_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY.fields_by_name[ - "value" -].message_type = _PERMISSIONS -_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY.containing_type = ( - _IAMPOLICYSEARCHRESULT_EXPLANATION -) -_IAMPOLICYSEARCHRESULT_EXPLANATION.fields_by_name[ - "matched_permissions" -].message_type = _IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY -_IAMPOLICYSEARCHRESULT_EXPLANATION.containing_type = _IAMPOLICYSEARCHRESULT -_IAMPOLICYSEARCHRESULT.fields_by_name[ - "policy" -].message_type = ( - google_dot_iam_dot_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._POLICY -) -_IAMPOLICYSEARCHRESULT.fields_by_name[ - "explanation" -].message_type = _IAMPOLICYSEARCHRESULT_EXPLANATION -DESCRIPTOR.message_types_by_name["StandardResourceMetadata"] = _STANDARDRESOURCEMETADATA -DESCRIPTOR.message_types_by_name["IamPolicySearchResult"] = _IAMPOLICYSEARCHRESULT -DESCRIPTOR.message_types_by_name["Permissions"] = _PERMISSIONS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -StandardResourceMetadata = _reflection.GeneratedProtocolMessageType( - "StandardResourceMetadata", - (_message.Message,), - { - "LabelsEntry": _reflection.GeneratedProtocolMessageType( - "LabelsEntry", - (_message.Message,), - { - "DESCRIPTOR": _STANDARDRESOURCEMETADATA_LABELSENTRY, - "__module__": "google.cloud.asset_v1p1beta1.proto.assets_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.StandardResourceMetadata.LabelsEntry) - }, - ), - "DESCRIPTOR": _STANDARDRESOURCEMETADATA, - "__module__": "google.cloud.asset_v1p1beta1.proto.assets_pb2", - "__doc__": """The standard metadata of a cloud resource. - - Attributes: - name: - The full resource name. For example: ``//compute.googleapis.co - m/projects/my_project_123/zones/zone1/instances/instance1``. - See `Resource Names `__ for more information. - asset_type: - The type of this resource. For example: - “compute.googleapis.com/Disk”. - project: - The project that this resource belongs to, in the form of - ``projects/{project_number}``. - display_name: - The display name of this resource. - description: - One or more paragraphs of text description of this resource. - Maximum length could be up to 1M bytes. - additional_attributes: - Additional searchable attributes of this resource. - Informational only. The exact set of attributes is subject to - change. For example: project id, DNS name etc. - location: - Location can be “global”, regional like “us-east1”, or zonal - like “us-west1-b”. - labels: - Labels associated with this resource. See `Labelling and - grouping GCP resources - `__ for more - information. - network_tags: - Network tags associated with this resource. Like labels, - network tags are a type of annotations used to group GCP - resources. See `Labelling GCP resources - `__ for more - information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.StandardResourceMetadata) - }, -) -_sym_db.RegisterMessage(StandardResourceMetadata) -_sym_db.RegisterMessage(StandardResourceMetadata.LabelsEntry) - -IamPolicySearchResult = _reflection.GeneratedProtocolMessageType( - "IamPolicySearchResult", - (_message.Message,), - { - "Explanation": _reflection.GeneratedProtocolMessageType( - "Explanation", - (_message.Message,), - { - "MatchedPermissionsEntry": _reflection.GeneratedProtocolMessageType( - "MatchedPermissionsEntry", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY, - "__module__": "google.cloud.asset_v1p1beta1.proto.assets_pb2" - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation.MatchedPermissionsEntry) - }, - ), - "DESCRIPTOR": _IAMPOLICYSEARCHRESULT_EXPLANATION, - "__module__": "google.cloud.asset_v1p1beta1.proto.assets_pb2", - "__doc__": """Explanation about the IAM policy search result. - - Attributes: - matched_permissions: - The map from roles to their included permission matching the - permission query (e.g. containing - ``policy.role.permissions:``). A sample role string: - “roles/compute.instanceAdmin”. The roles can also be found in - the returned ``policy`` bindings. Note that the map is - populated only if requesting with a permission query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.IamPolicySearchResult.Explanation) - }, - ), - "DESCRIPTOR": _IAMPOLICYSEARCHRESULT, - "__module__": "google.cloud.asset_v1p1beta1.proto.assets_pb2", - "__doc__": """The result for a IAM Policy search. - - Attributes: - resource: - The `full resource name `__ of the resource - associated with this IAM policy. - project: - The project that the associated GCP resource belongs to, in - the form of ``projects/{project_number}``. If an IAM policy is - set on a resource (like VM instance, Cloud Storage bucket), - the project field will indicate the project that contains the - resource. If an IAM policy is set on a folder or orgnization, - the project field will be empty. - policy: - The IAM policy directly set on the given resource. Note that - the original IAM policy can contain multiple bindings. This - only contains the bindings that match the given query. For - queries that don’t contain a constrain on policies (e.g. an - empty query), this contains all the bindings. - explanation: - Explanation about the IAM policy search result. It contains - additional information to explain why the search result - matches the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.IamPolicySearchResult) - }, -) -_sym_db.RegisterMessage(IamPolicySearchResult) -_sym_db.RegisterMessage(IamPolicySearchResult.Explanation) -_sym_db.RegisterMessage(IamPolicySearchResult.Explanation.MatchedPermissionsEntry) - -Permissions = _reflection.GeneratedProtocolMessageType( - "Permissions", - (_message.Message,), - { - "DESCRIPTOR": _PERMISSIONS, - "__module__": "google.cloud.asset_v1p1beta1.proto.assets_pb2", - "__doc__": """IAM permissions - - Attributes: - permissions: - A list of permissions. A sample permission string: - “compute.disk.get”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p1beta1.Permissions) - }, -) -_sym_db.RegisterMessage(Permissions) - - -DESCRIPTOR._options = None -_STANDARDRESOURCEMETADATA_LABELSENTRY._options = None -_IAMPOLICYSEARCHRESULT_EXPLANATION_MATCHEDPERMISSIONSENTRY._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1p1beta1/proto/assets_pb2_grpc.py b/google/cloud/asset_v1p1beta1/proto/assets_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/asset_v1p1beta1/proto/assets_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/asset_v1p1beta1/py.typed b/google/cloud/asset_v1p1beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/google/cloud/asset_v1p1beta1/services/__init__.py b/google/cloud/asset_v1p1beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/asset_v1p1beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/cloud/asset.py b/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py similarity index 70% rename from google/cloud/asset.py rename to google/cloud/asset_v1p1beta1/services/asset_service/__init__.py index 2ebc40d0..ec3c27d2 100644 --- a/google/cloud/asset.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py @@ -1,29 +1,24 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 __future__ import absolute_import - -from google.cloud.asset_v1 import AssetServiceClient -from google.cloud.asset_v1 import enums -from google.cloud.asset_v1 import types - +from .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient __all__ = ( - "enums", - "types", "AssetServiceClient", + "AssetServiceAsyncClient", ) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py b/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..ff8665de --- /dev/null +++ b/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py @@ -0,0 +1,332 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.asset_v1p1beta1.services.asset_service import pagers +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets + +from .transports.base import AssetServiceTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = AssetServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(AssetServiceClient).get_transport_class, type(AssetServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = AssetServiceClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def search_all_resources( + self, + request: asset_service.SearchAllResourcesRequest = None, + *, + scope: str = None, + query: str = None, + asset_types: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesAsyncPager: + r"""Searches all the resources under a given accessible + CRM scope (project/folder/organization). This RPC gives + callers especially admins the ability to search all the + resources under a scope, even if they don't have .get + permission of all the resources. Callers should have + cloud.assets.SearchAllResources permission on the + requested scope, otherwise it will be rejected. + + Args: + request (:class:`~.asset_service.SearchAllResourcesRequest`): + The request object. Search all resources request. + scope (:class:`str`): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The + allowed value must be: + + - Organization number (such as "organizations/123") + - Folder number(such as "folders/1234") + - Project number (such as "projects/12345") + - Project id (such as "projects/abc") + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_types (:class:`Sequence[str]`): + Optional. A list of asset types that + this request searches for. If empty, it + will search all the supported asset + types. + This corresponds to the ``asset_types`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.SearchAllResourcesAsyncPager: + Search all resources response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([scope, query, asset_types]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.SearchAllResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + if asset_types is not None: + request.asset_types = asset_types + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_all_resources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=15.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + ) + + # 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.SearchAllResourcesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_all_iam_policies( + self, + request: asset_service.SearchAllIamPoliciesRequest = None, + *, + scope: str = None, + query: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesAsyncPager: + r"""Searches all the IAM policies under a given + accessible CRM scope (project/folder/organization). This + RPC gives callers especially admins the ability to + search all the IAM policies under a scope, even if they + don't have .getIamPolicy permission of all the IAM + policies. Callers should have + cloud.assets.SearchAllIamPolicies permission on the + requested scope, otherwise it will be rejected. + + Args: + request (:class:`~.asset_service.SearchAllIamPoliciesRequest`): + The request object. Search all IAM policies request. + scope (:class:`str`): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The + allowed value must be: + + - Organization number (such as "organizations/123") + - Folder number(such as "folders/1234") + - Project number (such as "projects/12345") + - Project id (such as "projects/abc") + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. Examples: + + - "policy:myuser@mydomain.com" + - "policy:(myuser@mydomain.com viewer)". + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.SearchAllIamPoliciesAsyncPager: + Search all IAM policies response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([scope, query]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.SearchAllIamPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_all_iam_policies, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=15.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + ) + + # 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.SearchAllIamPoliciesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceAsyncClient",) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/client.py b/google/cloud/asset_v1p1beta1/services/asset_service/client.py new file mode 100644 index 00000000..5d03fbd9 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/services/asset_service/client.py @@ -0,0 +1,444 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.asset_v1p1beta1.services.asset_service import pagers +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets + +from .transports.base import AssetServiceTransport +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudasset.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AssetServiceTransport): + # transport is a AssetServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def search_all_resources( + self, + request: asset_service.SearchAllResourcesRequest = None, + *, + scope: str = None, + query: str = None, + asset_types: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesPager: + r"""Searches all the resources under a given accessible + CRM scope (project/folder/organization). This RPC gives + callers especially admins the ability to search all the + resources under a scope, even if they don't have .get + permission of all the resources. Callers should have + cloud.assets.SearchAllResources permission on the + requested scope, otherwise it will be rejected. + + Args: + request (:class:`~.asset_service.SearchAllResourcesRequest`): + The request object. Search all resources request. + scope (:class:`str`): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The + allowed value must be: + + - Organization number (such as "organizations/123") + - Folder number(such as "folders/1234") + - Project number (such as "projects/12345") + - Project id (such as "projects/abc") + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_types (:class:`Sequence[str]`): + Optional. A list of asset types that + this request searches for. If empty, it + will search all the supported asset + types. + This corresponds to the ``asset_types`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.SearchAllResourcesPager: + Search all resources response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scope, query, asset_types]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.SearchAllResourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.SearchAllResourcesRequest): + request = asset_service.SearchAllResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + if asset_types is not None: + request.asset_types = asset_types + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_all_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchAllResourcesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def search_all_iam_policies( + self, + request: asset_service.SearchAllIamPoliciesRequest = None, + *, + scope: str = None, + query: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesPager: + r"""Searches all the IAM policies under a given + accessible CRM scope (project/folder/organization). This + RPC gives callers especially admins the ability to + search all the IAM policies under a scope, even if they + don't have .getIamPolicy permission of all the IAM + policies. Callers should have + cloud.assets.SearchAllIamPolicies permission on the + requested scope, otherwise it will be rejected. + + Args: + request (:class:`~.asset_service.SearchAllIamPoliciesRequest`): + The request object. Search all IAM policies request. + scope (:class:`str`): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The + allowed value must be: + + - Organization number (such as "organizations/123") + - Folder number(such as "folders/1234") + - Project number (such as "projects/12345") + - Project id (such as "projects/abc") + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. Examples: + + - "policy:myuser@mydomain.com" + - "policy:(myuser@mydomain.com viewer)". + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.SearchAllIamPoliciesPager: + Search all IAM policies response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([scope, query]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.SearchAllIamPoliciesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.SearchAllIamPoliciesRequest): + request = asset_service.SearchAllIamPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_all_iam_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", request.scope),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.SearchAllIamPoliciesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceClient",) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py b/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py new file mode 100644 index 00000000..d41893a2 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py @@ -0,0 +1,277 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets + + +class SearchAllResourcesPager: + """A pager for iterating through ``search_all_resources`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.SearchAllResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAllResources`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.SearchAllResourcesResponse` + 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[..., asset_service.SearchAllResourcesResponse], + request: asset_service.SearchAllResourcesRequest, + response: asset_service.SearchAllResourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.SearchAllResourcesRequest`): + The initial request object. + response (:class:`~.asset_service.SearchAllResourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.SearchAllResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[asset_service.SearchAllResourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[assets.StandardResourceMetadata]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchAllResourcesAsyncPager: + """A pager for iterating through ``search_all_resources`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.SearchAllResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAllResources`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.SearchAllResourcesResponse` + 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[asset_service.SearchAllResourcesResponse]], + request: asset_service.SearchAllResourcesRequest, + response: asset_service.SearchAllResourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.SearchAllResourcesRequest`): + The initial request object. + response (:class:`~.asset_service.SearchAllResourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.SearchAllResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[asset_service.SearchAllResourcesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[assets.StandardResourceMetadata]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchAllIamPoliciesPager: + """A pager for iterating through ``search_all_iam_policies`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.SearchAllIamPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAllIamPolicies`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.SearchAllIamPoliciesResponse` + 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[..., asset_service.SearchAllIamPoliciesResponse], + request: asset_service.SearchAllIamPoliciesRequest, + response: asset_service.SearchAllIamPoliciesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.SearchAllIamPoliciesRequest`): + The initial request object. + response (:class:`~.asset_service.SearchAllIamPoliciesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.SearchAllIamPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[asset_service.SearchAllIamPoliciesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[assets.IamPolicySearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class SearchAllIamPoliciesAsyncPager: + """A pager for iterating through ``search_all_iam_policies`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.SearchAllIamPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAllIamPolicies`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.SearchAllIamPoliciesResponse` + 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[asset_service.SearchAllIamPoliciesResponse]], + request: asset_service.SearchAllIamPoliciesRequest, + response: asset_service.SearchAllIamPoliciesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.SearchAllIamPoliciesRequest`): + The initial request object. + response (:class:`~.asset_service.SearchAllIamPoliciesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.SearchAllIamPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[asset_service.SearchAllIamPoliciesResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[assets.IamPolicySearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..624eab74 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry["grpc"] = AssetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + +__all__ = ( + "AssetServiceTransport", + "AssetServiceGrpcTransport", + "AssetServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..10cef926 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.asset_v1p1beta1.types import asset_service + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search_all_resources: gapic_v1.method.wrap_method( + self.search_all_resources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=15.0, + client_info=_client_info, + ), + self.search_all_iam_policies: gapic_v1.method.wrap_method( + self.search_all_iam_policies, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=15.0, + client_info=_client_info, + ), + } + + @property + def search_all_resources( + self, + ) -> typing.Callable[ + [asset_service.SearchAllResourcesRequest], + typing.Union[ + asset_service.SearchAllResourcesResponse, + typing.Awaitable[asset_service.SearchAllResourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def search_all_iam_policies( + self, + ) -> typing.Callable[ + [asset_service.SearchAllIamPoliciesRequest], + typing.Union[ + asset_service.SearchAllIamPoliciesResponse, + typing.Awaitable[asset_service.SearchAllIamPoliciesResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("AssetServiceTransport",) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..d4ac7672 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.asset_v1p1beta1.types import asset_service + +from .base import AssetServiceTransport + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def search_all_resources( + self, + ) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse, + ]: + r"""Return a callable for the search all resources method over gRPC. + + Searches all the resources under a given accessible + CRM scope (project/folder/organization). This RPC gives + callers especially admins the ability to search all the + resources under a scope, even if they don't have .get + permission of all the resources. Callers should have + cloud.assets.SearchAllResources permission on the + requested scope, otherwise it will be rejected. + + Returns: + Callable[[~.SearchAllResourcesRequest], + ~.SearchAllResourcesResponse]: + 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_all_resources" not in self._stubs: + self._stubs["search_all_resources"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p1beta1.AssetService/SearchAllResources", + request_serializer=asset_service.SearchAllResourcesRequest.serialize, + response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, + ) + return self._stubs["search_all_resources"] + + @property + def search_all_iam_policies( + self, + ) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse, + ]: + r"""Return a callable for the search all iam policies method over gRPC. + + Searches all the IAM policies under a given + accessible CRM scope (project/folder/organization). This + RPC gives callers especially admins the ability to + search all the IAM policies under a scope, even if they + don't have .getIamPolicy permission of all the IAM + policies. Callers should have + cloud.assets.SearchAllIamPolicies permission on the + requested scope, otherwise it will be rejected. + + Returns: + Callable[[~.SearchAllIamPoliciesRequest], + ~.SearchAllIamPoliciesResponse]: + 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_all_iam_policies" not in self._stubs: + self._stubs["search_all_iam_policies"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p1beta1.AssetService/SearchAllIamPolicies", + request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, + response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, + ) + return self._stubs["search_all_iam_policies"] + + +__all__ = ("AssetServiceGrpcTransport",) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..98fa28a7 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,271 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1p1beta1.types import asset_service + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: 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: + address (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 ignored if ``channel`` 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`. + 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def search_all_resources( + self, + ) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Awaitable[asset_service.SearchAllResourcesResponse], + ]: + r"""Return a callable for the search all resources method over gRPC. + + Searches all the resources under a given accessible + CRM scope (project/folder/organization). This RPC gives + callers especially admins the ability to search all the + resources under a scope, even if they don't have .get + permission of all the resources. Callers should have + cloud.assets.SearchAllResources permission on the + requested scope, otherwise it will be rejected. + + Returns: + Callable[[~.SearchAllResourcesRequest], + Awaitable[~.SearchAllResourcesResponse]]: + 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_all_resources" not in self._stubs: + self._stubs["search_all_resources"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p1beta1.AssetService/SearchAllResources", + request_serializer=asset_service.SearchAllResourcesRequest.serialize, + response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, + ) + return self._stubs["search_all_resources"] + + @property + def search_all_iam_policies( + self, + ) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Awaitable[asset_service.SearchAllIamPoliciesResponse], + ]: + r"""Return a callable for the search all iam policies method over gRPC. + + Searches all the IAM policies under a given + accessible CRM scope (project/folder/organization). This + RPC gives callers especially admins the ability to + search all the IAM policies under a scope, even if they + don't have .getIamPolicy permission of all the IAM + policies. Callers should have + cloud.assets.SearchAllIamPolicies permission on the + requested scope, otherwise it will be rejected. + + Returns: + Callable[[~.SearchAllIamPoliciesRequest], + Awaitable[~.SearchAllIamPoliciesResponse]]: + 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_all_iam_policies" not in self._stubs: + self._stubs["search_all_iam_policies"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p1beta1.AssetService/SearchAllIamPolicies", + request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, + response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, + ) + return self._stubs["search_all_iam_policies"] + + +__all__ = ("AssetServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/asset_v1p1beta1/types.py b/google/cloud/asset_v1p1beta1/types.py deleted file mode 100644 index f5cf296d..00000000 --- a/google/cloud/asset_v1p1beta1/types.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.asset_v1p1beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p1beta1.proto import assets_pb2 -from google.iam.v1 import policy_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - policy_pb2, - expr_pb2, -] - -_local_modules = [ - asset_service_pb2, - assets_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.asset_v1p1beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/asset_v1p1beta1/types/__init__.py b/google/cloud/asset_v1p1beta1/types/__init__.py new file mode 100644 index 00000000..da73ca1e --- /dev/null +++ b/google/cloud/asset_v1p1beta1/types/__init__.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .assets import ( + StandardResourceMetadata, + IamPolicySearchResult, + Permissions, +) +from .asset_service import ( + SearchAllResourcesRequest, + SearchAllResourcesResponse, + SearchAllIamPoliciesRequest, + SearchAllIamPoliciesResponse, +) + + +__all__ = ( + "StandardResourceMetadata", + "IamPolicySearchResult", + "Permissions", + "SearchAllResourcesRequest", + "SearchAllResourcesResponse", + "SearchAllIamPoliciesRequest", + "SearchAllIamPoliciesResponse", +) diff --git a/google/cloud/asset_v1p1beta1/types/asset_service.py b/google/cloud/asset_v1p1beta1/types/asset_service.py new file mode 100644 index 00000000..71aa5286 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/types/asset_service.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.asset_v1p1beta1.types import assets + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1p1beta1", + manifest={ + "SearchAllResourcesRequest", + "SearchAllResourcesResponse", + "SearchAllIamPoliciesRequest", + "SearchAllIamPoliciesResponse", + }, +) + + +class SearchAllResourcesRequest(proto.Message): + r"""Search all resources request. + + Attributes: + scope (str): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The allowed + value must be: + + - Organization number (such as "organizations/123") + - Folder number(such as "folders/1234") + - Project number (such as "projects/12345") + - Project id (such as "projects/abc") + query (str): + Optional. The query statement. + asset_types (Sequence[str]): + Optional. A list of asset types that this + request searches for. If empty, it will search + all the supported asset types. + page_size (int): + Optional. The page size for search result pagination. Page + size is capped at 500 even if a larger value is given. If + set to zero, server will pick an appropriate default. + Returned results may be fewer than requested. When this + happens, there could be more results as long as + ``next_page_token`` is returned. + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``page_token`` must be the value of ``next_page_token`` from + the previous response. The values of all other method + parameters, must be identical to those in the previous call. + order_by (str): + Optional. A comma separated list of fields + specifying the sorting order of the results. The + default order is ascending. Add " desc" after + the field name to indicate descending order. + Redundant space characters are ignored. For + example, " foo , bar desc ". + """ + + scope = proto.Field(proto.STRING, number=1) + + query = proto.Field(proto.STRING, number=2) + + asset_types = proto.RepeatedField(proto.STRING, number=3) + + page_size = proto.Field(proto.INT32, number=4) + + page_token = proto.Field(proto.STRING, number=5) + + order_by = proto.Field(proto.STRING, number=10) + + +class SearchAllResourcesResponse(proto.Message): + r"""Search all resources response. + + Attributes: + results (Sequence[~.assets.StandardResourceMetadata]): + A list of resource that match the search + query. + next_page_token (str): + If there are more results than those appearing in this + response, then ``next_page_token`` is included. To get the + next set of results, call this method again using the value + of ``next_page_token`` as ``page_token``. + """ + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, number=1, message=assets.StandardResourceMetadata, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class SearchAllIamPoliciesRequest(proto.Message): + r"""Search all IAM policies request. + + Attributes: + scope (str): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The allowed + value must be: + + - Organization number (such as "organizations/123") + - Folder number(such as "folders/1234") + - Project number (such as "projects/12345") + - Project id (such as "projects/abc") + query (str): + Optional. The query statement. Examples: + + - "policy:myuser@mydomain.com" + - "policy:(myuser@mydomain.com viewer)". + page_size (int): + Optional. The page size for search result pagination. Page + size is capped at 500 even if a larger value is given. If + set to zero, server will pick an appropriate default. + Returned results may be fewer than requested. When this + happens, there could be more results as long as + ``next_page_token`` is returned. + page_token (str): + Optional. If present, retrieve the next batch of results + from the preceding call to this method. ``page_token`` must + be the value of ``next_page_token`` from the previous + response. The values of all other method parameters must be + identical to those in the previous call. + """ + + scope = proto.Field(proto.STRING, number=1) + + query = proto.Field(proto.STRING, number=2) + + page_size = proto.Field(proto.INT32, number=3) + + page_token = proto.Field(proto.STRING, number=4) + + +class SearchAllIamPoliciesResponse(proto.Message): + r"""Search all IAM policies response. + + Attributes: + results (Sequence[~.assets.IamPolicySearchResult]): + A list of IamPolicy that match the search + query. Related information such as the + associated resource is returned along with the + policy. + next_page_token (str): + Set if there are more results than those appearing in this + response; to get the next set of results, call this method + again, using this value as the ``page_token``. + """ + + @property + def raw_page(self): + return self + + results = proto.RepeatedField( + proto.MESSAGE, number=1, message=assets.IamPolicySearchResult, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p1beta1/types/assets.py b/google/cloud/asset_v1p1beta1/types/assets.py new file mode 100644 index 00000000..d53fa624 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/types/assets.py @@ -0,0 +1,159 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.iam.v1 import policy_pb2 as giv_policy # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1p1beta1", + manifest={"StandardResourceMetadata", "IamPolicySearchResult", "Permissions",}, +) + + +class StandardResourceMetadata(proto.Message): + r"""The standard metadata of a cloud resource. + + Attributes: + name (str): + The full resource name. For example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more information. + asset_type (str): + The type of this resource. + For example: "compute.googleapis.com/Disk". + project (str): + The project that this resource belongs to, in the form of + ``projects/{project_number}``. + display_name (str): + The display name of this resource. + description (str): + One or more paragraphs of text description of + this resource. Maximum length could be up to 1M + bytes. + additional_attributes (Sequence[str]): + Additional searchable attributes of this + resource. Informational only. The exact set of + attributes is subject to change. For example: + project id, DNS name etc. + location (str): + Location can be "global", regional like "us- + ast1", or zonal like "us-west1-b". + labels (Sequence[~.assets.StandardResourceMetadata.LabelsEntry]): + Labels associated with this resource. See `Labelling and + grouping GCP + resources `__ + for more information. + network_tags (Sequence[str]): + Network tags associated with this resource. Like labels, + network tags are a type of annotations used to group GCP + resources. See `Labelling GCP + resources `__ + for more information. + """ + + name = proto.Field(proto.STRING, number=1) + + asset_type = proto.Field(proto.STRING, number=2) + + project = proto.Field(proto.STRING, number=3) + + display_name = proto.Field(proto.STRING, number=4) + + description = proto.Field(proto.STRING, number=5) + + additional_attributes = proto.RepeatedField(proto.STRING, number=10) + + location = proto.Field(proto.STRING, number=11) + + labels = proto.MapField(proto.STRING, proto.STRING, number=12) + + network_tags = proto.RepeatedField(proto.STRING, number=13) + + +class IamPolicySearchResult(proto.Message): + r"""The result for a IAM Policy search. + + Attributes: + resource (str): + The `full resource + name `__ + of the resource associated with this IAM policy. + project (str): + The project that the associated GCP resource belongs to, in + the form of ``projects/{project_number}``. If an IAM policy + is set on a resource (like VM instance, Cloud Storage + bucket), the project field will indicate the project that + contains the resource. If an IAM policy is set on a folder + or orgnization, the project field will be empty. + policy (~.giv_policy.Policy): + The IAM policy directly set on the given + resource. Note that the original IAM policy can + contain multiple bindings. This only contains + the bindings that match the given query. For + queries that don't contain a constrain on + policies (e.g. an empty query), this contains + all the bindings. + explanation (~.assets.IamPolicySearchResult.Explanation): + Explanation about the IAM policy search + result. It contains additional information to + explain why the search result matches the query. + """ + + class Explanation(proto.Message): + r"""Explanation about the IAM policy search result. + + Attributes: + matched_permissions (Sequence[~.assets.IamPolicySearchResult.Explanation.MatchedPermissionsEntry]): + The map from roles to their included permission matching the + permission query (e.g. containing + ``policy.role.permissions:``). A sample role string: + "roles/compute.instanceAdmin". The roles can also be found + in the returned ``policy`` bindings. Note that the map is + populated only if requesting with a permission query. + """ + + matched_permissions = proto.MapField( + proto.STRING, proto.MESSAGE, number=1, message="Permissions", + ) + + resource = proto.Field(proto.STRING, number=1) + + project = proto.Field(proto.STRING, number=3) + + policy = proto.Field(proto.MESSAGE, number=4, message=giv_policy.Policy,) + + explanation = proto.Field(proto.MESSAGE, number=5, message=Explanation,) + + +class Permissions(proto.Message): + r"""IAM permissions + + Attributes: + permissions (Sequence[str]): + A list of permissions. A sample permission + string: "compute.disk.get". + """ + + permissions = proto.RepeatedField(proto.STRING, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p2beta1/__init__.py b/google/cloud/asset_v1p2beta1/__init__.py index 30e98575..159a6d98 100644 --- a/google/cloud/asset_v1p2beta1/__init__.py +++ b/google/cloud/asset_v1p2beta1/__init__.py @@ -1,45 +1,55 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.asset_v1p2beta1 import types -from google.cloud.asset_v1p2beta1.gapic import asset_service_client -from google.cloud.asset_v1p2beta1.gapic import enums - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class AssetServiceClient(asset_service_client.AssetServiceClient): - __doc__ = asset_service_client.AssetServiceClient.__doc__ - enums = enums +from .services.asset_service import AssetServiceClient +from .types.asset_service import ContentType +from .types.asset_service import CreateFeedRequest +from .types.asset_service import DeleteFeedRequest +from .types.asset_service import Feed +from .types.asset_service import FeedOutputConfig +from .types.asset_service import GcsDestination +from .types.asset_service import GetFeedRequest +from .types.asset_service import ListFeedsRequest +from .types.asset_service import ListFeedsResponse +from .types.asset_service import OutputConfig +from .types.asset_service import PubsubDestination +from .types.asset_service import UpdateFeedRequest +from .types.assets import Asset +from .types.assets import Resource +from .types.assets import TemporalAsset +from .types.assets import TimeWindow __all__ = ( - "enums", - "types", + "Asset", + "ContentType", + "CreateFeedRequest", + "DeleteFeedRequest", + "Feed", + "FeedOutputConfig", + "GcsDestination", + "GetFeedRequest", + "ListFeedsRequest", + "ListFeedsResponse", + "OutputConfig", + "PubsubDestination", + "Resource", + "TemporalAsset", + "TimeWindow", + "UpdateFeedRequest", "AssetServiceClient", ) diff --git a/google/cloud/asset_v1p2beta1/gapic/__init__.py b/google/cloud/asset_v1p2beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p2beta1/gapic/asset_service_client.py b/google/cloud/asset_v1p2beta1/gapic/asset_service_client.py deleted file mode 100644 index 5cbf3acf..00000000 --- a/google/cloud/asset_v1p2beta1/gapic/asset_service_client.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Accesses the google.cloud.asset.v1p2beta1 AssetService API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.path_template -import grpc - -from google.cloud.asset_v1p2beta1.gapic import asset_service_client_config -from google.cloud.asset_v1p2beta1.gapic import enums -from google.cloud.asset_v1p2beta1.gapic.transports import asset_service_grpc_transport -from google.cloud.asset_v1p2beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p2beta1.proto import asset_service_pb2_grpc -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-asset",).version - - -class AssetServiceClient(object): - """Asset service definition.""" - - SERVICE_ADDRESS = "cloudasset.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.asset.v1p2beta1.AssetService" - - @classmethod - def from_service_account_file(cls, filename, *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: - AssetServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def feed_path(cls, project, feed): - """Return a fully-qualified feed string.""" - return google.api_core.path_template.expand( - "projects/{project}/feeds/{feed}", project=project, feed=feed, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.AssetServiceGrpcTransport, - Callable[[~.Credentials, type], ~.AssetServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = asset_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=asset_service_grpc_transport.AssetServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = asset_service_grpc_transport.AssetServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def delete_feed( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Deletes an asset feed. - - Example: - >>> from google.cloud import asset_v1p2beta1 - >>> - >>> client = asset_v1p2beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `name`: - >>> name = '' - >>> - >>> client.delete_feed(name) - - Args: - name (str): Required. The name of the feed and it must be in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_feed" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_feed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_feed, - default_retry=self._method_configs["DeleteFeed"].retry, - default_timeout=self._method_configs["DeleteFeed"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.DeleteFeedRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_feed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_feed( - self, - parent, - feed_id, - feed, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates a feed in a parent project/folder/organization to listen to its - asset updates. - - Example: - >>> from google.cloud import asset_v1p2beta1 - >>> - >>> client = asset_v1p2beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> # TODO: Initialize `feed_id`: - >>> feed_id = '' - >>> - >>> # TODO: Initialize `feed`: - >>> feed = {} - >>> - >>> response = client.create_feed(parent, feed_id, feed) - - Args: - parent (str): Required. The name of the project/folder/organization where this feed - should be created in. It can only be an organization number (such as - "organizations/123"), a folder number (such as "folders/123"), a project ID - (such as "projects/my-project-id")", or a project number (such as - "projects/12345"). - feed_id (str): Required. This is the client-assigned asset feed identifier and it needs to - be unique under a specific parent project/folder/organization. - feed (Union[dict, ~google.cloud.asset_v1p2beta1.types.Feed]): Required. The feed details. The field ``name`` must be empty and it - will be generated in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p2beta1.types.Feed` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1p2beta1.types.Feed` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_feed" not in self._inner_api_calls: - self._inner_api_calls[ - "create_feed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_feed, - default_retry=self._method_configs["CreateFeed"].retry, - default_timeout=self._method_configs["CreateFeed"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.CreateFeedRequest( - parent=parent, feed_id=feed_id, feed=feed, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_feed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def get_feed( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets details about an asset feed. - - Example: - >>> from google.cloud import asset_v1p2beta1 - >>> - >>> client = asset_v1p2beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `name`: - >>> name = '' - >>> - >>> response = client.get_feed(name) - - Args: - name (str): Required. The name of the Feed and it must be in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1p2beta1.types.Feed` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_feed" not in self._inner_api_calls: - self._inner_api_calls[ - "get_feed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_feed, - default_retry=self._method_configs["GetFeed"].retry, - default_timeout=self._method_configs["GetFeed"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.GetFeedRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_feed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_feeds( - self, - parent, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists all asset feeds in a parent project/folder/organization. - - Example: - >>> from google.cloud import asset_v1p2beta1 - >>> - >>> client = asset_v1p2beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> response = client.list_feeds(parent) - - Args: - parent (str): Required. The parent project/folder/organization whose feeds are to be - listed. It can only be using project/folder/organization number (such as - "folders/12345")", or a project ID (such as "projects/my-project-id"). - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1p2beta1.types.ListFeedsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_feeds" not in self._inner_api_calls: - self._inner_api_calls[ - "list_feeds" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_feeds, - default_retry=self._method_configs["ListFeeds"].retry, - default_timeout=self._method_configs["ListFeeds"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.ListFeedsRequest(parent=parent,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["list_feeds"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_feed( - self, - feed, - update_mask, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Updates an asset feed configuration. - - Example: - >>> from google.cloud import asset_v1p2beta1 - >>> - >>> client = asset_v1p2beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `feed`: - >>> feed = {} - >>> - >>> # TODO: Initialize `update_mask`: - >>> update_mask = {} - >>> - >>> response = client.update_feed(feed, update_mask) - - Args: - feed (Union[dict, ~google.cloud.asset_v1p2beta1.types.Feed]): Required. The new values of feed details. It must match an existing - feed and the field ``name`` must be in the format of: - projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p2beta1.types.Feed` - update_mask (Union[dict, ~google.cloud.asset_v1p2beta1.types.FieldMask]): Required. Only updates the ``feed`` fields indicated by this mask. - The field mask must not be empty, and it must not contain fields that - are immutable or only set by the server. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p2beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1p2beta1.types.Feed` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_feed" not in self._inner_api_calls: - self._inner_api_calls[ - "update_feed" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_feed, - default_retry=self._method_configs["UpdateFeed"].retry, - default_timeout=self._method_configs["UpdateFeed"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.UpdateFeedRequest( - feed=feed, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("feed.name", feed.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_feed"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/asset_v1p2beta1/gapic/asset_service_client_config.py b/google/cloud/asset_v1p2beta1/gapic/asset_service_client_config.py deleted file mode 100644 index 3e6dcea6..00000000 --- a/google/cloud/asset_v1p2beta1/gapic/asset_service_client_config.py +++ /dev/null @@ -1,67 +0,0 @@ -config = { - "interfaces": { - "google.cloud.asset.v1p2beta1.AssetService": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - }, - "methods": { - "DeleteFeed": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "CreateFeed": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetFeed": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "ListFeeds": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "UpdateFeed": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - }, - } - } -} diff --git a/google/cloud/asset_v1p2beta1/gapic/transports/__init__.py b/google/cloud/asset_v1p2beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p2beta1/gapic/transports/asset_service_grpc_transport.py b/google/cloud/asset_v1p2beta1/gapic/transports/asset_service_grpc_transport.py deleted file mode 100644 index 3cff05c5..00000000 --- a/google/cloud/asset_v1p2beta1/gapic/transports/asset_service_grpc_transport.py +++ /dev/null @@ -1,174 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 google.api_core.grpc_helpers - -from google.cloud.asset_v1p2beta1.proto import asset_service_pb2_grpc - - -class AssetServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.asset.v1p2beta1 AssetService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="cloudasset.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "asset_service_stub": asset_service_pb2_grpc.AssetServiceStub(channel), - } - - @classmethod - def create_channel( - cls, address="cloudasset.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def delete_feed(self): - """Return the gRPC stub for :meth:`AssetServiceClient.delete_feed`. - - Deletes an asset feed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].DeleteFeed - - @property - def create_feed(self): - """Return the gRPC stub for :meth:`AssetServiceClient.create_feed`. - - Creates a feed in a parent project/folder/organization to listen to its - asset updates. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].CreateFeed - - @property - def get_feed(self): - """Return the gRPC stub for :meth:`AssetServiceClient.get_feed`. - - Gets details about an asset feed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].GetFeed - - @property - def list_feeds(self): - """Return the gRPC stub for :meth:`AssetServiceClient.list_feeds`. - - Lists all asset feeds in a parent project/folder/organization. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].ListFeeds - - @property - def update_feed(self): - """Return the gRPC stub for :meth:`AssetServiceClient.update_feed`. - - Updates an asset feed configuration. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].UpdateFeed diff --git a/google/cloud/asset_v1p2beta1/proto/__init__.py b/google/cloud/asset_v1p2beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p2beta1/proto/asset_service.proto b/google/cloud/asset_v1p2beta1/proto/asset_service.proto deleted file mode 100644 index 7925bba6..00000000 --- a/google/cloud/asset_v1p2beta1/proto/asset_service.proto +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.asset.v1p2beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/cloud/asset/v1p2beta1/assets.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/field_mask.proto"; -import "google/protobuf/timestamp.proto"; - -option csharp_namespace = "Google.Cloud.Asset.V1p2Beta1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1;asset"; -option java_multiple_files = true; -option java_outer_classname = "AssetServiceProto"; -option java_package = "com.google.cloud.asset.v1p2beta1"; -option php_namespace = "Google\\Cloud\\Asset\\V1p2Beta1"; - -// Asset service definition. -service AssetService { - option (google.api.default_host) = "cloudasset.googleapis.com"; - option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/cloud-platform"; - - // Creates a feed in a parent project/folder/organization to listen to its - // asset updates. - rpc CreateFeed(CreateFeedRequest) returns (Feed) { - option (google.api.http) = { - post: "/v1p2beta1/{parent=*/*}/feeds" - body: "*" - }; - option (google.api.method_signature) = "parent"; - } - - // Gets details about an asset feed. - rpc GetFeed(GetFeedRequest) returns (Feed) { - option (google.api.http) = { - get: "/v1p2beta1/{name=*/*/feeds/*}" - }; - option (google.api.method_signature) = "name"; - } - - // Lists all asset feeds in a parent project/folder/organization. - rpc ListFeeds(ListFeedsRequest) returns (ListFeedsResponse) { - option (google.api.http) = { - get: "/v1p2beta1/{parent=*/*}/feeds" - }; - option (google.api.method_signature) = "parent"; - } - - // Updates an asset feed configuration. - rpc UpdateFeed(UpdateFeedRequest) returns (Feed) { - option (google.api.http) = { - patch: "/v1p2beta1/{feed.name=*/*/feeds/*}" - body: "*" - }; - option (google.api.method_signature) = "feed"; - } - - // Deletes an asset feed. - rpc DeleteFeed(DeleteFeedRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p2beta1/{name=*/*/feeds/*}" - }; - option (google.api.method_signature) = "name"; - } -} - -// Create asset feed request. -message CreateFeedRequest { - // Required. The name of the project/folder/organization where this feed - // should be created in. It can only be an organization number (such as - // "organizations/123"), a folder number (such as "folders/123"), a project ID - // (such as "projects/my-project-id")", or a project number (such as - // "projects/12345"). - string parent = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. This is the client-assigned asset feed identifier and it needs to - // be unique under a specific parent project/folder/organization. - string feed_id = 2 [(google.api.field_behavior) = REQUIRED]; - - // Required. The feed details. The field `name` must be empty and it will be generated - // in the format of: - // projects/project_number/feeds/feed_id - // folders/folder_number/feeds/feed_id - // organizations/organization_number/feeds/feed_id - Feed feed = 3 [(google.api.field_behavior) = REQUIRED]; -} - -// Get asset feed request. -message GetFeedRequest { - // Required. The name of the Feed and it must be in the format of: - // projects/project_number/feeds/feed_id - // folders/folder_number/feeds/feed_id - // organizations/organization_number/feeds/feed_id - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "cloudasset.googleapis.com/Feed" - } - ]; -} - -// List asset feeds request. -message ListFeedsRequest { - // Required. The parent project/folder/organization whose feeds are to be - // listed. It can only be using project/folder/organization number (such as - // "folders/12345")", or a project ID (such as "projects/my-project-id"). - string parent = 1 [(google.api.field_behavior) = REQUIRED]; -} - -message ListFeedsResponse { - // A list of feeds. - repeated Feed feeds = 1; -} - -// Update asset feed request. -message UpdateFeedRequest { - // Required. The new values of feed details. It must match an existing feed and the - // field `name` must be in the format of: - // projects/project_number/feeds/feed_id or - // folders/folder_number/feeds/feed_id or - // organizations/organization_number/feeds/feed_id. - Feed feed = 1 [(google.api.field_behavior) = REQUIRED]; - - // Required. Only updates the `feed` fields indicated by this mask. - // The field mask must not be empty, and it must not contain fields that - // are immutable or only set by the server. - google.protobuf.FieldMask update_mask = 2 [(google.api.field_behavior) = REQUIRED]; -} - -message DeleteFeedRequest { - // Required. The name of the feed and it must be in the format of: - // projects/project_number/feeds/feed_id - // folders/folder_number/feeds/feed_id - // organizations/organization_number/feeds/feed_id - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "cloudasset.googleapis.com/Feed" - } - ]; -} - -// Output configuration for export assets destination. -message OutputConfig { - // Asset export destination. - oneof destination { - // Destination on Cloud Storage. - GcsDestination gcs_destination = 1; - } -} - -// A Cloud Storage location. -message GcsDestination { - // Required. - oneof object_uri { - // The uri of the Cloud Storage object. It's the same uri that is used by - // gsutil. For example: "gs://bucket_name/object_name". See [Viewing and - // Editing Object - // Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) - // for more information. - string uri = 1; - } -} - -// A Cloud Pubsub destination. -message PubsubDestination { - // The name of the Cloud Pub/Sub topic to publish to. - // For example: `projects/PROJECT_ID/topics/TOPIC_ID`. - string topic = 1; -} - -// Output configuration for asset feed destination. -message FeedOutputConfig { - // Asset feed destination. - oneof destination { - // Destination on Cloud Pubsub. - PubsubDestination pubsub_destination = 1; - } -} - -// An asset feed used to export asset updates to a destinations. -// An asset feed filter controls what updates are exported. -// The asset feed must be created within a project, organization, or -// folder. Supported destinations are: -// Cloud Pub/Sub topics. -message Feed { - option (google.api.resource) = { - type: "cloudasset.googleapis.com/Feed" - pattern: "projects/{project}/feeds/{feed}" - pattern: "folders/{folder}/feeds/{feed}" - pattern: "organizations/{organization}/feeds/{feed}" - history: ORIGINALLY_SINGLE_PATTERN - }; - - // Required. The format will be - // projects/{project_number}/feeds/{client-assigned_feed_identifier} or - // folders/{folder_number}/feeds/{client-assigned_feed_identifier} or - // organizations/{organization_number}/feeds/{client-assigned_feed_identifier} - // - // The client-assigned feed identifier must be unique within the parent - // project/folder/organization. - string name = 1 [(google.api.field_behavior) = REQUIRED]; - - // A list of the full names of the assets to receive updates. You must specify - // either or both of asset_names and asset_types. Only asset updates matching - // specified asset_names and asset_types are exported to the feed. For - // example: - // `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - // See [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more info. - repeated string asset_names = 2; - - // A list of types of the assets to receive updates. You must specify either - // or both of asset_names and asset_types. Only asset updates matching - // specified asset_names and asset_types are exported to the feed. - // For example: - // "compute.googleapis.com/Disk" See [Introduction to Cloud Asset - // Inventory](https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview) - // for all supported asset types. - repeated string asset_types = 3; - - // Asset content type. If not specified, no content but the asset name and - // type will be returned. - ContentType content_type = 4; - - // Required. Feed output configuration defining where the asset updates are - // published to. - FeedOutputConfig feed_output_config = 5 [(google.api.field_behavior) = REQUIRED]; -} - -// Asset content type. -enum ContentType { - // Unspecified content type. - CONTENT_TYPE_UNSPECIFIED = 0; - - // Resource metadata. - RESOURCE = 1; - - // The actual IAM policy set on a resource. - IAM_POLICY = 2; -} diff --git a/google/cloud/asset_v1p2beta1/proto/asset_service_pb2.py b/google/cloud/asset_v1p2beta1/proto/asset_service_pb2.py deleted file mode 100644 index 7c5005fa..00000000 --- a/google/cloud/asset_v1p2beta1/proto/asset_service_pb2.py +++ /dev/null @@ -1,1088 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1p2beta1/proto/asset_service.proto -"""Generated protocol buffer code.""" -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.asset_v1p2beta1.proto import ( - assets_pb2 as google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_assets__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1p2beta1/proto/asset_service.proto", - package="google.cloud.asset.v1p2beta1", - syntax="proto3", - serialized_options=b"\n com.google.cloud.asset.v1p2beta1B\021AssetServiceProtoP\001ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p2beta1;asset\252\002\034Google.Cloud.Asset.V1p2Beta1\312\002\034Google\\Cloud\\Asset\\V1p2Beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n6google/cloud/asset_v1p2beta1/proto/asset_service.proto\x12\x1cgoogle.cloud.asset.v1p2beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a/google/cloud/asset_v1p2beta1/proto/assets.proto\x1a#google/longrunning/operations.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto"u\n\x11\x43reateFeedRequest\x12\x13\n\x06parent\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x14\n\x07\x66\x65\x65\x64_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x35\n\x04\x66\x65\x65\x64\x18\x03 \x01(\x0b\x32".google.cloud.asset.v1p2beta1.FeedB\x03\xe0\x41\x02"F\n\x0eGetFeedRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudasset.googleapis.com/Feed"\'\n\x10ListFeedsRequest\x12\x13\n\x06parent\x18\x01 \x01(\tB\x03\xe0\x41\x02"F\n\x11ListFeedsResponse\x12\x31\n\x05\x66\x65\x65\x64s\x18\x01 \x03(\x0b\x32".google.cloud.asset.v1p2beta1.Feed"\x80\x01\n\x11UpdateFeedRequest\x12\x35\n\x04\x66\x65\x65\x64\x18\x01 \x01(\x0b\x32".google.cloud.asset.v1p2beta1.FeedB\x03\xe0\x41\x02\x12\x34\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x02"I\n\x11\x44\x65leteFeedRequest\x12\x34\n\x04name\x18\x01 \x01(\tB&\xe0\x41\x02\xfa\x41 \n\x1e\x63loudasset.googleapis.com/Feed"f\n\x0cOutputConfig\x12G\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32,.google.cloud.asset.v1p2beta1.GcsDestinationH\x00\x42\r\n\x0b\x64\x65stination"-\n\x0eGcsDestination\x12\r\n\x03uri\x18\x01 \x01(\tH\x00\x42\x0c\n\nobject_uri""\n\x11PubsubDestination\x12\r\n\x05topic\x18\x01 \x01(\t"p\n\x10\x46\x65\x65\x64OutputConfig\x12M\n\x12pubsub_destination\x18\x01 \x01(\x0b\x32/.google.cloud.asset.v1p2beta1.PubsubDestinationH\x00\x42\r\n\x0b\x64\x65stination"\xe9\x02\n\x04\x46\x65\x65\x64\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x13\n\x0b\x61sset_names\x18\x02 \x03(\t\x12\x13\n\x0b\x61sset_types\x18\x03 \x03(\t\x12?\n\x0c\x63ontent_type\x18\x04 \x01(\x0e\x32).google.cloud.asset.v1p2beta1.ContentType\x12O\n\x12\x66\x65\x65\x64_output_config\x18\x05 \x01(\x0b\x32..google.cloud.asset.v1p2beta1.FeedOutputConfigB\x03\xe0\x41\x02:\x91\x01\xea\x41\x8d\x01\n\x1e\x63loudasset.googleapis.com/Feed\x12\x1fprojects/{project}/feeds/{feed}\x12\x1d\x66olders/{folder}/feeds/{feed}\x12)organizations/{organization}/feeds/{feed} \x01*I\n\x0b\x43ontentType\x12\x1c\n\x18\x43ONTENT_TYPE_UNSPECIFIED\x10\x00\x12\x0c\n\x08RESOURCE\x10\x01\x12\x0e\n\nIAM_POLICY\x10\x02\x32\xbf\x06\n\x0c\x41ssetService\x12\x94\x01\n\nCreateFeed\x12/.google.cloud.asset.v1p2beta1.CreateFeedRequest\x1a".google.cloud.asset.v1p2beta1.Feed"1\x82\xd3\xe4\x93\x02""\x1d/v1p2beta1/{parent=*/*}/feeds:\x01*\xda\x41\x06parent\x12\x89\x01\n\x07GetFeed\x12,.google.cloud.asset.v1p2beta1.GetFeedRequest\x1a".google.cloud.asset.v1p2beta1.Feed",\x82\xd3\xe4\x93\x02\x1f\x12\x1d/v1p2beta1/{name=*/*/feeds/*}\xda\x41\x04name\x12\x9c\x01\n\tListFeeds\x12..google.cloud.asset.v1p2beta1.ListFeedsRequest\x1a/.google.cloud.asset.v1p2beta1.ListFeedsResponse".\x82\xd3\xe4\x93\x02\x1f\x12\x1d/v1p2beta1/{parent=*/*}/feeds\xda\x41\x06parent\x12\x97\x01\n\nUpdateFeed\x12/.google.cloud.asset.v1p2beta1.UpdateFeedRequest\x1a".google.cloud.asset.v1p2beta1.Feed"4\x82\xd3\xe4\x93\x02\'2"/v1p2beta1/{feed.name=*/*/feeds/*}:\x01*\xda\x41\x04\x66\x65\x65\x64\x12\x83\x01\n\nDeleteFeed\x12/.google.cloud.asset.v1p2beta1.DeleteFeedRequest\x1a\x16.google.protobuf.Empty",\x82\xd3\xe4\x93\x02\x1f*\x1d/v1p2beta1/{name=*/*/feeds/*}\xda\x41\x04name\x1aM\xca\x41\x19\x63loudasset.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xb8\x01\n com.google.cloud.asset.v1p2beta1B\x11\x41ssetServiceProtoP\x01ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p2beta1;asset\xaa\x02\x1cGoogle.Cloud.Asset.V1p2Beta1\xca\x02\x1cGoogle\\Cloud\\Asset\\V1p2Beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_assets__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - -_CONTENTTYPE = _descriptor.EnumDescriptor( - name="ContentType", - full_name="google.cloud.asset.v1p2beta1.ContentType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="CONTENT_TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RESOURCE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="IAM_POLICY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1560, - serialized_end=1633, -) -_sym_db.RegisterEnumDescriptor(_CONTENTTYPE) - -ContentType = enum_type_wrapper.EnumTypeWrapper(_CONTENTTYPE) -CONTENT_TYPE_UNSPECIFIED = 0 -RESOURCE = 1 -IAM_POLICY = 2 - - -_CREATEFEEDREQUEST = _descriptor.Descriptor( - name="CreateFeedRequest", - full_name="google.cloud.asset.v1p2beta1.CreateFeedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1p2beta1.CreateFeedRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="feed_id", - full_name="google.cloud.asset.v1p2beta1.CreateFeedRequest.feed_id", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="feed", - full_name="google.cloud.asset.v1p2beta1.CreateFeedRequest.feed", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=385, - serialized_end=502, -) - - -_GETFEEDREQUEST = _descriptor.Descriptor( - name="GetFeedRequest", - full_name="google.cloud.asset.v1p2beta1.GetFeedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1p2beta1.GetFeedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudasset.googleapis.com/Feed", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=504, - serialized_end=574, -) - - -_LISTFEEDSREQUEST = _descriptor.Descriptor( - name="ListFeedsRequest", - full_name="google.cloud.asset.v1p2beta1.ListFeedsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1p2beta1.ListFeedsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=576, - serialized_end=615, -) - - -_LISTFEEDSRESPONSE = _descriptor.Descriptor( - name="ListFeedsResponse", - full_name="google.cloud.asset.v1p2beta1.ListFeedsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="feeds", - full_name="google.cloud.asset.v1p2beta1.ListFeedsResponse.feeds", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=617, - serialized_end=687, -) - - -_UPDATEFEEDREQUEST = _descriptor.Descriptor( - name="UpdateFeedRequest", - full_name="google.cloud.asset.v1p2beta1.UpdateFeedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="feed", - full_name="google.cloud.asset.v1p2beta1.UpdateFeedRequest.feed", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.asset.v1p2beta1.UpdateFeedRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=690, - serialized_end=818, -) - - -_DELETEFEEDREQUEST = _descriptor.Descriptor( - name="DeleteFeedRequest", - full_name="google.cloud.asset.v1p2beta1.DeleteFeedRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1p2beta1.DeleteFeedRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A \n\036cloudasset.googleapis.com/Feed", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=820, - serialized_end=893, -) - - -_OUTPUTCONFIG = _descriptor.Descriptor( - name="OutputConfig", - full_name="google.cloud.asset.v1p2beta1.OutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_destination", - full_name="google.cloud.asset.v1p2beta1.OutputConfig.gcs_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="destination", - full_name="google.cloud.asset.v1p2beta1.OutputConfig.destination", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=895, - serialized_end=997, -) - - -_GCSDESTINATION = _descriptor.Descriptor( - name="GcsDestination", - full_name="google.cloud.asset.v1p2beta1.GcsDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.asset.v1p2beta1.GcsDestination.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="object_uri", - full_name="google.cloud.asset.v1p2beta1.GcsDestination.object_uri", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=999, - serialized_end=1044, -) - - -_PUBSUBDESTINATION = _descriptor.Descriptor( - name="PubsubDestination", - full_name="google.cloud.asset.v1p2beta1.PubsubDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="topic", - full_name="google.cloud.asset.v1p2beta1.PubsubDestination.topic", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1046, - serialized_end=1080, -) - - -_FEEDOUTPUTCONFIG = _descriptor.Descriptor( - name="FeedOutputConfig", - full_name="google.cloud.asset.v1p2beta1.FeedOutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="pubsub_destination", - full_name="google.cloud.asset.v1p2beta1.FeedOutputConfig.pubsub_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="destination", - full_name="google.cloud.asset.v1p2beta1.FeedOutputConfig.destination", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=1082, - serialized_end=1194, -) - - -_FEED = _descriptor.Descriptor( - name="Feed", - full_name="google.cloud.asset.v1p2beta1.Feed", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1p2beta1.Feed.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_names", - full_name="google.cloud.asset.v1p2beta1.Feed.asset_names", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_types", - full_name="google.cloud.asset.v1p2beta1.Feed.asset_types", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content_type", - full_name="google.cloud.asset.v1p2beta1.Feed.content_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="feed_output_config", - full_name="google.cloud.asset.v1p2beta1.Feed.feed_output_config", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352A\215\001\n\036cloudasset.googleapis.com/Feed\022\037projects/{project}/feeds/{feed}\022\035folders/{folder}/feeds/{feed}\022)organizations/{organization}/feeds/{feed} \001", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1197, - serialized_end=1558, -) - -_CREATEFEEDREQUEST.fields_by_name["feed"].message_type = _FEED -_LISTFEEDSRESPONSE.fields_by_name["feeds"].message_type = _FEED -_UPDATEFEEDREQUEST.fields_by_name["feed"].message_type = _FEED -_UPDATEFEEDREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_OUTPUTCONFIG.fields_by_name["gcs_destination"].message_type = _GCSDESTINATION -_OUTPUTCONFIG.oneofs_by_name["destination"].fields.append( - _OUTPUTCONFIG.fields_by_name["gcs_destination"] -) -_OUTPUTCONFIG.fields_by_name[ - "gcs_destination" -].containing_oneof = _OUTPUTCONFIG.oneofs_by_name["destination"] -_GCSDESTINATION.oneofs_by_name["object_uri"].fields.append( - _GCSDESTINATION.fields_by_name["uri"] -) -_GCSDESTINATION.fields_by_name["uri"].containing_oneof = _GCSDESTINATION.oneofs_by_name[ - "object_uri" -] -_FEEDOUTPUTCONFIG.fields_by_name["pubsub_destination"].message_type = _PUBSUBDESTINATION -_FEEDOUTPUTCONFIG.oneofs_by_name["destination"].fields.append( - _FEEDOUTPUTCONFIG.fields_by_name["pubsub_destination"] -) -_FEEDOUTPUTCONFIG.fields_by_name[ - "pubsub_destination" -].containing_oneof = _FEEDOUTPUTCONFIG.oneofs_by_name["destination"] -_FEED.fields_by_name["content_type"].enum_type = _CONTENTTYPE -_FEED.fields_by_name["feed_output_config"].message_type = _FEEDOUTPUTCONFIG -DESCRIPTOR.message_types_by_name["CreateFeedRequest"] = _CREATEFEEDREQUEST -DESCRIPTOR.message_types_by_name["GetFeedRequest"] = _GETFEEDREQUEST -DESCRIPTOR.message_types_by_name["ListFeedsRequest"] = _LISTFEEDSREQUEST -DESCRIPTOR.message_types_by_name["ListFeedsResponse"] = _LISTFEEDSRESPONSE -DESCRIPTOR.message_types_by_name["UpdateFeedRequest"] = _UPDATEFEEDREQUEST -DESCRIPTOR.message_types_by_name["DeleteFeedRequest"] = _DELETEFEEDREQUEST -DESCRIPTOR.message_types_by_name["OutputConfig"] = _OUTPUTCONFIG -DESCRIPTOR.message_types_by_name["GcsDestination"] = _GCSDESTINATION -DESCRIPTOR.message_types_by_name["PubsubDestination"] = _PUBSUBDESTINATION -DESCRIPTOR.message_types_by_name["FeedOutputConfig"] = _FEEDOUTPUTCONFIG -DESCRIPTOR.message_types_by_name["Feed"] = _FEED -DESCRIPTOR.enum_types_by_name["ContentType"] = _CONTENTTYPE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -CreateFeedRequest = _reflection.GeneratedProtocolMessageType( - "CreateFeedRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEFEEDREQUEST, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """Create asset feed request. - - Attributes: - parent: - Required. The name of the project/folder/organization where - this feed should be created in. It can only be an organization - number (such as “organizations/123”), a folder number (such as - “folders/123”), a project ID (such as “projects/my-project- - id”)“, or a project number (such as”projects/12345"). - feed_id: - Required. This is the client-assigned asset feed identifier - and it needs to be unique under a specific parent - project/folder/organization. - feed: - Required. The feed details. The field ``name`` must be empty - and it will be generated in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.CreateFeedRequest) - }, -) -_sym_db.RegisterMessage(CreateFeedRequest) - -GetFeedRequest = _reflection.GeneratedProtocolMessageType( - "GetFeedRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETFEEDREQUEST, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """Get asset feed request. - - Attributes: - name: - Required. The name of the Feed and it must be in the format - of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.GetFeedRequest) - }, -) -_sym_db.RegisterMessage(GetFeedRequest) - -ListFeedsRequest = _reflection.GeneratedProtocolMessageType( - "ListFeedsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTFEEDSREQUEST, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """List asset feeds request. - - Attributes: - parent: - Required. The parent project/folder/organization whose feeds - are to be listed. It can only be using - project/folder/organization number (such as “folders/12345”)“, - or a project ID (such as”projects/my-project-id"). - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.ListFeedsRequest) - }, -) -_sym_db.RegisterMessage(ListFeedsRequest) - -ListFeedsResponse = _reflection.GeneratedProtocolMessageType( - "ListFeedsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTFEEDSRESPONSE, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """ - Attributes: - feeds: - A list of feeds. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.ListFeedsResponse) - }, -) -_sym_db.RegisterMessage(ListFeedsResponse) - -UpdateFeedRequest = _reflection.GeneratedProtocolMessageType( - "UpdateFeedRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEFEEDREQUEST, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """Update asset feed request. - - Attributes: - feed: - Required. The new values of feed details. It must match an - existing feed and the field ``name`` must be in the format of: - projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - update_mask: - Required. Only updates the ``feed`` fields indicated by this - mask. The field mask must not be empty, and it must not - contain fields that are immutable or only set by the server. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.UpdateFeedRequest) - }, -) -_sym_db.RegisterMessage(UpdateFeedRequest) - -DeleteFeedRequest = _reflection.GeneratedProtocolMessageType( - "DeleteFeedRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEFEEDREQUEST, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """ - Attributes: - name: - Required. The name of the feed and it must be in the format - of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.DeleteFeedRequest) - }, -) -_sym_db.RegisterMessage(DeleteFeedRequest) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """Output configuration for export assets destination. - - Attributes: - destination: - Asset export destination. - gcs_destination: - Destination on Cloud Storage. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """A Cloud Storage location. - - Attributes: - object_uri: - Required. - uri: - The uri of the Cloud Storage object. It’s the same uri that is - used by gsutil. For example: “gs://bucket_name/object_name”. - See `Viewing and Editing Object Metadata - `__ for more information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - -PubsubDestination = _reflection.GeneratedProtocolMessageType( - "PubsubDestination", - (_message.Message,), - { - "DESCRIPTOR": _PUBSUBDESTINATION, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """A Cloud Pubsub destination. - - Attributes: - topic: - The name of the Cloud Pub/Sub topic to publish to. For - example: ``projects/PROJECT_ID/topics/TOPIC_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.PubsubDestination) - }, -) -_sym_db.RegisterMessage(PubsubDestination) - -FeedOutputConfig = _reflection.GeneratedProtocolMessageType( - "FeedOutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _FEEDOUTPUTCONFIG, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """Output configuration for asset feed destination. - - Attributes: - destination: - Asset feed destination. - pubsub_destination: - Destination on Cloud Pubsub. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.FeedOutputConfig) - }, -) -_sym_db.RegisterMessage(FeedOutputConfig) - -Feed = _reflection.GeneratedProtocolMessageType( - "Feed", - (_message.Message,), - { - "DESCRIPTOR": _FEED, - "__module__": "google.cloud.asset_v1p2beta1.proto.asset_service_pb2", - "__doc__": """An asset feed used to export asset updates to a destinations. An asset - feed filter controls what updates are exported. The asset feed must be - created within a project, organization, or folder. Supported - destinations are: Cloud Pub/Sub topics. - - Attributes: - name: - Required. The format will be - projects/{project_number}/feeds/{client- - assigned_feed_identifier} or - folders/{folder_number}/feeds/{client- - assigned_feed_identifier} or - organizations/{organization_number}/feeds/{client- - assigned_feed_identifier} The client-assigned feed identifier - must be unique within the parent project/folder/organization. - asset_names: - A list of the full names of the assets to receive updates. You - must specify either or both of asset_names and asset_types. - Only asset updates matching specified asset_names and - asset_types are exported to the feed. For example: ``//compute - .googleapis.com/projects/my_project_123/zones/zone1/instances/ - instance1``. See `Resource Names `__ for more info. - asset_types: - A list of types of the assets to receive updates. You must - specify either or both of asset_names and asset_types. Only - asset updates matching specified asset_names and asset_types - are exported to the feed. For example: - “compute.googleapis.com/Disk” See `Introduction to Cloud Asset - Inventory `__ for all - supported asset types. - content_type: - Asset content type. If not specified, no content but the asset - name and type will be returned. - feed_output_config: - Required. Feed output configuration defining where the asset - updates are published to. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.Feed) - }, -) -_sym_db.RegisterMessage(Feed) - - -DESCRIPTOR._options = None -_CREATEFEEDREQUEST.fields_by_name["parent"]._options = None -_CREATEFEEDREQUEST.fields_by_name["feed_id"]._options = None -_CREATEFEEDREQUEST.fields_by_name["feed"]._options = None -_GETFEEDREQUEST.fields_by_name["name"]._options = None -_LISTFEEDSREQUEST.fields_by_name["parent"]._options = None -_UPDATEFEEDREQUEST.fields_by_name["feed"]._options = None -_UPDATEFEEDREQUEST.fields_by_name["update_mask"]._options = None -_DELETEFEEDREQUEST.fields_by_name["name"]._options = None -_FEED.fields_by_name["name"]._options = None -_FEED.fields_by_name["feed_output_config"]._options = None -_FEED._options = None - -_ASSETSERVICE = _descriptor.ServiceDescriptor( - name="AssetService", - full_name="google.cloud.asset.v1p2beta1.AssetService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\031cloudasset.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=1636, - serialized_end=2467, - methods=[ - _descriptor.MethodDescriptor( - name="CreateFeed", - full_name="google.cloud.asset.v1p2beta1.AssetService.CreateFeed", - index=0, - containing_service=None, - input_type=_CREATEFEEDREQUEST, - output_type=_FEED, - serialized_options=b'\202\323\344\223\002""\035/v1p2beta1/{parent=*/*}/feeds:\001*\332A\006parent', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetFeed", - full_name="google.cloud.asset.v1p2beta1.AssetService.GetFeed", - index=1, - containing_service=None, - input_type=_GETFEEDREQUEST, - output_type=_FEED, - serialized_options=b"\202\323\344\223\002\037\022\035/v1p2beta1/{name=*/*/feeds/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListFeeds", - full_name="google.cloud.asset.v1p2beta1.AssetService.ListFeeds", - index=2, - containing_service=None, - input_type=_LISTFEEDSREQUEST, - output_type=_LISTFEEDSRESPONSE, - serialized_options=b"\202\323\344\223\002\037\022\035/v1p2beta1/{parent=*/*}/feeds\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateFeed", - full_name="google.cloud.asset.v1p2beta1.AssetService.UpdateFeed", - index=3, - containing_service=None, - input_type=_UPDATEFEEDREQUEST, - output_type=_FEED, - serialized_options=b"\202\323\344\223\002'2\"/v1p2beta1/{feed.name=*/*/feeds/*}:\001*\332A\004feed", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteFeed", - full_name="google.cloud.asset.v1p2beta1.AssetService.DeleteFeed", - index=4, - containing_service=None, - input_type=_DELETEFEEDREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002\037*\035/v1p2beta1/{name=*/*/feeds/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_ASSETSERVICE) - -DESCRIPTOR.services_by_name["AssetService"] = _ASSETSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1p2beta1/proto/asset_service_pb2_grpc.py b/google/cloud/asset_v1p2beta1/proto/asset_service_pb2_grpc.py deleted file mode 100644 index 7c558f97..00000000 --- a/google/cloud/asset_v1p2beta1/proto/asset_service_pb2_grpc.py +++ /dev/null @@ -1,261 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.asset_v1p2beta1.proto import ( - asset_service_pb2 as google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class AssetServiceStub(object): - """Asset service definition. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.CreateFeed = channel.unary_unary( - "/google.cloud.asset.v1p2beta1.AssetService/CreateFeed", - request_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.CreateFeedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.FromString, - ) - self.GetFeed = channel.unary_unary( - "/google.cloud.asset.v1p2beta1.AssetService/GetFeed", - request_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.GetFeedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.FromString, - ) - self.ListFeeds = channel.unary_unary( - "/google.cloud.asset.v1p2beta1.AssetService/ListFeeds", - request_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.ListFeedsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.ListFeedsResponse.FromString, - ) - self.UpdateFeed = channel.unary_unary( - "/google.cloud.asset.v1p2beta1.AssetService/UpdateFeed", - request_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.UpdateFeedRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.FromString, - ) - self.DeleteFeed = channel.unary_unary( - "/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed", - request_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.DeleteFeedRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - - -class AssetServiceServicer(object): - """Asset service definition. - """ - - def CreateFeed(self, request, context): - """Creates a feed in a parent project/folder/organization to listen to its - asset updates. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetFeed(self, request, context): - """Gets details about an asset feed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListFeeds(self, request, context): - """Lists all asset feeds in a parent project/folder/organization. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateFeed(self, request, context): - """Updates an asset feed configuration. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteFeed(self, request, context): - """Deletes an asset feed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_AssetServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "CreateFeed": grpc.unary_unary_rpc_method_handler( - servicer.CreateFeed, - request_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.CreateFeedRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.SerializeToString, - ), - "GetFeed": grpc.unary_unary_rpc_method_handler( - servicer.GetFeed, - request_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.GetFeedRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.SerializeToString, - ), - "ListFeeds": grpc.unary_unary_rpc_method_handler( - servicer.ListFeeds, - request_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.ListFeedsRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.ListFeedsResponse.SerializeToString, - ), - "UpdateFeed": grpc.unary_unary_rpc_method_handler( - servicer.UpdateFeed, - request_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.UpdateFeedRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.SerializeToString, - ), - "DeleteFeed": grpc.unary_unary_rpc_method_handler( - servicer.DeleteFeed, - request_deserializer=google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.DeleteFeedRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.asset.v1p2beta1.AssetService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class AssetService(object): - """Asset service definition. - """ - - @staticmethod - def CreateFeed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1p2beta1.AssetService/CreateFeed", - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.CreateFeedRequest.SerializeToString, - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetFeed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1p2beta1.AssetService/GetFeed", - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.GetFeedRequest.SerializeToString, - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListFeeds( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1p2beta1.AssetService/ListFeeds", - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.ListFeedsRequest.SerializeToString, - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.ListFeedsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateFeed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1p2beta1.AssetService/UpdateFeed", - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.UpdateFeedRequest.SerializeToString, - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.Feed.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteFeed( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed", - google_dot_cloud_dot_asset__v1p2beta1_dot_proto_dot_asset__service__pb2.DeleteFeedRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/asset_v1p2beta1/proto/assets.proto b/google/cloud/asset_v1p2beta1/proto/assets.proto deleted file mode 100644 index 8fee229b..00000000 --- a/google/cloud/asset_v1p2beta1/proto/assets.proto +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.asset.v1p2beta1; - -import "google/api/annotations.proto"; -import "google/iam/v1/policy.proto"; -import "google/protobuf/any.proto"; -import "google/protobuf/struct.proto"; -import "google/protobuf/timestamp.proto"; - -option cc_enable_arenas = true; -option csharp_namespace = "Google.Cloud.Asset.v1p2beta1"; -option go_package = "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1;asset"; -option java_multiple_files = true; -option java_outer_classname = "AssetProto"; -option java_package = "com.google.cloud.asset.v1p2beta1"; -option php_namespace = "Google\\Cloud\\Asset\\v1p2beta1"; - -// Temporal asset. In addition to the asset, the temporal asset includes the -// status of the asset and valid from and to time of it. -message TemporalAsset { - // The time window when the asset data and state was observed. - TimeWindow window = 1; - - // If the asset is deleted or not. - bool deleted = 2; - - // Asset. - Asset asset = 3; -} - -// A time window of (start_time, end_time]. -message TimeWindow { - // Start time of the time window (exclusive). - google.protobuf.Timestamp start_time = 1; - - // End time of the time window (inclusive). - // Current timestamp if not specified. - google.protobuf.Timestamp end_time = 2; -} - -// Cloud asset. This includes all Google Cloud Platform resources, -// Cloud IAM policies, and other non-GCP assets. -message Asset { - // The full name of the asset. For example: - // `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. - // See [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more information. - string name = 1; - - // Type of the asset. Example: "compute.googleapis.com/Disk". - string asset_type = 2; - - // Representation of the resource. - Resource resource = 3; - - // Representation of the actual Cloud IAM policy set on a cloud resource. For - // each resource, there must be at most one Cloud IAM policy set on it. - google.iam.v1.Policy iam_policy = 4; - - // Asset's ancestry path in Cloud Resource Manager (CRM) hierarchy, - // represented as a list of relative resource names. Ancestry path starts with - // the closest CRM ancestor and ends at root. If the asset is a CRM - // project/folder/organization, this starts from the asset itself. - // - // Example: ["projects/123456789", "folders/5432", "organizations/1234"] - repeated string ancestors = 6; -} - -// Representation of a cloud resource. -message Resource { - // The API version. Example: "v1". - string version = 1; - - // The URL of the discovery document containing the resource's JSON schema. - // For example: - // `"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"`. - // It will be left unspecified for resources without a discovery-based API, - // such as Cloud Bigtable. - string discovery_document_uri = 2; - - // The JSON schema name listed in the discovery document. - // Example: "Project". It will be left unspecified for resources (such as - // Cloud Bigtable) without a discovery-based API. - string discovery_name = 3; - - // The REST URL for accessing the resource. An HTTP GET operation using this - // URL returns the resource itself. - // Example: - // `https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`. - // It will be left unspecified for resources without a REST API. - string resource_url = 4; - - // The full name of the immediate parent of this resource. See - // [Resource - // Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) - // for more information. - // - // For GCP assets, it is the parent resource defined in the [Cloud IAM policy - // hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy). - // For example: - // `"//cloudresourcemanager.googleapis.com/projects/my_project_123"`. - // - // For third-party assets, it is up to the users to define. - string parent = 5; - - // The content of the resource, in which some sensitive fields are scrubbed - // away and may not be present. - google.protobuf.Struct data = 6; -} diff --git a/google/cloud/asset_v1p2beta1/proto/assets_pb2.py b/google/cloud/asset_v1p2beta1/proto/assets_pb2.py deleted file mode 100644 index f1b713c5..00000000 --- a/google/cloud/asset_v1p2beta1/proto/assets_pb2.py +++ /dev/null @@ -1,579 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1p2beta1/proto/assets.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1p2beta1/proto/assets.proto", - package="google.cloud.asset.v1p2beta1", - syntax="proto3", - serialized_options=b"\n com.google.cloud.asset.v1p2beta1B\nAssetProtoP\001ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p2beta1;asset\370\001\001\252\002\034Google.Cloud.Asset.v1p2beta1\312\002\034Google\\Cloud\\Asset\\v1p2beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n/google/cloud/asset_v1p2beta1/proto/assets.proto\x12\x1cgoogle.cloud.asset.v1p2beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a\x19google/protobuf/any.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\x8e\x01\n\rTemporalAsset\x12\x38\n\x06window\x18\x01 \x01(\x0b\x32(.google.cloud.asset.v1p2beta1.TimeWindow\x12\x0f\n\x07\x64\x65leted\x18\x02 \x01(\x08\x12\x32\n\x05\x61sset\x18\x03 \x01(\x0b\x32#.google.cloud.asset.v1p2beta1.Asset"j\n\nTimeWindow\x12.\n\nstart_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\xa1\x01\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\nasset_type\x18\x02 \x01(\t\x12\x38\n\x08resource\x18\x03 \x01(\x0b\x32&.google.cloud.asset.v1p2beta1.Resource\x12)\n\niam_policy\x18\x04 \x01(\x0b\x32\x15.google.iam.v1.Policy\x12\x11\n\tancestors\x18\x06 \x03(\t"\xa0\x01\n\x08Resource\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x1e\n\x16\x64iscovery_document_uri\x18\x02 \x01(\t\x12\x16\n\x0e\x64iscovery_name\x18\x03 \x01(\t\x12\x14\n\x0cresource_url\x18\x04 \x01(\t\x12\x0e\n\x06parent\x18\x05 \x01(\t\x12%\n\x04\x64\x61ta\x18\x06 \x01(\x0b\x32\x17.google.protobuf.StructB\xb4\x01\n com.google.cloud.asset.v1p2beta1B\nAssetProtoP\x01ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p2beta1;asset\xf8\x01\x01\xaa\x02\x1cGoogle.Cloud.Asset.v1p2beta1\xca\x02\x1cGoogle\\Cloud\\Asset\\v1p2beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_protobuf_dot_any__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_TEMPORALASSET = _descriptor.Descriptor( - name="TemporalAsset", - full_name="google.cloud.asset.v1p2beta1.TemporalAsset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="window", - full_name="google.cloud.asset.v1p2beta1.TemporalAsset.window", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="deleted", - full_name="google.cloud.asset.v1p2beta1.TemporalAsset.deleted", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset", - full_name="google.cloud.asset.v1p2beta1.TemporalAsset.asset", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=230, - serialized_end=372, -) - - -_TIMEWINDOW = _descriptor.Descriptor( - name="TimeWindow", - full_name="google.cloud.asset.v1p2beta1.TimeWindow", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="start_time", - full_name="google.cloud.asset.v1p2beta1.TimeWindow.start_time", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.asset.v1p2beta1.TimeWindow.end_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=374, - serialized_end=480, -) - - -_ASSET = _descriptor.Descriptor( - name="Asset", - full_name="google.cloud.asset.v1p2beta1.Asset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1p2beta1.Asset.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_type", - full_name="google.cloud.asset.v1p2beta1.Asset.asset_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.asset.v1p2beta1.Asset.resource", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="iam_policy", - full_name="google.cloud.asset.v1p2beta1.Asset.iam_policy", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ancestors", - full_name="google.cloud.asset.v1p2beta1.Asset.ancestors", - index=4, - number=6, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=483, - serialized_end=644, -) - - -_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.asset.v1p2beta1.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="version", - full_name="google.cloud.asset.v1p2beta1.Resource.version", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="discovery_document_uri", - full_name="google.cloud.asset.v1p2beta1.Resource.discovery_document_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="discovery_name", - full_name="google.cloud.asset.v1p2beta1.Resource.discovery_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_url", - full_name="google.cloud.asset.v1p2beta1.Resource.resource_url", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1p2beta1.Resource.parent", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="data", - full_name="google.cloud.asset.v1p2beta1.Resource.data", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=647, - serialized_end=807, -) - -_TEMPORALASSET.fields_by_name["window"].message_type = _TIMEWINDOW -_TEMPORALASSET.fields_by_name["asset"].message_type = _ASSET -_TIMEWINDOW.fields_by_name[ - "start_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_TIMEWINDOW.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_ASSET.fields_by_name["resource"].message_type = _RESOURCE -_ASSET.fields_by_name[ - "iam_policy" -].message_type = ( - google_dot_iam_dot_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._POLICY -) -_RESOURCE.fields_by_name[ - "data" -].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -DESCRIPTOR.message_types_by_name["TemporalAsset"] = _TEMPORALASSET -DESCRIPTOR.message_types_by_name["TimeWindow"] = _TIMEWINDOW -DESCRIPTOR.message_types_by_name["Asset"] = _ASSET -DESCRIPTOR.message_types_by_name["Resource"] = _RESOURCE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TemporalAsset = _reflection.GeneratedProtocolMessageType( - "TemporalAsset", - (_message.Message,), - { - "DESCRIPTOR": _TEMPORALASSET, - "__module__": "google.cloud.asset_v1p2beta1.proto.assets_pb2", - "__doc__": """Temporal asset. In addition to the asset, the temporal asset includes - the status of the asset and valid from and to time of it. - - Attributes: - window: - The time window when the asset data and state was observed. - deleted: - If the asset is deleted or not. - asset: - Asset. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.TemporalAsset) - }, -) -_sym_db.RegisterMessage(TemporalAsset) - -TimeWindow = _reflection.GeneratedProtocolMessageType( - "TimeWindow", - (_message.Message,), - { - "DESCRIPTOR": _TIMEWINDOW, - "__module__": "google.cloud.asset_v1p2beta1.proto.assets_pb2", - "__doc__": """A time window of (start_time, end_time]. - - Attributes: - start_time: - Start time of the time window (exclusive). - end_time: - End time of the time window (inclusive). Current timestamp if - not specified. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.TimeWindow) - }, -) -_sym_db.RegisterMessage(TimeWindow) - -Asset = _reflection.GeneratedProtocolMessageType( - "Asset", - (_message.Message,), - { - "DESCRIPTOR": _ASSET, - "__module__": "google.cloud.asset_v1p2beta1.proto.assets_pb2", - "__doc__": """Cloud asset. This includes all Google Cloud Platform resources, Cloud - IAM policies, and other non-GCP assets. - - Attributes: - name: - - The full name of the asset. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See https://cloud.google.com/apis/design/resource_names#full_resource_name - for more information. - asset_type: - Type of the asset. Example: “compute.googleapis.com/Disk”. - resource: - Representation of the resource. - iam_policy: - Representation of the actual Cloud IAM policy set on a cloud - resource. For each resource, there must be at most one Cloud - IAM policy set on it. - ancestors: - Asset’s ancestry path in Cloud Resource Manager (CRM) - hierarchy, represented as a list of relative resource names. - Ancestry path starts with the closest CRM ancestor and ends at - root. If the asset is a CRM project/folder/organization, this - starts from the asset itself. Example: [“projects/123456789”, - “folders/5432”, “organizations/1234”] - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.Asset) - }, -) -_sym_db.RegisterMessage(Asset) - -Resource = _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _RESOURCE, - "__module__": "google.cloud.asset_v1p2beta1.proto.assets_pb2", - "__doc__": """Representation of a cloud resource. - - Attributes: - version: - The API version. Example: “v1”. - discovery_document_uri: - The URL of the discovery document containing the resource’s - JSON schema. For example: ``"https://www.googleapis.com/discov - ery/v1/apis/compute/v1/rest"``. It will be left unspecified - for resources without a discovery-based API, such as Cloud - Bigtable. - discovery_name: - The JSON schema name listed in the discovery document. - Example: “Project”. It will be left unspecified for resources - (such as Cloud Bigtable) without a discovery-based API. - resource_url: - The REST URL for accessing the resource. An HTTP GET operation - using this URL returns the resource itself. Example: - ``https://cloudresourcemanager.googleapis.com/v1/projects/my- - project-123``. It will be left unspecified for resources - without a REST API. - parent: - The full name of the immediate parent of this resource. See - `Resource Names `__ for more information. For GCP - assets, it is the parent resource defined in the `Cloud IAM - policy hierarchy `__. For example: ``"//cloudresourcemanager.go - ogleapis.com/projects/my_project_123"``. For third-party - assets, it is up to the users to define. - data: - The content of the resource, in which some sensitive fields - are scrubbed away and may not be present. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.Resource) - }, -) -_sym_db.RegisterMessage(Resource) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1p2beta1/proto/assets_pb2_grpc.py b/google/cloud/asset_v1p2beta1/proto/assets_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/asset_v1p2beta1/proto/assets_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/asset_v1p2beta1/py.typed b/google/cloud/asset_v1p2beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/google/cloud/asset_v1p2beta1/services/__init__.py b/google/cloud/asset_v1p2beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/asset_v1p2beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py b/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py new file mode 100644 index 00000000..ec3c27d2 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient + +__all__ = ( + "AssetServiceClient", + "AssetServiceAsyncClient", +) diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py b/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..bfbd2a04 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.asset_v1p2beta1.types import asset_service + +from .transports.base import AssetServiceTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + feed_path = staticmethod(AssetServiceClient.feed_path) + + from_service_account_file = AssetServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(AssetServiceClient).get_transport_class, type(AssetServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = AssetServiceClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def create_feed( + self, + request: asset_service.CreateFeedRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Args: + request (:class:`~.asset_service.CreateFeedRequest`): + The request object. Create asset feed request. + parent (:class:`str`): + Required. The name of the + project/folder/organization where this + feed should be created in. It can only + be an organization number (such as + "organizations/123"), a folder number + (such as "folders/123"), a project ID + (such as "projects/my-project-id")", or + a project number (such as + "projects/12345"). + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Cloud Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.CreateFeedRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_feed, + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_feed( + self, + request: asset_service.GetFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + Args: + request (:class:`~.asset_service.GetFeedRequest`): + The request object. Get asset feed request. + name (:class:`str`): + Required. The name of the Feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Cloud Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.GetFeedRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_feed, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_feeds( + self, + request: asset_service.ListFeedsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + Args: + request (:class:`~.asset_service.ListFeedsRequest`): + The request object. List asset feeds request. + parent (:class:`str`): + Required. The parent + project/folder/organization whose feeds + are to be listed. It can only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListFeedsResponse: + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.ListFeedsRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_feeds, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_feed( + self, + request: asset_service.UpdateFeedRequest = None, + *, + feed: asset_service.Feed = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + Args: + request (:class:`~.asset_service.UpdateFeedRequest`): + The request object. Update asset feed request. + feed (:class:`~.asset_service.Feed`): + Required. The new values of feed details. It must match + an existing feed and the field ``name`` must be in the + format of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + This corresponds to the ``feed`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Cloud Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([feed]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.UpdateFeedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if feed is not None: + request.feed = feed + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_feed, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("feed.name", request.feed.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_feed( + self, + request: asset_service.DeleteFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an asset feed. + + Args: + request (:class:`~.asset_service.DeleteFeedRequest`): + The request object. + name (:class:`str`): + Required. The name of the feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = asset_service.DeleteFeedRequest(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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_feed, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceAsyncClient",) diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/client.py b/google/cloud/asset_v1p2beta1/services/asset_service/client.py new file mode 100644 index 00000000..729ccabb --- /dev/null +++ b/google/cloud/asset_v1p2beta1/services/asset_service/client.py @@ -0,0 +1,627 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.asset_v1p2beta1.types import asset_service + +from .transports.base import AssetServiceTransport +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudasset.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def feed_path(project: str, feed: str,) -> str: + """Return a fully-qualified feed string.""" + return "projects/{project}/feeds/{feed}".format(project=project, feed=feed,) + + @staticmethod + def parse_feed_path(path: str) -> Dict[str, str]: + """Parse a feed path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AssetServiceTransport): + # transport is a AssetServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def create_feed( + self, + request: asset_service.CreateFeedRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Args: + request (:class:`~.asset_service.CreateFeedRequest`): + The request object. Create asset feed request. + parent (:class:`str`): + Required. The name of the + project/folder/organization where this + feed should be created in. It can only + be an organization number (such as + "organizations/123"), a folder number + (such as "folders/123"), a project ID + (such as "projects/my-project-id")", or + a project number (such as + "projects/12345"). + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Cloud Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.CreateFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.CreateFeedRequest): + request = asset_service.CreateFeedRequest(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._transport._wrapped_methods[self._transport.create_feed] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_feed( + self, + request: asset_service.GetFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + Args: + request (:class:`~.asset_service.GetFeedRequest`): + The request object. Get asset feed request. + name (:class:`str`): + Required. The name of the Feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Cloud Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.GetFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.GetFeedRequest): + request = asset_service.GetFeedRequest(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._transport._wrapped_methods[self._transport.get_feed] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_feeds( + self, + request: asset_service.ListFeedsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + Args: + request (:class:`~.asset_service.ListFeedsRequest`): + The request object. List asset feeds request. + parent (:class:`str`): + Required. The parent + project/folder/organization whose feeds + are to be listed. It can only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListFeedsResponse: + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.ListFeedsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ListFeedsRequest): + request = asset_service.ListFeedsRequest(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._transport._wrapped_methods[self._transport.list_feeds] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_feed( + self, + request: asset_service.UpdateFeedRequest = None, + *, + feed: asset_service.Feed = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + Args: + request (:class:`~.asset_service.UpdateFeedRequest`): + The request object. Update asset feed request. + feed (:class:`~.asset_service.Feed`): + Required. The new values of feed details. It must match + an existing feed and the field ``name`` must be in the + format of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + This corresponds to the ``feed`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + Cloud Pub/Sub topics. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([feed]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.UpdateFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.UpdateFeedRequest): + request = asset_service.UpdateFeedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if feed is not None: + request.feed = feed + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_feed] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("feed.name", request.feed.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_feed( + self, + request: asset_service.DeleteFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an asset feed. + + Args: + request (:class:`~.asset_service.DeleteFeedRequest`): + The request object. + name (:class:`str`): + Required. The name of the feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.DeleteFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.DeleteFeedRequest): + request = asset_service.DeleteFeedRequest(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._transport._wrapped_methods[self._transport.delete_feed] + + # 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),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceClient",) diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..624eab74 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry["grpc"] = AssetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + +__all__ = ( + "AssetServiceTransport", + "AssetServiceGrpcTransport", + "AssetServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..d397e55b --- /dev/null +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py @@ -0,0 +1,198 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.asset_v1p2beta1.types import asset_service +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_feed: gapic_v1.method.wrap_method( + self.create_feed, default_timeout=60.0, client_info=_client_info, + ), + self.get_feed: gapic_v1.method.wrap_method( + self.get_feed, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.list_feeds: gapic_v1.method.wrap_method( + self.list_feeds, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_feed: gapic_v1.method.wrap_method( + self.update_feed, default_timeout=60.0, client_info=_client_info, + ), + self.delete_feed: gapic_v1.method.wrap_method( + self.delete_feed, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + } + + @property + def create_feed( + self, + ) -> typing.Callable[ + [asset_service.CreateFeedRequest], + typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + ]: + raise NotImplementedError() + + @property + def get_feed( + self, + ) -> typing.Callable[ + [asset_service.GetFeedRequest], + typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + ]: + raise NotImplementedError() + + @property + def list_feeds( + self, + ) -> typing.Callable[ + [asset_service.ListFeedsRequest], + typing.Union[ + asset_service.ListFeedsResponse, + typing.Awaitable[asset_service.ListFeedsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_feed( + self, + ) -> typing.Callable[ + [asset_service.UpdateFeedRequest], + typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + ]: + raise NotImplementedError() + + @property + def delete_feed( + self, + ) -> typing.Callable[ + [asset_service.DeleteFeedRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + +__all__ = ("AssetServiceTransport",) diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..c4708959 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,337 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.asset_v1p2beta1.types import asset_service +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import AssetServiceTransport + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def create_feed( + self, + ) -> Callable[[asset_service.CreateFeedRequest], asset_service.Feed]: + r"""Return a callable for the create feed method over gRPC. + + Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Returns: + Callable[[~.CreateFeedRequest], + ~.Feed]: + 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_feed" not in self._stubs: + self._stubs["create_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/CreateFeed", + request_serializer=asset_service.CreateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["create_feed"] + + @property + def get_feed(self) -> Callable[[asset_service.GetFeedRequest], asset_service.Feed]: + r"""Return a callable for the get feed method over gRPC. + + Gets details about an asset feed. + + Returns: + Callable[[~.GetFeedRequest], + ~.Feed]: + 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_feed" not in self._stubs: + self._stubs["get_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/GetFeed", + request_serializer=asset_service.GetFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["get_feed"] + + @property + def list_feeds( + self, + ) -> Callable[[asset_service.ListFeedsRequest], asset_service.ListFeedsResponse]: + r"""Return a callable for the list feeds method over gRPC. + + Lists all asset feeds in a parent + project/folder/organization. + + Returns: + Callable[[~.ListFeedsRequest], + ~.ListFeedsResponse]: + 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_feeds" not in self._stubs: + self._stubs["list_feeds"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/ListFeeds", + request_serializer=asset_service.ListFeedsRequest.serialize, + response_deserializer=asset_service.ListFeedsResponse.deserialize, + ) + return self._stubs["list_feeds"] + + @property + def update_feed( + self, + ) -> Callable[[asset_service.UpdateFeedRequest], asset_service.Feed]: + r"""Return a callable for the update feed method over gRPC. + + Updates an asset feed configuration. + + Returns: + Callable[[~.UpdateFeedRequest], + ~.Feed]: + 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_feed" not in self._stubs: + self._stubs["update_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/UpdateFeed", + request_serializer=asset_service.UpdateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["update_feed"] + + @property + def delete_feed(self) -> Callable[[asset_service.DeleteFeedRequest], empty.Empty]: + r"""Return a callable for the delete feed method over gRPC. + + Deletes an asset feed. + + Returns: + Callable[[~.DeleteFeedRequest], + ~.Empty]: + 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_feed" not in self._stubs: + self._stubs["delete_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed", + request_serializer=asset_service.DeleteFeedRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_feed"] + + +__all__ = ("AssetServiceGrpcTransport",) diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..7930a703 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,336 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1p2beta1.types import asset_service +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: 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: + address (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 ignored if ``channel`` 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`. + 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def create_feed( + self, + ) -> Callable[[asset_service.CreateFeedRequest], Awaitable[asset_service.Feed]]: + r"""Return a callable for the create feed method over gRPC. + + Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Returns: + Callable[[~.CreateFeedRequest], + Awaitable[~.Feed]]: + 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_feed" not in self._stubs: + self._stubs["create_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/CreateFeed", + request_serializer=asset_service.CreateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["create_feed"] + + @property + def get_feed( + self, + ) -> Callable[[asset_service.GetFeedRequest], Awaitable[asset_service.Feed]]: + r"""Return a callable for the get feed method over gRPC. + + Gets details about an asset feed. + + Returns: + Callable[[~.GetFeedRequest], + Awaitable[~.Feed]]: + 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_feed" not in self._stubs: + self._stubs["get_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/GetFeed", + request_serializer=asset_service.GetFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["get_feed"] + + @property + def list_feeds( + self, + ) -> Callable[ + [asset_service.ListFeedsRequest], Awaitable[asset_service.ListFeedsResponse] + ]: + r"""Return a callable for the list feeds method over gRPC. + + Lists all asset feeds in a parent + project/folder/organization. + + Returns: + Callable[[~.ListFeedsRequest], + Awaitable[~.ListFeedsResponse]]: + 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_feeds" not in self._stubs: + self._stubs["list_feeds"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/ListFeeds", + request_serializer=asset_service.ListFeedsRequest.serialize, + response_deserializer=asset_service.ListFeedsResponse.deserialize, + ) + return self._stubs["list_feeds"] + + @property + def update_feed( + self, + ) -> Callable[[asset_service.UpdateFeedRequest], Awaitable[asset_service.Feed]]: + r"""Return a callable for the update feed method over gRPC. + + Updates an asset feed configuration. + + Returns: + Callable[[~.UpdateFeedRequest], + Awaitable[~.Feed]]: + 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_feed" not in self._stubs: + self._stubs["update_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/UpdateFeed", + request_serializer=asset_service.UpdateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs["update_feed"] + + @property + def delete_feed( + self, + ) -> Callable[[asset_service.DeleteFeedRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete feed method over gRPC. + + Deletes an asset feed. + + Returns: + Callable[[~.DeleteFeedRequest], + Awaitable[~.Empty]]: + 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_feed" not in self._stubs: + self._stubs["delete_feed"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed", + request_serializer=asset_service.DeleteFeedRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_feed"] + + +__all__ = ("AssetServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/asset_v1p2beta1/types.py b/google/cloud/asset_v1p2beta1/types.py deleted file mode 100644 index 56de02c4..00000000 --- a/google/cloud/asset_v1p2beta1/types.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.asset_v1p2beta1.proto import asset_service_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_shared_modules = [ - empty_pb2, - field_mask_pb2, -] - -_local_modules = [ - asset_service_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.asset_v1p2beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/asset_v1p2beta1/types/__init__.py b/google/cloud/asset_v1p2beta1/types/__init__.py new file mode 100644 index 00000000..43e90db3 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/types/__init__.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .assets import ( + TemporalAsset, + TimeWindow, + Asset, + Resource, +) +from .asset_service import ( + CreateFeedRequest, + GetFeedRequest, + ListFeedsRequest, + ListFeedsResponse, + UpdateFeedRequest, + DeleteFeedRequest, + OutputConfig, + GcsDestination, + PubsubDestination, + FeedOutputConfig, + Feed, +) + + +__all__ = ( + "TemporalAsset", + "TimeWindow", + "Asset", + "Resource", + "CreateFeedRequest", + "GetFeedRequest", + "ListFeedsRequest", + "ListFeedsResponse", + "UpdateFeedRequest", + "DeleteFeedRequest", + "OutputConfig", + "GcsDestination", + "PubsubDestination", + "FeedOutputConfig", + "Feed", +) diff --git a/google/cloud/asset_v1p2beta1/types/asset_service.py b/google/cloud/asset_v1p2beta1/types/asset_service.py new file mode 100644 index 00000000..bd64a00a --- /dev/null +++ b/google/cloud/asset_v1p2beta1/types/asset_service.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1p2beta1", + manifest={ + "ContentType", + "CreateFeedRequest", + "GetFeedRequest", + "ListFeedsRequest", + "ListFeedsResponse", + "UpdateFeedRequest", + "DeleteFeedRequest", + "OutputConfig", + "GcsDestination", + "PubsubDestination", + "FeedOutputConfig", + "Feed", + }, +) + + +class ContentType(proto.Enum): + r"""Asset content type.""" + CONTENT_TYPE_UNSPECIFIED = 0 + RESOURCE = 1 + IAM_POLICY = 2 + + +class CreateFeedRequest(proto.Message): + r"""Create asset feed request. + + Attributes: + parent (str): + Required. The name of the + project/folder/organization where this feed + should be created in. It can only be an + organization number (such as + "organizations/123"), a folder number (such as + "folders/123"), a project ID (such as + "projects/my-project-id")", or a project number + (such as "projects/12345"). + feed_id (str): + Required. This is the client-assigned asset + feed identifier and it needs to be unique under + a specific parent project/folder/organization. + feed (~.asset_service.Feed): + Required. The feed details. The field ``name`` must be empty + and it will be generated in the format of: + projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + parent = proto.Field(proto.STRING, number=1) + + feed_id = proto.Field(proto.STRING, number=2) + + feed = proto.Field(proto.MESSAGE, number=3, message="Feed",) + + +class GetFeedRequest(proto.Message): + r"""Get asset feed request. + + Attributes: + name (str): + Required. The name of the Feed and it must be in the format + of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + name = proto.Field(proto.STRING, number=1) + + +class ListFeedsRequest(proto.Message): + r"""List asset feeds request. + + Attributes: + parent (str): + Required. The parent + project/folder/organization whose feeds are to + be listed. It can only be using + project/folder/organization number (such as + "folders/12345")", or a project ID (such as + "projects/my-project-id"). + """ + + parent = proto.Field(proto.STRING, number=1) + + +class ListFeedsResponse(proto.Message): + r""" + + Attributes: + feeds (Sequence[~.asset_service.Feed]): + A list of feeds. + """ + + feeds = proto.RepeatedField(proto.MESSAGE, number=1, message="Feed",) + + +class UpdateFeedRequest(proto.Message): + r"""Update asset feed request. + + Attributes: + feed (~.asset_service.Feed): + Required. The new values of feed details. It must match an + existing feed and the field ``name`` must be in the format + of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + update_mask (~.field_mask.FieldMask): + Required. Only updates the ``feed`` fields indicated by this + mask. The field mask must not be empty, and it must not + contain fields that are immutable or only set by the server. + """ + + feed = proto.Field(proto.MESSAGE, number=1, message="Feed",) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteFeedRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the feed and it must be in the format + of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + name = proto.Field(proto.STRING, number=1) + + +class OutputConfig(proto.Message): + r"""Output configuration for export assets destination. + + Attributes: + gcs_destination (~.asset_service.GcsDestination): + Destination on Cloud Storage. + """ + + gcs_destination = proto.Field( + proto.MESSAGE, number=1, oneof="destination", message="GcsDestination", + ) + + +class GcsDestination(proto.Message): + r"""A Cloud Storage location. + + Attributes: + uri (str): + The uri of the Cloud Storage object. It's the same uri that + is used by gsutil. For example: + "gs://bucket_name/object_name". See `Viewing and Editing + Object + Metadata `__ + for more information. + """ + + uri = proto.Field(proto.STRING, number=1, oneof="object_uri") + + +class PubsubDestination(proto.Message): + r"""A Cloud Pubsub destination. + + Attributes: + topic (str): + The name of the Cloud Pub/Sub topic to publish to. For + example: ``projects/PROJECT_ID/topics/TOPIC_ID``. + """ + + topic = proto.Field(proto.STRING, number=1) + + +class FeedOutputConfig(proto.Message): + r"""Output configuration for asset feed destination. + + Attributes: + pubsub_destination (~.asset_service.PubsubDestination): + Destination on Cloud Pubsub. + """ + + pubsub_destination = proto.Field( + proto.MESSAGE, number=1, oneof="destination", message=PubsubDestination, + ) + + +class Feed(proto.Message): + r"""An asset feed used to export asset updates to a destinations. + An asset feed filter controls what updates are exported. The + asset feed must be created within a project, organization, or + folder. Supported destinations are: + Cloud Pub/Sub topics. + + Attributes: + name (str): + Required. The format will be + projects/{project_number}/feeds/{client-assigned_feed_identifier} + or + folders/{folder_number}/feeds/{client-assigned_feed_identifier} + or + organizations/{organization_number}/feeds/{client-assigned_feed_identifier} + + The client-assigned feed identifier must be unique within + the parent project/folder/organization. + asset_names (Sequence[str]): + A list of the full names of the assets to receive updates. + You must specify either or both of asset_names and + asset_types. Only asset updates matching specified + asset_names and asset_types are exported to the feed. For + example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more info. + asset_types (Sequence[str]): + A list of types of the assets to receive updates. You must + specify either or both of asset_names and asset_types. Only + asset updates matching specified asset_names and asset_types + are exported to the feed. For example: + "compute.googleapis.com/Disk" See `Introduction to Cloud + Asset + Inventory `__ + for all supported asset types. + content_type (~.asset_service.ContentType): + Asset content type. If not specified, no + content but the asset name and type will be + returned. + feed_output_config (~.asset_service.FeedOutputConfig): + Required. Feed output configuration defining + where the asset updates are published to. + """ + + name = proto.Field(proto.STRING, number=1) + + asset_names = proto.RepeatedField(proto.STRING, number=2) + + asset_types = proto.RepeatedField(proto.STRING, number=3) + + content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) + + feed_output_config = proto.Field(proto.MESSAGE, number=5, message=FeedOutputConfig,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p2beta1/types/assets.py b/google/cloud/asset_v1p2beta1/types/assets.py new file mode 100644 index 00000000..84f260f3 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/types/assets.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1p2beta1", + manifest={"TemporalAsset", "TimeWindow", "Asset", "Resource",}, +) + + +class TemporalAsset(proto.Message): + r"""Temporal asset. In addition to the asset, the temporal asset + includes the status of the asset and valid from and to time of + it. + + Attributes: + window (~.assets.TimeWindow): + The time window when the asset data and state + was observed. + deleted (bool): + If the asset is deleted or not. + asset (~.assets.Asset): + Asset. + """ + + window = proto.Field(proto.MESSAGE, number=1, message="TimeWindow",) + + deleted = proto.Field(proto.BOOL, number=2) + + asset = proto.Field(proto.MESSAGE, number=3, message="Asset",) + + +class TimeWindow(proto.Message): + r"""A time window of (start_time, end_time]. + + Attributes: + start_time (~.timestamp.Timestamp): + Start time of the time window (exclusive). + end_time (~.timestamp.Timestamp): + End time of the time window (inclusive). + Current timestamp if not specified. + """ + + start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + +class Asset(proto.Message): + r"""Cloud asset. This includes all Google Cloud Platform + resources, Cloud IAM policies, and other non-GCP assets. + + Attributes: + name (str): + The full name of the asset. For example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more information. + asset_type (str): + Type of the asset. Example: + "compute.googleapis.com/Disk". + resource (~.assets.Resource): + Representation of the resource. + iam_policy (~.policy.Policy): + Representation of the actual Cloud IAM policy + set on a cloud resource. For each resource, + there must be at most one Cloud IAM policy set + on it. + ancestors (Sequence[str]): + Asset's ancestry path in Cloud Resource Manager (CRM) + hierarchy, represented as a list of relative resource names. + Ancestry path starts with the closest CRM ancestor and ends + at root. If the asset is a CRM project/folder/organization, + this starts from the asset itself. + + Example: ["projects/123456789", "folders/5432", + "organizations/1234"] + """ + + name = proto.Field(proto.STRING, number=1) + + asset_type = proto.Field(proto.STRING, number=2) + + resource = proto.Field(proto.MESSAGE, number=3, message="Resource",) + + iam_policy = proto.Field(proto.MESSAGE, number=4, message=policy.Policy,) + + ancestors = proto.RepeatedField(proto.STRING, number=6) + + +class Resource(proto.Message): + r"""Representation of a cloud resource. + + Attributes: + version (str): + The API version. Example: "v1". + discovery_document_uri (str): + The URL of the discovery document containing the resource's + JSON schema. For example: + ``"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"``. + It will be left unspecified for resources without a + discovery-based API, such as Cloud Bigtable. + discovery_name (str): + The JSON schema name listed in the discovery + document. Example: "Project". It will be left + unspecified for resources (such as Cloud + Bigtable) without a discovery-based API. + resource_url (str): + The REST URL for accessing the resource. An HTTP GET + operation using this URL returns the resource itself. + Example: + ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123``. + It will be left unspecified for resources without a REST + API. + parent (str): + The full name of the immediate parent of this resource. See + `Resource + Names `__ + for more information. + + For GCP assets, it is the parent resource defined in the + `Cloud IAM policy + hierarchy `__. + For example: + ``"//cloudresourcemanager.googleapis.com/projects/my_project_123"``. + + For third-party assets, it is up to the users to define. + data (~.struct.Struct): + The content of the resource, in which some + sensitive fields are scrubbed away and may not + be present. + """ + + version = proto.Field(proto.STRING, number=1) + + discovery_document_uri = proto.Field(proto.STRING, number=2) + + discovery_name = proto.Field(proto.STRING, number=3) + + resource_url = proto.Field(proto.STRING, number=4) + + parent = proto.Field(proto.STRING, number=5) + + data = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p4beta1/__init__.py b/google/cloud/asset_v1p4beta1/__init__.py index 61850095..108a29dc 100644 --- a/google/cloud/asset_v1p4beta1/__init__.py +++ b/google/cloud/asset_v1p4beta1/__init__.py @@ -1,45 +1,37 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.asset_v1p4beta1 import types -from google.cloud.asset_v1p4beta1.gapic import asset_service_client -from google.cloud.asset_v1p4beta1.gapic import enums - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class AssetServiceClient(asset_service_client.AssetServiceClient): - __doc__ = asset_service_client.AssetServiceClient.__doc__ - enums = enums +from .services.asset_service import AssetServiceClient +from .types.asset_service import AnalyzeIamPolicyRequest +from .types.asset_service import AnalyzeIamPolicyResponse +from .types.asset_service import ExportIamPolicyAnalysisRequest +from .types.asset_service import ExportIamPolicyAnalysisResponse +from .types.asset_service import IamPolicyAnalysisOutputConfig +from .types.asset_service import IamPolicyAnalysisQuery +from .types.assets import IamPolicyAnalysisResult __all__ = ( - "enums", - "types", + "AnalyzeIamPolicyRequest", + "AnalyzeIamPolicyResponse", + "ExportIamPolicyAnalysisRequest", + "ExportIamPolicyAnalysisResponse", + "IamPolicyAnalysisOutputConfig", + "IamPolicyAnalysisQuery", + "IamPolicyAnalysisResult", "AssetServiceClient", ) diff --git a/google/cloud/asset_v1p4beta1/gapic/__init__.py b/google/cloud/asset_v1p4beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p4beta1/gapic/asset_service_client.py b/google/cloud/asset_v1p4beta1/gapic/asset_service_client.py deleted file mode 100644 index 193ecf6c..00000000 --- a/google/cloud/asset_v1p4beta1/gapic/asset_service_client.py +++ /dev/null @@ -1,374 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Accesses the google.cloud.asset.v1p4beta1 AssetService API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -import google.api_core.operations_v1 -import grpc - -from google.cloud.asset_v1p4beta1.gapic import asset_service_client_config -from google.cloud.asset_v1p4beta1.gapic import enums -from google.cloud.asset_v1p4beta1.gapic.transports import asset_service_grpc_transport -from google.cloud.asset_v1p4beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p4beta1.proto import asset_service_pb2_grpc -from google.longrunning import operations_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-asset",).version - - -class AssetServiceClient(object): - """Asset service definition.""" - - SERVICE_ADDRESS = "cloudasset.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.asset.v1p4beta1.AssetService" - - @classmethod - def from_service_account_file(cls, filename, *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: - AssetServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.AssetServiceGrpcTransport, - Callable[[~.Credentials, type], ~.AssetServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = asset_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=asset_service_grpc_transport.AssetServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = asset_service_grpc_transport.AssetServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def export_iam_policy_analysis( - self, - analysis_query, - output_config, - options_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Exports IAM policy analysis based on the specified request. This API - implements the ``google.longrunning.Operation`` API allowing you to keep - track of the export. The metadata contains the request to help callers - to map responses to requests. - - Example: - >>> from google.cloud import asset_v1p4beta1 - >>> - >>> client = asset_v1p4beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `analysis_query`: - >>> analysis_query = {} - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.export_iam_policy_analysis(analysis_query, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - analysis_query (Union[dict, ~google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery]): Required. The request query. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery` - output_config (Union[dict, ~google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisOutputConfig]): Required. Output configuration indicating where the results will be output to. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisOutputConfig` - options_ (Union[dict, ~google.cloud.asset_v1p4beta1.types.Options]): Optional. The request options. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p4beta1.types.Options` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1p4beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "export_iam_policy_analysis" not in self._inner_api_calls: - self._inner_api_calls[ - "export_iam_policy_analysis" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.export_iam_policy_analysis, - default_retry=self._method_configs["ExportIamPolicyAnalysis"].retry, - default_timeout=self._method_configs["ExportIamPolicyAnalysis"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.ExportIamPolicyAnalysisRequest( - analysis_query=analysis_query, - output_config=output_config, - options=options_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("analysis_query.parent", analysis_query.parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["export_iam_policy_analysis"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - asset_service_pb2.ExportIamPolicyAnalysisResponse, - metadata_type=asset_service_pb2.ExportIamPolicyAnalysisRequest, - ) - - def analyze_iam_policy( - self, - analysis_query, - options_=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Analyzes IAM policies based on the specified request. Returns a list - of ``IamPolicyAnalysisResult`` matching the request. - - Example: - >>> from google.cloud import asset_v1p4beta1 - >>> - >>> client = asset_v1p4beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `analysis_query`: - >>> analysis_query = {} - >>> - >>> response = client.analyze_iam_policy(analysis_query) - - Args: - analysis_query (Union[dict, ~google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery]): Required. The request query. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery` - options_ (Union[dict, ~google.cloud.asset_v1p4beta1.types.Options]): Optional. The request options. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p4beta1.types.Options` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "analyze_iam_policy" not in self._inner_api_calls: - self._inner_api_calls[ - "analyze_iam_policy" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.analyze_iam_policy, - default_retry=self._method_configs["AnalyzeIamPolicy"].retry, - default_timeout=self._method_configs["AnalyzeIamPolicy"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.AnalyzeIamPolicyRequest( - analysis_query=analysis_query, options=options_, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("analysis_query.parent", analysis_query.parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["analyze_iam_policy"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/asset_v1p4beta1/gapic/asset_service_client_config.py b/google/cloud/asset_v1p4beta1/gapic/asset_service_client_config.py deleted file mode 100644 index f161977e..00000000 --- a/google/cloud/asset_v1p4beta1/gapic/asset_service_client_config.py +++ /dev/null @@ -1,52 +0,0 @@ -config = { - "interfaces": { - "google.cloud.asset.v1p4beta1.AssetService": { - "retry_codes": { - "retry_policy_1_codes": ["UNAVAILABLE"], - "no_retry_codes": [], - "no_retry_1_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 300000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 300000, - "total_timeout_millis": 300000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - }, - "methods": { - "ExportIamPolicyAnalysis": { - "timeout_millis": 600000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "AnalyzeIamPolicy": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/asset_v1p4beta1/gapic/enums.py b/google/cloud/asset_v1p4beta1/gapic/enums.py deleted file mode 100644 index 8bf76999..00000000 --- a/google/cloud/asset_v1p4beta1/gapic/enums.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class Code(enum.IntEnum): - """ - The canonical error codes for gRPC APIs. - - Sometimes multiple error codes may apply. Services should return the - most specific error code that applies. For example, prefer - ``OUT_OF_RANGE`` over ``FAILED_PRECONDITION`` if both codes apply. - Similarly prefer ``NOT_FOUND`` or ``ALREADY_EXISTS`` over - ``FAILED_PRECONDITION``. - - Attributes: - OK (int): Not an error; returned on success - - HTTP Mapping: 200 OK - CANCELLED (int): The operation was cancelled, typically by the caller. - - HTTP Mapping: 499 Client Closed Request - UNKNOWN (int): Unknown error. For example, this error may be returned when a - ``Status`` value received from another address space belongs to an error - space that is not known in this address space. Also errors raised by - APIs that do not return enough error information may be converted to - this error. - - HTTP Mapping: 500 Internal Server Error - INVALID_ARGUMENT (int): The client specified an invalid argument. Note that this differs - from ``FAILED_PRECONDITION``. ``INVALID_ARGUMENT`` indicates arguments - that are problematic regardless of the state of the system (e.g., a - malformed file name). - - HTTP Mapping: 400 Bad Request - DEADLINE_EXCEEDED (int): The deadline expired before the operation could complete. For operations - that change the state of the system, this error may be returned - even if the operation has completed successfully. For example, a - successful response from a server could have been delayed long - enough for the deadline to expire. - - HTTP Mapping: 504 Gateway Timeout - NOT_FOUND (int): Some requested entity (e.g., file or directory) was not found. - - Note to server developers: if a request is denied for an entire class of - users, such as gradual feature rollout or undocumented whitelist, - ``NOT_FOUND`` may be used. If a request is denied for some users within - a class of users, such as user-based access control, - ``PERMISSION_DENIED`` must be used. - - HTTP Mapping: 404 Not Found - ALREADY_EXISTS (int): The entity that a client attempted to create (e.g., file or directory) - already exists. - - HTTP Mapping: 409 Conflict - PERMISSION_DENIED (int): The caller does not have permission to execute the specified - operation. ``PERMISSION_DENIED`` must not be used for rejections caused - by exhausting some resource (use ``RESOURCE_EXHAUSTED`` instead for - those errors). ``PERMISSION_DENIED`` must not be used if the caller can - not be identified (use ``UNAUTHENTICATED`` instead for those errors). - This error code does not imply the request is valid or the requested - entity exists or satisfies other pre-conditions. - - HTTP Mapping: 403 Forbidden - UNAUTHENTICATED (int): The request does not have valid authentication credentials for the - operation. - - HTTP Mapping: 401 Unauthorized - RESOURCE_EXHAUSTED (int): Some resource has been exhausted, perhaps a per-user quota, or - perhaps the entire file system is out of space. - - HTTP Mapping: 429 Too Many Requests - FAILED_PRECONDITION (int): The operation was rejected because the system is not in a state - required for the operation's execution. For example, the directory to be - deleted is non-empty, an rmdir operation is applied to a non-directory, - etc. - - Service implementors can use the following guidelines to decide between - ``FAILED_PRECONDITION``, ``ABORTED``, and ``UNAVAILABLE``: (a) Use - ``UNAVAILABLE`` if the client can retry just the failing call. (b) Use - ``ABORTED`` if the client should retry at a higher level (e.g., when a - client-specified test-and-set fails, indicating the client should - restart a read-modify-write sequence). (c) Use ``FAILED_PRECONDITION`` - if the client should not retry until the system state has been - explicitly fixed. E.g., if an "rmdir" fails because the directory is - non-empty, ``FAILED_PRECONDITION`` should be returned since the client - should not retry unless the files are deleted from the directory. - - HTTP Mapping: 400 Bad Request - ABORTED (int): The operation was aborted, typically due to a concurrency issue such - as a sequencer check failure or transaction abort. - - See the guidelines above for deciding between ``FAILED_PRECONDITION``, - ``ABORTED``, and ``UNAVAILABLE``. - - HTTP Mapping: 409 Conflict - OUT_OF_RANGE (int): The operation was attempted past the valid range. E.g., seeking or - reading past end-of-file. - - Unlike ``INVALID_ARGUMENT``, this error indicates a problem that may be - fixed if the system state changes. For example, a 32-bit file system - will generate ``INVALID_ARGUMENT`` if asked to read at an offset that is - not in the range [0,2^32-1], but it will generate ``OUT_OF_RANGE`` if - asked to read from an offset past the current file size. - - There is a fair bit of overlap between ``FAILED_PRECONDITION`` and - ``OUT_OF_RANGE``. We recommend using ``OUT_OF_RANGE`` (the more specific - error) when it applies so that callers who are iterating through a space - can easily look for an ``OUT_OF_RANGE`` error to detect when they are - done. - - HTTP Mapping: 400 Bad Request - UNIMPLEMENTED (int): The operation is not implemented or is not supported/enabled in this - service. - - HTTP Mapping: 501 Not Implemented - INTERNAL (int): Internal errors. This means that some invariants expected by the - underlying system have been broken. This error code is reserved - for serious errors. - - HTTP Mapping: 500 Internal Server Error - UNAVAILABLE (int): The service is currently unavailable. This is most likely a - transient condition, which can be corrected by retrying with a backoff. - Note that it is not always safe to retry non-idempotent operations. - - See the guidelines above for deciding between ``FAILED_PRECONDITION``, - ``ABORTED``, and ``UNAVAILABLE``. - - HTTP Mapping: 503 Service Unavailable - DATA_LOSS (int): Unrecoverable data loss or corruption. - - HTTP Mapping: 500 Internal Server Error - """ - - OK = 0 - CANCELLED = 1 - UNKNOWN = 2 - INVALID_ARGUMENT = 3 - DEADLINE_EXCEEDED = 4 - NOT_FOUND = 5 - ALREADY_EXISTS = 6 - PERMISSION_DENIED = 7 - UNAUTHENTICATED = 16 - RESOURCE_EXHAUSTED = 8 - FAILED_PRECONDITION = 9 - ABORTED = 10 - OUT_OF_RANGE = 11 - UNIMPLEMENTED = 12 - INTERNAL = 13 - UNAVAILABLE = 14 - DATA_LOSS = 15 diff --git a/google/cloud/asset_v1p4beta1/gapic/transports/__init__.py b/google/cloud/asset_v1p4beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p4beta1/gapic/transports/asset_service_grpc_transport.py b/google/cloud/asset_v1p4beta1/gapic/transports/asset_service_grpc_transport.py deleted file mode 100644 index ea8df7ca..00000000 --- a/google/cloud/asset_v1p4beta1/gapic/transports/asset_service_grpc_transport.py +++ /dev/null @@ -1,146 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 google.api_core.grpc_helpers -import google.api_core.operations_v1 - -from google.cloud.asset_v1p4beta1.proto import asset_service_pb2_grpc - - -class AssetServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.asset.v1p4beta1 AssetService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="cloudasset.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "asset_service_stub": asset_service_pb2_grpc.AssetServiceStub(channel), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="cloudasset.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def export_iam_policy_analysis(self): - """Return the gRPC stub for :meth:`AssetServiceClient.export_iam_policy_analysis`. - - Exports IAM policy analysis based on the specified request. This API - implements the ``google.longrunning.Operation`` API allowing you to keep - track of the export. The metadata contains the request to help callers - to map responses to requests. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].ExportIamPolicyAnalysis - - @property - def analyze_iam_policy(self): - """Return the gRPC stub for :meth:`AssetServiceClient.analyze_iam_policy`. - - Analyzes IAM policies based on the specified request. Returns a list - of ``IamPolicyAnalysisResult`` matching the request. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].AnalyzeIamPolicy diff --git a/google/cloud/asset_v1p4beta1/proto/__init__.py b/google/cloud/asset_v1p4beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p4beta1/proto/asset_service_pb2.py b/google/cloud/asset_v1p4beta1/proto/asset_service_pb2.py deleted file mode 100644 index 487cc4b6..00000000 --- a/google/cloud/asset_v1p4beta1/proto/asset_service_pb2.py +++ /dev/null @@ -1,1584 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1p4beta1/proto/asset_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.cloud.asset_v1p4beta1.proto import ( - assets_pb2 as google_dot_cloud_dot_asset__v1p4beta1_dot_proto_dot_assets__pb2, -) -from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1p4beta1/proto/asset_service.proto", - package="google.cloud.asset.v1p4beta1", - syntax="proto3", - serialized_options=b"\n com.google.cloud.asset.v1p4beta1B\021AssetServiceProtoP\001ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p4beta1;asset\252\002\034Google.Cloud.Asset.V1P4Beta1\312\002\034Google\\Cloud\\Asset\\V1p4beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n6google/cloud/asset_v1p4beta1/proto/asset_service.proto\x12\x1cgoogle.cloud.asset.v1p4beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a/google/cloud/asset_v1p4beta1/proto/assets.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a#google/longrunning/operations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x17google/api/client.proto"\xfe\x03\n\x16IamPolicyAnalysisQuery\x12\x13\n\x06parent\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x65\n\x11resource_selector\x18\x02 \x01(\x0b\x32\x45.google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.ResourceSelectorB\x03\xe0\x41\x01\x12\x65\n\x11identity_selector\x18\x03 \x01(\x0b\x32\x45.google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.IdentitySelectorB\x03\xe0\x41\x01\x12\x61\n\x0f\x61\x63\x63\x65ss_selector\x18\x04 \x01(\x0b\x32\x43.google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.AccessSelectorB\x03\xe0\x41\x01\x1a\x33\n\x10ResourceSelector\x12\x1f\n\x12\x66ull_resource_name\x18\x01 \x01(\tB\x03\xe0\x41\x02\x1a)\n\x10IdentitySelector\x12\x15\n\x08identity\x18\x01 \x01(\tB\x03\xe0\x41\x02\x1a>\n\x0e\x41\x63\x63\x65ssSelector\x12\x12\n\x05roles\x18\x01 \x03(\tB\x03\xe0\x41\x01\x12\x18\n\x0bpermissions\x18\x02 \x03(\tB\x03\xe0\x41\x01"\xd7\x03\n\x17\x41nalyzeIamPolicyRequest\x12Q\n\x0e\x61nalysis_query\x18\x01 \x01(\x0b\x32\x34.google.cloud.asset.v1p4beta1.IamPolicyAnalysisQueryB\x03\xe0\x41\x02\x12S\n\x07options\x18\x02 \x01(\x0b\x32=.google.cloud.asset.v1p4beta1.AnalyzeIamPolicyRequest.OptionsB\x03\xe0\x41\x01\x1a\x93\x02\n\x07Options\x12\x1a\n\rexpand_groups\x18\x01 \x01(\x08\x42\x03\xe0\x41\x01\x12\x19\n\x0c\x65xpand_roles\x18\x02 \x01(\x08\x42\x03\xe0\x41\x01\x12\x1d\n\x10\x65xpand_resources\x18\x03 \x01(\x08\x42\x03\xe0\x41\x01\x12"\n\x15output_resource_edges\x18\x04 \x01(\x08\x42\x03\xe0\x41\x01\x12\x1f\n\x12output_group_edges\x18\x05 \x01(\x08\x42\x03\xe0\x41\x01\x12\x32\n%analyze_service_account_impersonation\x18\x06 \x01(\x08\x42\x03\xe0\x41\x01\x12\x39\n\x11\x65xecution_timeout\x18\x07 \x01(\x0b\x32\x19.google.protobuf.DurationB\x03\xe0\x41\x01"\xbc\x04\n\x18\x41nalyzeIamPolicyResponse\x12_\n\rmain_analysis\x18\x01 \x01(\x0b\x32H.google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.IamPolicyAnalysis\x12x\n&service_account_impersonation_analysis\x18\x02 \x03(\x0b\x32H.google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.IamPolicyAnalysis\x12\x16\n\x0e\x66ully_explored\x18\x03 \x01(\x08\x12`\n\x13non_critical_errors\x18\x04 \x03(\x0b\x32\x43.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AnalysisState\x1a\xca\x01\n\x11IamPolicyAnalysis\x12L\n\x0e\x61nalysis_query\x18\x01 \x01(\x0b\x32\x34.google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery\x12O\n\x10\x61nalysis_results\x18\x02 \x03(\x0b\x32\x35.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult\x12\x16\n\x0e\x66ully_explored\x18\x03 \x01(\x08"\xb9\x01\n\x1dIamPolicyAnalysisOutputConfig\x12\x65\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32J.google.cloud.asset.v1p4beta1.IamPolicyAnalysisOutputConfig.GcsDestinationH\x00\x1a"\n\x0eGcsDestination\x12\x10\n\x03uri\x18\x01 \x01(\tB\x03\xe0\x41\x02\x42\r\n\x0b\x64\x65stination"\x83\x04\n\x1e\x45xportIamPolicyAnalysisRequest\x12Q\n\x0e\x61nalysis_query\x18\x01 \x01(\x0b\x32\x34.google.cloud.asset.v1p4beta1.IamPolicyAnalysisQueryB\x03\xe0\x41\x02\x12Z\n\x07options\x18\x02 \x01(\x0b\x32\x44.google.cloud.asset.v1p4beta1.ExportIamPolicyAnalysisRequest.OptionsB\x03\xe0\x41\x01\x12W\n\routput_config\x18\x03 \x01(\x0b\x32;.google.cloud.asset.v1p4beta1.IamPolicyAnalysisOutputConfigB\x03\xe0\x41\x02\x1a\xd8\x01\n\x07Options\x12\x1a\n\rexpand_groups\x18\x01 \x01(\x08\x42\x03\xe0\x41\x01\x12\x19\n\x0c\x65xpand_roles\x18\x02 \x01(\x08\x42\x03\xe0\x41\x01\x12\x1d\n\x10\x65xpand_resources\x18\x03 \x01(\x08\x42\x03\xe0\x41\x01\x12"\n\x15output_resource_edges\x18\x04 \x01(\x08\x42\x03\xe0\x41\x01\x12\x1f\n\x12output_group_edges\x18\x05 \x01(\x08\x42\x03\xe0\x41\x01\x12\x32\n%analyze_service_account_impersonation\x18\x06 \x01(\x08\x42\x03\xe0\x41\x01"u\n\x1f\x45xportIamPolicyAnalysisResponse\x12R\n\routput_config\x18\x01 \x01(\x0b\x32;.google.cloud.asset.v1p4beta1.IamPolicyAnalysisOutputConfig2\xe5\x04\n\x0c\x41ssetService\x12\xc2\x01\n\x10\x41nalyzeIamPolicy\x12\x35.google.cloud.asset.v1p4beta1.AnalyzeIamPolicyRequest\x1a\x36.google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse"?\x82\xd3\xe4\x93\x02\x39\x12\x37/v1p4beta1/{analysis_query.parent=*/*}:analyzeIamPolicy\x12\xc0\x02\n\x17\x45xportIamPolicyAnalysis\x12<.google.cloud.asset.v1p4beta1.ExportIamPolicyAnalysisRequest\x1a\x1d.google.longrunning.Operation"\xc7\x01\x82\xd3\xe4\x93\x02\x43">/v1p4beta1/{analysis_query.parent=*/*}:exportIamPolicyAnalysis:\x01*\xca\x41{\n`__ . - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.ResourceSelector) - }, - ), - "IdentitySelector": _reflection.GeneratedProtocolMessageType( - "IdentitySelector", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISQUERY_IDENTITYSELECTOR, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """Specifies an identity for which to determine resource access, based on - roles assigned either directly to them or to the groups they belong - to, directly or indirectly. - - Attributes: - identity: - Required. The identity appear in the form of members in `IAM - policy binding - `__. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.IdentitySelector) - }, - ), - "AccessSelector": _reflection.GeneratedProtocolMessageType( - "AccessSelector", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISQUERY_ACCESSSELECTOR, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """Specifies roles and/or permissions to analyze, to determine both the - identities possessing them and the resources they control. If multiple - values are specified, results will include identities and resources - matching any of them. - - Attributes: - roles: - Optional. The roles to appear in result. - permissions: - Optional. The permissions to appear in result. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.AccessSelector) - }, - ), - "DESCRIPTOR": _IAMPOLICYANALYSISQUERY, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """IAM policy analysis query message. - - Attributes: - parent: - Required. The relative name of the root asset. Only resources - and IAM policies within the parent will be analyzed. This can - only be an organization number (such as “organizations/123”) - or a folder number (such as “folders/123”). - resource_selector: - Optional. Specifies a resource for analysis. Leaving it empty - means ANY. - identity_selector: - Optional. Specifies an identity for analysis. Leaving it empty - means ANY. - access_selector: - Optional. Specifies roles or permissions for analysis. Leaving - it empty means ANY. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery) - }, -) -_sym_db.RegisterMessage(IamPolicyAnalysisQuery) -_sym_db.RegisterMessage(IamPolicyAnalysisQuery.ResourceSelector) -_sym_db.RegisterMessage(IamPolicyAnalysisQuery.IdentitySelector) -_sym_db.RegisterMessage(IamPolicyAnalysisQuery.AccessSelector) - -AnalyzeIamPolicyRequest = _reflection.GeneratedProtocolMessageType( - "AnalyzeIamPolicyRequest", - (_message.Message,), - { - "Options": _reflection.GeneratedProtocolMessageType( - "Options", - (_message.Message,), - { - "DESCRIPTOR": _ANALYZEIAMPOLICYREQUEST_OPTIONS, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """Contains request options. - - Attributes: - expand_groups: - Optional. If true, the identities section of the result will - expand any Google groups appearing in an IAM policy binding. - If [identity_selector][] is specified, the identity in the - result will be determined by the selector, and this flag will - have no effect. Default is false. - expand_roles: - Optional. If true, the access section of result will expand - any roles appearing in IAM policy bindings to include their - permissions. If [access_selector][] is specified, the access - section of the result will be determined by the selector, and - this flag will have no effect. Default is false. - expand_resources: - Optional. If true, the resource section of the result will - expand any resource attached to an IAM policy to include - resources lower in the resource hierarchy. For example, if - the request analyzes for which resources user A has permission - P, and the results include an IAM policy with P on a GCP - folder, the results will also include resources in that folder - with permission P. If [resource_selector][] is specified, the - resource section of the result will be determined by the - selector, and this flag will have no effect. Default is false. - output_resource_edges: - Optional. If true, the result will output resource edges, - starting from the policy attached resource, to any expanded - resources. Default is false. - output_group_edges: - Optional. If true, the result will output group identity - edges, starting from the binding’s group members, to any - expanded identities. Default is false. - analyze_service_account_impersonation: - Optional. If true, the response will include access analysis - from identities to resources via service account - impersonation. This is a very expensive operation, because - many derived queries will be executed. We highly recommend you - use ExportIamPolicyAnalysis rpc instead. For example, if the - request analyzes for which resources user A has permission P, - and there’s an IAM policy states user A has - iam.serviceAccounts.getAccessToken permission to a service - account SA, and there’s another IAM policy states service - account SA has permission P to a GCP folder F, then user A - potentially has access to the GCP folder F. And those advanced - analysis results will be included in [AnalyzeIamPolicyResponse - .service_account_impersonation_analysis][google.cloud.asset.v1 - p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation - _analysis]. Another example, if the request analyzes for who - has permission P to a GCP folder F, and there’s an IAM policy - states user A has iam.serviceAccounts.actAs permission to a - service account SA, and there’s another IAM policy states - service account SA has permission P to the GCP folder F, then - user A potentially has access to the GCP folder F. And those - advanced analysis results will be included in [AnalyzeIamPolic - yResponse.service_account_impersonation_analysis][google.cloud - .asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impe - rsonation_analysis]. Default is false. - execution_timeout: - Optional. Amount of time executable has to complete. See JSON - representation of `Duration - `__. If this field is set with a - value less than the RPC deadline, and the execution of your - query hasn’t finished in the specified execution timeout, you - will get a response with partial result. Otherwise, your - query’s execution will continue until the RPC deadline. If - it’s not finished until then, you will get a DEADLINE_EXCEEDED - error. Default is empty. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.AnalyzeIamPolicyRequest.Options) - }, - ), - "DESCRIPTOR": _ANALYZEIAMPOLICYREQUEST, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """A request message for [AssetService.AnalyzeIamPolicy][google.cloud.ass - et.v1p4beta1.AssetService.AnalyzeIamPolicy]. - - Attributes: - analysis_query: - Required. The request query. - options: - Optional. The request options. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.AnalyzeIamPolicyRequest) - }, -) -_sym_db.RegisterMessage(AnalyzeIamPolicyRequest) -_sym_db.RegisterMessage(AnalyzeIamPolicyRequest.Options) - -AnalyzeIamPolicyResponse = _reflection.GeneratedProtocolMessageType( - "AnalyzeIamPolicyResponse", - (_message.Message,), - { - "IamPolicyAnalysis": _reflection.GeneratedProtocolMessageType( - "IamPolicyAnalysis", - (_message.Message,), - { - "DESCRIPTOR": _ANALYZEIAMPOLICYRESPONSE_IAMPOLICYANALYSIS, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """An analysis message to group the query and results. - - Attributes: - analysis_query: - The analysis query. - analysis_results: - A list of [IamPolicyAnalysisResult][google.cloud.asset.v1p4bet - a1.IamPolicyAnalysisResult] that matches the analysis query, - or empty if no result is found. - fully_explored: - Represents whether all entries in the [analysis_results][googl - e.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.IamPolicyAnal - ysis.analysis_results] have been fully explored to answer the - query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.IamPolicyAnalysis) - }, - ), - "DESCRIPTOR": _ANALYZEIAMPOLICYRESPONSE, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """A response message for [AssetService.AnalyzeIamPolicy][google.cloud.as - set.v1p4beta1.AssetService.AnalyzeIamPolicy]. - - Attributes: - main_analysis: - The main analysis that matches the original request. - service_account_impersonation_analysis: - The service account impersonation analysis if [AnalyzeIamPolic - yRequest.analyze_service_account_impersonation][] is enabled. - fully_explored: - Represents whether all entries in the [main_analysis][google.c - loud.asset.v1p4beta1.AnalyzeIamPolicyResponse.main_analysis] - and [service_account_impersonation_analysis][google.cloud.asse - t.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersona - tion_analysis] have been fully explored to answer the query in - the request. - non_critical_errors: - A list of non-critical errors happened during the request - handling to explain why ``fully_explored`` is false, or empty - if no error happened. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse) - }, -) -_sym_db.RegisterMessage(AnalyzeIamPolicyResponse) -_sym_db.RegisterMessage(AnalyzeIamPolicyResponse.IamPolicyAnalysis) - -IamPolicyAnalysisOutputConfig = _reflection.GeneratedProtocolMessageType( - "IamPolicyAnalysisOutputConfig", - (_message.Message,), - { - "GcsDestination": _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISOUTPUTCONFIG_GCSDESTINATION, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """A Cloud Storage location. - - Attributes: - uri: - Required. The uri of the Cloud Storage object. It’s the same - uri that is used by gsutil. For example: - “gs://bucket_name/object_name”. See `Viewing and Editing - Object Metadata - `__ for more information. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisOutputConfig.GcsDestination) - }, - ), - "DESCRIPTOR": _IAMPOLICYANALYSISOUTPUTCONFIG, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """Output configuration for export IAM policy analysis destination. - - Attributes: - destination: - IAM policy analysis export destination. - gcs_destination: - Destination on Cloud Storage. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisOutputConfig) - }, -) -_sym_db.RegisterMessage(IamPolicyAnalysisOutputConfig) -_sym_db.RegisterMessage(IamPolicyAnalysisOutputConfig.GcsDestination) - -ExportIamPolicyAnalysisRequest = _reflection.GeneratedProtocolMessageType( - "ExportIamPolicyAnalysisRequest", - (_message.Message,), - { - "Options": _reflection.GeneratedProtocolMessageType( - "Options", - (_message.Message,), - { - "DESCRIPTOR": _EXPORTIAMPOLICYANALYSISREQUEST_OPTIONS, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """Contains request options. - - Attributes: - expand_groups: - Optional. If true, the identities section of the result will - expand any Google groups appearing in an IAM policy binding. - If [identity_selector][] is specified, the identity in the - result will be determined by the selector, and this flag will - have no effect. Default is false. - expand_roles: - Optional. If true, the access section of result will expand - any roles appearing in IAM policy bindings to include their - permissions. If [access_selector][] is specified, the access - section of the result will be determined by the selector, and - this flag will have no effect. Default is false. - expand_resources: - Optional. If true, the resource section of the result will - expand any resource attached to an IAM policy to include - resources lower in the resource hierarchy. For example, if - the request analyzes for which resources user A has permission - P, and the results include an IAM policy with P on a GCP - folder, the results will also include resources in that folder - with permission P. If [resource_selector][] is specified, the - resource section of the result will be determined by the - selector, and this flag will have no effect. Default is false. - output_resource_edges: - Optional. If true, the result will output resource edges, - starting from the policy attached resource, to any expanded - resources. Default is false. - output_group_edges: - Optional. If true, the result will output group identity - edges, starting from the binding’s group members, to any - expanded identities. Default is false. - analyze_service_account_impersonation: - Optional. If true, the response will include access analysis - from identities to resources via service account - impersonation. This is a very expensive operation, because - many derived queries will be executed. For example, if the - request analyzes for which resources user A has permission P, - and there’s an IAM policy states user A has - iam.serviceAccounts.getAccessToken permission to a service - account SA, and there’s another IAM policy states service - account SA has permission P to a GCP folder F, then user A - potentially has access to the GCP folder F. And those advanced - analysis results will be included in [AnalyzeIamPolicyResponse - .service_account_impersonation_analysis][google.cloud.asset.v1 - p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation - _analysis]. Another example, if the request analyzes for who - has permission P to a GCP folder F, and there’s an IAM policy - states user A has iam.serviceAccounts.actAs permission to a - service account SA, and there’s another IAM policy states - service account SA has permission P to the GCP folder F, then - user A potentially has access to the GCP folder F. And those - advanced analysis results will be included in [AnalyzeIamPolic - yResponse.service_account_impersonation_analysis][google.cloud - .asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impe - rsonation_analysis]. Default is false. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.ExportIamPolicyAnalysisRequest.Options) - }, - ), - "DESCRIPTOR": _EXPORTIAMPOLICYANALYSISREQUEST, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """A request message for [AssetService.ExportIamPolicyAnalysis][google.cl - oud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. - - Attributes: - analysis_query: - Required. The request query. - options: - Optional. The request options. - output_config: - Required. Output configuration indicating where the results - will be output to. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.ExportIamPolicyAnalysisRequest) - }, -) -_sym_db.RegisterMessage(ExportIamPolicyAnalysisRequest) -_sym_db.RegisterMessage(ExportIamPolicyAnalysisRequest.Options) - -ExportIamPolicyAnalysisResponse = _reflection.GeneratedProtocolMessageType( - "ExportIamPolicyAnalysisResponse", - (_message.Message,), - { - "DESCRIPTOR": _EXPORTIAMPOLICYANALYSISRESPONSE, - "__module__": "google.cloud.asset_v1p4beta1.proto.asset_service_pb2", - "__doc__": """The export IAM policy analysis response. This message is returned by - the [google.longrunning.Operations.GetOperation][] method in the - returned [google.longrunning.Operation.response][] field. - - Attributes: - output_config: - Output configuration indicating where the results were output - to. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.ExportIamPolicyAnalysisResponse) - }, -) -_sym_db.RegisterMessage(ExportIamPolicyAnalysisResponse) - - -DESCRIPTOR._options = None -_IAMPOLICYANALYSISQUERY_RESOURCESELECTOR.fields_by_name[ - "full_resource_name" -]._options = None -_IAMPOLICYANALYSISQUERY_IDENTITYSELECTOR.fields_by_name["identity"]._options = None -_IAMPOLICYANALYSISQUERY_ACCESSSELECTOR.fields_by_name["roles"]._options = None -_IAMPOLICYANALYSISQUERY_ACCESSSELECTOR.fields_by_name["permissions"]._options = None -_IAMPOLICYANALYSISQUERY.fields_by_name["parent"]._options = None -_IAMPOLICYANALYSISQUERY.fields_by_name["resource_selector"]._options = None -_IAMPOLICYANALYSISQUERY.fields_by_name["identity_selector"]._options = None -_IAMPOLICYANALYSISQUERY.fields_by_name["access_selector"]._options = None -_ANALYZEIAMPOLICYREQUEST_OPTIONS.fields_by_name["expand_groups"]._options = None -_ANALYZEIAMPOLICYREQUEST_OPTIONS.fields_by_name["expand_roles"]._options = None -_ANALYZEIAMPOLICYREQUEST_OPTIONS.fields_by_name["expand_resources"]._options = None -_ANALYZEIAMPOLICYREQUEST_OPTIONS.fields_by_name["output_resource_edges"]._options = None -_ANALYZEIAMPOLICYREQUEST_OPTIONS.fields_by_name["output_group_edges"]._options = None -_ANALYZEIAMPOLICYREQUEST_OPTIONS.fields_by_name[ - "analyze_service_account_impersonation" -]._options = None -_ANALYZEIAMPOLICYREQUEST_OPTIONS.fields_by_name["execution_timeout"]._options = None -_ANALYZEIAMPOLICYREQUEST.fields_by_name["analysis_query"]._options = None -_ANALYZEIAMPOLICYREQUEST.fields_by_name["options"]._options = None -_IAMPOLICYANALYSISOUTPUTCONFIG_GCSDESTINATION.fields_by_name["uri"]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST_OPTIONS.fields_by_name["expand_groups"]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST_OPTIONS.fields_by_name["expand_roles"]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST_OPTIONS.fields_by_name[ - "expand_resources" -]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST_OPTIONS.fields_by_name[ - "output_resource_edges" -]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST_OPTIONS.fields_by_name[ - "output_group_edges" -]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST_OPTIONS.fields_by_name[ - "analyze_service_account_impersonation" -]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST.fields_by_name["analysis_query"]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST.fields_by_name["options"]._options = None -_EXPORTIAMPOLICYANALYSISREQUEST.fields_by_name["output_config"]._options = None - -_ASSETSERVICE = _descriptor.ServiceDescriptor( - name="AssetService", - full_name="google.cloud.asset.v1p4beta1.AssetService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\031cloudasset.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=2710, - serialized_end=3323, - methods=[ - _descriptor.MethodDescriptor( - name="AnalyzeIamPolicy", - full_name="google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy", - index=0, - containing_service=None, - input_type=_ANALYZEIAMPOLICYREQUEST, - output_type=_ANALYZEIAMPOLICYRESPONSE, - serialized_options=b"\202\323\344\223\0029\0227/v1p4beta1/{analysis_query.parent=*/*}:analyzeIamPolicy", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ExportIamPolicyAnalysis", - full_name="google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis", - index=1, - containing_service=None, - input_type=_EXPORTIAMPOLICYANALYSISREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002C">/v1p4beta1/{analysis_query.parent=*/*}:exportIamPolicyAnalysis:\001*\312A{\n\n\rAnalysisState\x12\x1e\n\x04\x63ode\x18\x01 \x01(\x0e\x32\x10.google.rpc.Code\x12\r\n\x05\x63\x61use\x18\x02 \x01(\t\x1a\x83\x01\n\x08Resource\x12\x1a\n\x12\x66ull_resource_name\x18\x01 \x01(\t\x12[\n\x0e\x61nalysis_state\x18\x02 \x01(\x0b\x32\x43.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AnalysisState\x1a\x9b\x01\n\x06\x41\x63\x63\x65ss\x12\x0e\n\x04role\x18\x01 \x01(\tH\x00\x12\x14\n\npermission\x18\x02 \x01(\tH\x00\x12[\n\x0e\x61nalysis_state\x18\x03 \x01(\x0b\x32\x43.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AnalysisStateB\x0e\n\x0coneof_access\x1a\x30\n\x04\x45\x64ge\x12\x13\n\x0bsource_node\x18\x01 \x01(\t\x12\x13\n\x0btarget_node\x18\x02 \x01(\t\x1au\n\x08Identity\x12\x0c\n\x04name\x18\x01 \x01(\t\x12[\n\x0e\x61nalysis_state\x18\x02 \x01(\x0b\x32\x43.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AnalysisState\x1a\x8a\x02\n\x11\x41\x63\x63\x65ssControlList\x12Q\n\tresources\x18\x01 \x03(\x0b\x32>.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Resource\x12N\n\x08\x61\x63\x63\x65sses\x18\x02 \x03(\x0b\x32<.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Access\x12R\n\x0eresource_edges\x18\x03 \x03(\x0b\x32:.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge\x1a\xb3\x01\n\x0cIdentityList\x12R\n\nidentities\x18\x01 \x03(\x0b\x32>.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Identity\x12O\n\x0bgroup_edges\x18\x02 \x03(\x0b\x32:.google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.EdgeB\xb4\x01\n com.google.cloud.asset.v1p4beta1B\nAssetProtoP\x01ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p4beta1;asset\xf8\x01\x01\xaa\x02\x1cGoogle.Cloud.Asset.V1P4Beta1\xca\x02\x1cGoogle\\Cloud\\Asset\\V1p4beta1b\x06proto3', - dependencies=[ - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_rpc_dot_code__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - ], -) - - -_IAMPOLICYANALYSISRESULT_ANALYSISSTATE = _descriptor.Descriptor( - name="AnalysisState", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AnalysisState", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="code", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AnalysisState.code", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="cause", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AnalysisState.cause", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=490, - serialized_end=552, -) - -_IAMPOLICYANALYSISRESULT_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="full_resource_name", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Resource.full_resource_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="analysis_state", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Resource.analysis_state", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=555, - serialized_end=686, -) - -_IAMPOLICYANALYSISRESULT_ACCESS = _descriptor.Descriptor( - name="Access", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Access", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="role", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Access.role", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="permission", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Access.permission", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="analysis_state", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Access.analysis_state", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="oneof_access", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Access.oneof_access", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=689, - serialized_end=844, -) - -_IAMPOLICYANALYSISRESULT_EDGE = _descriptor.Descriptor( - name="Edge", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="source_node", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.source_node", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="target_node", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.target_node", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=846, - serialized_end=894, -) - -_IAMPOLICYANALYSISRESULT_IDENTITY = _descriptor.Descriptor( - name="Identity", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Identity", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Identity.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="analysis_state", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Identity.analysis_state", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=896, - serialized_end=1013, -) - -_IAMPOLICYANALYSISRESULT_ACCESSCONTROLLIST = _descriptor.Descriptor( - name="AccessControlList", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AccessControlList", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="resources", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AccessControlList.resources", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="accesses", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AccessControlList.accesses", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_edges", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AccessControlList.resource_edges", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1016, - serialized_end=1282, -) - -_IAMPOLICYANALYSISRESULT_IDENTITYLIST = _descriptor.Descriptor( - name="IdentityList", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.IdentityList", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="identities", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.IdentityList.identities", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="group_edges", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.IdentityList.group_edges", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1285, - serialized_end=1464, -) - -_IAMPOLICYANALYSISRESULT = _descriptor.Descriptor( - name="IamPolicyAnalysisResult", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="attached_resource_full_name", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.attached_resource_full_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="iam_binding", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="access_control_lists", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.access_control_lists", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="identity_list", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.identity_list", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="fully_explored", - full_name="google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.fully_explored", - index=4, - number=5, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _IAMPOLICYANALYSISRESULT_ANALYSISSTATE, - _IAMPOLICYANALYSISRESULT_RESOURCE, - _IAMPOLICYANALYSISRESULT_ACCESS, - _IAMPOLICYANALYSISRESULT_EDGE, - _IAMPOLICYANALYSISRESULT_IDENTITY, - _IAMPOLICYANALYSISRESULT_ACCESSCONTROLLIST, - _IAMPOLICYANALYSISRESULT_IDENTITYLIST, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=163, - serialized_end=1464, -) - -_IAMPOLICYANALYSISRESULT_ANALYSISSTATE.fields_by_name[ - "code" -].enum_type = google_dot_rpc_dot_code__pb2._CODE -_IAMPOLICYANALYSISRESULT_ANALYSISSTATE.containing_type = _IAMPOLICYANALYSISRESULT -_IAMPOLICYANALYSISRESULT_RESOURCE.fields_by_name[ - "analysis_state" -].message_type = _IAMPOLICYANALYSISRESULT_ANALYSISSTATE -_IAMPOLICYANALYSISRESULT_RESOURCE.containing_type = _IAMPOLICYANALYSISRESULT -_IAMPOLICYANALYSISRESULT_ACCESS.fields_by_name[ - "analysis_state" -].message_type = _IAMPOLICYANALYSISRESULT_ANALYSISSTATE -_IAMPOLICYANALYSISRESULT_ACCESS.containing_type = _IAMPOLICYANALYSISRESULT -_IAMPOLICYANALYSISRESULT_ACCESS.oneofs_by_name["oneof_access"].fields.append( - _IAMPOLICYANALYSISRESULT_ACCESS.fields_by_name["role"] -) -_IAMPOLICYANALYSISRESULT_ACCESS.fields_by_name[ - "role" -].containing_oneof = _IAMPOLICYANALYSISRESULT_ACCESS.oneofs_by_name["oneof_access"] -_IAMPOLICYANALYSISRESULT_ACCESS.oneofs_by_name["oneof_access"].fields.append( - _IAMPOLICYANALYSISRESULT_ACCESS.fields_by_name["permission"] -) -_IAMPOLICYANALYSISRESULT_ACCESS.fields_by_name[ - "permission" -].containing_oneof = _IAMPOLICYANALYSISRESULT_ACCESS.oneofs_by_name["oneof_access"] -_IAMPOLICYANALYSISRESULT_EDGE.containing_type = _IAMPOLICYANALYSISRESULT -_IAMPOLICYANALYSISRESULT_IDENTITY.fields_by_name[ - "analysis_state" -].message_type = _IAMPOLICYANALYSISRESULT_ANALYSISSTATE -_IAMPOLICYANALYSISRESULT_IDENTITY.containing_type = _IAMPOLICYANALYSISRESULT -_IAMPOLICYANALYSISRESULT_ACCESSCONTROLLIST.fields_by_name[ - "resources" -].message_type = _IAMPOLICYANALYSISRESULT_RESOURCE -_IAMPOLICYANALYSISRESULT_ACCESSCONTROLLIST.fields_by_name[ - "accesses" -].message_type = _IAMPOLICYANALYSISRESULT_ACCESS -_IAMPOLICYANALYSISRESULT_ACCESSCONTROLLIST.fields_by_name[ - "resource_edges" -].message_type = _IAMPOLICYANALYSISRESULT_EDGE -_IAMPOLICYANALYSISRESULT_ACCESSCONTROLLIST.containing_type = _IAMPOLICYANALYSISRESULT -_IAMPOLICYANALYSISRESULT_IDENTITYLIST.fields_by_name[ - "identities" -].message_type = _IAMPOLICYANALYSISRESULT_IDENTITY -_IAMPOLICYANALYSISRESULT_IDENTITYLIST.fields_by_name[ - "group_edges" -].message_type = _IAMPOLICYANALYSISRESULT_EDGE -_IAMPOLICYANALYSISRESULT_IDENTITYLIST.containing_type = _IAMPOLICYANALYSISRESULT -_IAMPOLICYANALYSISRESULT.fields_by_name[ - "iam_binding" -].message_type = ( - google_dot_iam_dot_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._BINDING -) -_IAMPOLICYANALYSISRESULT.fields_by_name[ - "access_control_lists" -].message_type = _IAMPOLICYANALYSISRESULT_ACCESSCONTROLLIST -_IAMPOLICYANALYSISRESULT.fields_by_name[ - "identity_list" -].message_type = _IAMPOLICYANALYSISRESULT_IDENTITYLIST -DESCRIPTOR.message_types_by_name["IamPolicyAnalysisResult"] = _IAMPOLICYANALYSISRESULT -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -IamPolicyAnalysisResult = _reflection.GeneratedProtocolMessageType( - "IamPolicyAnalysisResult", - (_message.Message,), - { - "AnalysisState": _reflection.GeneratedProtocolMessageType( - "AnalysisState", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISRESULT_ANALYSISSTATE, - "__module__": "google.cloud.asset_v1p4beta1.proto.assets_pb2", - "__doc__": """Represents analysis state of each node in the result graph or non- - critical errors in the response. - - Attributes: - code: - The Google standard error code that best describes the state. - For example: - OK means the node has been successfully - explored; - PERMISSION_DENIED means an access denied error is - encountered; - DEADLINE_EXCEEDED means the node hasn’t been - explored in time; - cause: - The human-readable description of the cause of failure. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AnalysisState) - }, - ), - "Resource": _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISRESULT_RESOURCE, - "__module__": "google.cloud.asset_v1p4beta1.proto.assets_pb2", - "__doc__": """A GCP resource that appears in an access control list. - - Attributes: - full_resource_name: - The `full resource name `__. - analysis_state: - The analysis state of this resource node. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Resource) - }, - ), - "Access": _reflection.GeneratedProtocolMessageType( - "Access", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISRESULT_ACCESS, - "__module__": "google.cloud.asset_v1p4beta1.proto.assets_pb2", - "__doc__": """A role or permission that appears in an access control list. - - Attributes: - role: - The role. - permission: - The permission. - analysis_state: - The analysis state of this access node. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Access) - }, - ), - "Edge": _reflection.GeneratedProtocolMessageType( - "Edge", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISRESULT_EDGE, - "__module__": "google.cloud.asset_v1p4beta1.proto.assets_pb2", - "__doc__": """A directional edge. - - Attributes: - source_node: - The source node of the edge. - target_node: - The target node of the edge. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge) - }, - ), - "Identity": _reflection.GeneratedProtocolMessageType( - "Identity", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISRESULT_IDENTITY, - "__module__": "google.cloud.asset_v1p4beta1.proto.assets_pb2", - "__doc__": """An identity that appears in an access control list. - - Attributes: - name: - The identity name in any form of members appear in `IAM policy - binding - `__, - such as: - user:foo@google.com - group:group1@google.com - - serviceAccount:s1@prj1.iam.gserviceaccount.com - - projectOwner:some_project_id - domain:google.com - allUsers - - etc. - analysis_state: - The analysis state of this identity node. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Identity) - }, - ), - "AccessControlList": _reflection.GeneratedProtocolMessageType( - "AccessControlList", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISRESULT_ACCESSCONTROLLIST, - "__module__": "google.cloud.asset_v1p4beta1.proto.assets_pb2", - "__doc__": """An access control list, derived from the above IAM policy binding, - which contains a set of resources and accesses. May include one item - from each set to compose an access control entry. NOTICE that there - could be multiple access control lists for one IAM policy binding. The - access control lists are created based on resource and access - combinations. For example, assume we have the following cases in one - IAM policy binding: - Permission P1 and P2 apply to resource R1 and - R2; - Permission P3 applies to resource R2 and R3; This will result - in the following access control lists: - AccessControlList 1: [R1, - R2], [P1, P2] - AccessControlList 2: [R2, R3], [P3] - - Attributes: - resources: - The resources that match one of the following conditions: - - The resource_selector, if it is specified in request; - - Otherwise, resources reachable from the policy attached - resource. - accesses: - The accesses that match one of the following conditions: - The - access_selector, if it is specified in request; - Otherwise, - access specifiers reachable from the policy binding’s role. - resource_edges: - Resource edges of the graph starting from the policy attached - resource to any descendant resources. The [Edge.source_node][g - oogle.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.sourc - e_node] contains the full resource name of a parent resource - and [Edge.target_node][google.cloud.asset.v1p4beta1.IamPolicyA - nalysisResult.Edge.target_node] contains the full resource - name of a child resource. This field is present only if the - output_resource_edges option is enabled in request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.AccessControlList) - }, - ), - "IdentityList": _reflection.GeneratedProtocolMessageType( - "IdentityList", - (_message.Message,), - { - "DESCRIPTOR": _IAMPOLICYANALYSISRESULT_IDENTITYLIST, - "__module__": "google.cloud.asset_v1p4beta1.proto.assets_pb2", - "__doc__": """ - Attributes: - identities: - Only the identities that match one of the following conditions - will be presented: - The identity_selector, if it is specified - in request; - Otherwise, identities reachable from the policy - binding’s members. - group_edges: - Group identity edges of the graph starting from the binding’s - group members to any node of the [identities][google.cloud.ass - et.v1p4beta1.IamPolicyAnalysisResult.IdentityList.identities]. - The [Edge.source_node][google.cloud.asset.v1p4beta1.IamPolicyA - nalysisResult.Edge.source_node] contains a group, such as - “group:parent@google.com”. The [Edge.target_node][google.cloud - .asset.v1p4beta1.IamPolicyAnalysisResult.Edge.target_node] - contains a member of the group, such as - “group:child@google.com” or “user:foo@google.com”. This field - is present only if the output_group_edges option is enabled in - request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.IdentityList) - }, - ), - "DESCRIPTOR": _IAMPOLICYANALYSISRESULT, - "__module__": "google.cloud.asset_v1p4beta1.proto.assets_pb2", - "__doc__": """IAM Policy analysis result, consisting of one IAM policy binding and - derived access control lists. - - Attributes: - attached_resource_full_name: - The full name of the resource to which the [iam_binding][googl - e.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] - policy attaches. - iam_binding: - The Cloud IAM policy binding under analysis. - access_control_lists: - The access control lists derived from the [iam_binding][google - .cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] - that match or potentially match resource and access selectors - specified in the request. - identity_list: - The identity list derived from members of the [iam_binding][go - ogle.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding - ] that match or potentially match identity selector specified - in the request. - fully_explored: - Represents whether all nodes in the transitive closure of the - [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisRe - sult.iam_binding] node have been explored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult) - }, -) -_sym_db.RegisterMessage(IamPolicyAnalysisResult) -_sym_db.RegisterMessage(IamPolicyAnalysisResult.AnalysisState) -_sym_db.RegisterMessage(IamPolicyAnalysisResult.Resource) -_sym_db.RegisterMessage(IamPolicyAnalysisResult.Access) -_sym_db.RegisterMessage(IamPolicyAnalysisResult.Edge) -_sym_db.RegisterMessage(IamPolicyAnalysisResult.Identity) -_sym_db.RegisterMessage(IamPolicyAnalysisResult.AccessControlList) -_sym_db.RegisterMessage(IamPolicyAnalysisResult.IdentityList) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1p4beta1/proto/assets_pb2_grpc.py b/google/cloud/asset_v1p4beta1/proto/assets_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/asset_v1p4beta1/proto/assets_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/asset_v1p4beta1/py.typed b/google/cloud/asset_v1p4beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/google/cloud/asset_v1p4beta1/services/__init__.py b/google/cloud/asset_v1p4beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/asset_v1p4beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py b/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py new file mode 100644 index 00000000..ec3c27d2 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient + +__all__ = ( + "AssetServiceClient", + "AssetServiceAsyncClient", +) diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py b/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..02a63e8f --- /dev/null +++ b/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.asset_v1p4beta1.types import asset_service +from google.cloud.asset_v1p4beta1.types import assets + +from .transports.base import AssetServiceTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = AssetServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(AssetServiceClient).get_transport_class, type(AssetServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = AssetServiceClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def analyze_iam_policy( + self, + request: asset_service.AnalyzeIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Analyzes IAM policies based on the specified request. Returns a + list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + matching the request. + + Args: + request (:class:`~.asset_service.AnalyzeIamPolicyRequest`): + The request object. A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.AnalyzeIamPolicyResponse: + A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. + + """ + # Create or coerce a protobuf request object. + + request = asset_service.AnalyzeIamPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.analyze_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=300.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.parent", request.analysis_query.parent),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def export_iam_policy_analysis( + self, + request: asset_service.ExportIamPolicyAnalysisRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports IAM policy analysis based on the specified request. This + API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. The metadata contains + the request to help callers to map responses to requests. + + Args: + request (:class:`~.asset_service.ExportIamPolicyAnalysisRequest`): + The request object. A request message for + [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.asset_service.ExportIamPolicyAnalysisResponse``: + The export IAM policy analysis response. This message is + returned by the + [google.longrunning.Operations.GetOperation][] method in + the returned [google.longrunning.Operation.response][] + field. + + """ + # Create or coerce a protobuf request object. + + request = asset_service.ExportIamPolicyAnalysisRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_iam_policy_analysis, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.parent", request.analysis_query.parent),) + ), + ) + + # 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, + asset_service.ExportIamPolicyAnalysisResponse, + metadata_type=asset_service.ExportIamPolicyAnalysisRequest, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceAsyncClient",) diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/client.py b/google/cloud/asset_v1p4beta1/services/asset_service/client.py new file mode 100644 index 00000000..2d473a48 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/services/asset_service/client.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.asset_v1p4beta1.types import asset_service +from google.cloud.asset_v1p4beta1.types import assets + +from .transports.base import AssetServiceTransport +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudasset.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AssetServiceTransport): + # transport is a AssetServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def analyze_iam_policy( + self, + request: asset_service.AnalyzeIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Analyzes IAM policies based on the specified request. Returns a + list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + matching the request. + + Args: + request (:class:`~.asset_service.AnalyzeIamPolicyRequest`): + The request object. A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.AnalyzeIamPolicyResponse: + A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.AnalyzeIamPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.AnalyzeIamPolicyRequest): + request = asset_service.AnalyzeIamPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.parent", request.analysis_query.parent),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def export_iam_policy_analysis( + self, + request: asset_service.ExportIamPolicyAnalysisRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports IAM policy analysis based on the specified request. This + API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. The metadata contains + the request to help callers to map responses to requests. + + Args: + request (:class:`~.asset_service.ExportIamPolicyAnalysisRequest`): + The request object. A request message for + [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.asset_service.ExportIamPolicyAnalysisResponse``: + The export IAM policy analysis response. This message is + returned by the + [google.longrunning.Operations.GetOperation][] method in + the returned [google.longrunning.Operation.response][] + field. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.ExportIamPolicyAnalysisRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ExportIamPolicyAnalysisRequest): + request = asset_service.ExportIamPolicyAnalysisRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.export_iam_policy_analysis + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("analysis_query.parent", request.analysis_query.parent),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + asset_service.ExportIamPolicyAnalysisResponse, + metadata_type=asset_service.ExportIamPolicyAnalysisRequest, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceClient",) diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..624eab74 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry["grpc"] = AssetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + +__all__ = ( + "AssetServiceTransport", + "AssetServiceGrpcTransport", + "AssetServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..498cb191 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.asset_v1p4beta1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.analyze_iam_policy: gapic_v1.method.wrap_method( + self.analyze_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + ), + default_timeout=300.0, + client_info=_client_info, + ), + self.export_iam_policy_analysis: gapic_v1.method.wrap_method( + self.export_iam_policy_analysis, + default_timeout=60.0, + client_info=_client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def analyze_iam_policy( + self, + ) -> typing.Callable[ + [asset_service.AnalyzeIamPolicyRequest], + typing.Union[ + asset_service.AnalyzeIamPolicyResponse, + typing.Awaitable[asset_service.AnalyzeIamPolicyResponse], + ], + ]: + raise NotImplementedError() + + @property + def export_iam_policy_analysis( + self, + ) -> typing.Callable[ + [asset_service.ExportIamPolicyAnalysisRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("AssetServiceTransport",) diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..4bc98bf0 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,286 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.asset_v1p4beta1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import AssetServiceTransport + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + 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. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def analyze_iam_policy( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], asset_service.AnalyzeIamPolicyResponse + ]: + r"""Return a callable for the analyze iam policy method over gRPC. + + Analyzes IAM policies based on the specified request. Returns a + list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + matching the request. + + Returns: + Callable[[~.AnalyzeIamPolicyRequest], + ~.AnalyzeIamPolicyResponse]: + 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 "analyze_iam_policy" not in self._stubs: + self._stubs["analyze_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p4beta1.AssetService/AnalyzeIamPolicy", + request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, + response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, + ) + return self._stubs["analyze_iam_policy"] + + @property + def export_iam_policy_analysis( + self, + ) -> Callable[[asset_service.ExportIamPolicyAnalysisRequest], operations.Operation]: + r"""Return a callable for the export iam policy analysis method over gRPC. + + Exports IAM policy analysis based on the specified request. This + API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. The metadata contains + the request to help callers to map responses to requests. + + Returns: + Callable[[~.ExportIamPolicyAnalysisRequest], + ~.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 "export_iam_policy_analysis" not in self._stubs: + self._stubs["export_iam_policy_analysis"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p4beta1.AssetService/ExportIamPolicyAnalysis", + request_serializer=asset_service.ExportIamPolicyAnalysisRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["export_iam_policy_analysis"] + + +__all__ = ("AssetServiceGrpcTransport",) diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..2b1f1a02 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,282 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1p4beta1.types import asset_service +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: 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: + address (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 ignored if ``channel`` 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`. + 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # 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. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def analyze_iam_policy( + self, + ) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + Awaitable[asset_service.AnalyzeIamPolicyResponse], + ]: + r"""Return a callable for the analyze iam policy method over gRPC. + + Analyzes IAM policies based on the specified request. Returns a + list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + matching the request. + + Returns: + Callable[[~.AnalyzeIamPolicyRequest], + Awaitable[~.AnalyzeIamPolicyResponse]]: + 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 "analyze_iam_policy" not in self._stubs: + self._stubs["analyze_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p4beta1.AssetService/AnalyzeIamPolicy", + request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, + response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, + ) + return self._stubs["analyze_iam_policy"] + + @property + def export_iam_policy_analysis( + self, + ) -> Callable[ + [asset_service.ExportIamPolicyAnalysisRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the export iam policy analysis method over gRPC. + + Exports IAM policy analysis based on the specified request. This + API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. The metadata contains + the request to help callers to map responses to requests. + + Returns: + Callable[[~.ExportIamPolicyAnalysisRequest], + 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 "export_iam_policy_analysis" not in self._stubs: + self._stubs["export_iam_policy_analysis"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p4beta1.AssetService/ExportIamPolicyAnalysis", + request_serializer=asset_service.ExportIamPolicyAnalysisRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["export_iam_policy_analysis"] + + +__all__ = ("AssetServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/asset_v1p4beta1/types.py b/google/cloud/asset_v1p4beta1/types.py deleted file mode 100644 index 00e0a7cb..00000000 --- a/google/cloud/asset_v1p4beta1/types.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.asset_v1p4beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p4beta1.proto import assets_pb2 -from google.iam.v1 import policy_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import duration_pb2 -from google.rpc import status_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - policy_pb2, - operations_pb2, - any_pb2, - duration_pb2, - status_pb2, - expr_pb2, -] - -_local_modules = [ - asset_service_pb2, - assets_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.asset_v1p4beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/asset_v1p4beta1/types/__init__.py b/google/cloud/asset_v1p4beta1/types/__init__.py new file mode 100644 index 00000000..06794497 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/types/__init__.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .assets import IamPolicyAnalysisResult +from .asset_service import ( + IamPolicyAnalysisQuery, + AnalyzeIamPolicyRequest, + AnalyzeIamPolicyResponse, + IamPolicyAnalysisOutputConfig, + ExportIamPolicyAnalysisRequest, + ExportIamPolicyAnalysisResponse, +) + + +__all__ = ( + "IamPolicyAnalysisResult", + "IamPolicyAnalysisQuery", + "AnalyzeIamPolicyRequest", + "AnalyzeIamPolicyResponse", + "IamPolicyAnalysisOutputConfig", + "ExportIamPolicyAnalysisRequest", + "ExportIamPolicyAnalysisResponse", +) diff --git a/google/cloud/asset_v1p4beta1/types/asset_service.py b/google/cloud/asset_v1p4beta1/types/asset_service.py new file mode 100644 index 00000000..db0a93fc --- /dev/null +++ b/google/cloud/asset_v1p4beta1/types/asset_service.py @@ -0,0 +1,460 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.asset_v1p4beta1.types import assets +from google.protobuf import duration_pb2 as duration # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1p4beta1", + manifest={ + "IamPolicyAnalysisQuery", + "AnalyzeIamPolicyRequest", + "AnalyzeIamPolicyResponse", + "IamPolicyAnalysisOutputConfig", + "ExportIamPolicyAnalysisRequest", + "ExportIamPolicyAnalysisResponse", + }, +) + + +class IamPolicyAnalysisQuery(proto.Message): + r"""IAM policy analysis query message. + + Attributes: + parent (str): + Required. The relative name of the root + asset. Only resources and IAM policies within + the parent will be analyzed. This can only be an + organization number (such as + "organizations/123") or a folder number (such as + "folders/123"). + resource_selector (~.asset_service.IamPolicyAnalysisQuery.ResourceSelector): + Optional. Specifies a resource for analysis. + Leaving it empty means ANY. + identity_selector (~.asset_service.IamPolicyAnalysisQuery.IdentitySelector): + Optional. Specifies an identity for analysis. + Leaving it empty means ANY. + access_selector (~.asset_service.IamPolicyAnalysisQuery.AccessSelector): + Optional. Specifies roles or permissions for + analysis. Leaving it empty means ANY. + """ + + class ResourceSelector(proto.Message): + r"""Specifies the resource to analyze for access policies, which may be + set directly on the resource, or on ancestors such as organizations, + folders or projects. At least one of + [ResourceSelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.ResourceSelector], + [IdentitySelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.IdentitySelector] + or + [AccessSelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.AccessSelector] + must be specified in a request. + + Attributes: + full_resource_name (str): + Required. The `full resource + name `__ + . + """ + + full_resource_name = proto.Field(proto.STRING, number=1) + + class IdentitySelector(proto.Message): + r"""Specifies an identity for which to determine resource access, + based on roles assigned either directly to them or to the groups + they belong to, directly or indirectly. + + Attributes: + identity (str): + Required. The identity appear in the form of members in `IAM + policy + binding `__. + """ + + identity = proto.Field(proto.STRING, number=1) + + class AccessSelector(proto.Message): + r"""Specifies roles and/or permissions to analyze, to determine + both the identities possessing them and the resources they + control. If multiple values are specified, results will include + identities and resources matching any of them. + + Attributes: + roles (Sequence[str]): + Optional. The roles to appear in result. + permissions (Sequence[str]): + Optional. The permissions to appear in + result. + """ + + roles = proto.RepeatedField(proto.STRING, number=1) + + permissions = proto.RepeatedField(proto.STRING, number=2) + + parent = proto.Field(proto.STRING, number=1) + + resource_selector = proto.Field(proto.MESSAGE, number=2, message=ResourceSelector,) + + identity_selector = proto.Field(proto.MESSAGE, number=3, message=IdentitySelector,) + + access_selector = proto.Field(proto.MESSAGE, number=4, message=AccessSelector,) + + +class AnalyzeIamPolicyRequest(proto.Message): + r"""A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. + + Attributes: + analysis_query (~.asset_service.IamPolicyAnalysisQuery): + Required. The request query. + options (~.asset_service.AnalyzeIamPolicyRequest.Options): + Optional. The request options. + """ + + class Options(proto.Message): + r"""Contains request options. + + Attributes: + expand_groups (bool): + Optional. If true, the identities section of the result will + expand any Google groups appearing in an IAM policy binding. + + If [identity_selector][] is specified, the identity in the + result will be determined by the selector, and this flag + will have no effect. + + Default is false. + expand_roles (bool): + Optional. If true, the access section of result will expand + any roles appearing in IAM policy bindings to include their + permissions. + + If [access_selector][] is specified, the access section of + the result will be determined by the selector, and this flag + will have no effect. + + Default is false. + expand_resources (bool): + Optional. If true, the resource section of the result will + expand any resource attached to an IAM policy to include + resources lower in the resource hierarchy. + + For example, if the request analyzes for which resources + user A has permission P, and the results include an IAM + policy with P on a GCP folder, the results will also include + resources in that folder with permission P. + + If [resource_selector][] is specified, the resource section + of the result will be determined by the selector, and this + flag will have no effect. Default is false. + output_resource_edges (bool): + Optional. If true, the result will output + resource edges, starting from the policy + attached resource, to any expanded resources. + Default is false. + output_group_edges (bool): + Optional. If true, the result will output + group identity edges, starting from the + binding's group members, to any expanded + identities. Default is false. + analyze_service_account_impersonation (bool): + Optional. If true, the response will include access analysis + from identities to resources via service account + impersonation. This is a very expensive operation, because + many derived queries will be executed. We highly recommend + you use ExportIamPolicyAnalysis rpc instead. + + For example, if the request analyzes for which resources + user A has permission P, and there's an IAM policy states + user A has iam.serviceAccounts.getAccessToken permission to + a service account SA, and there's another IAM policy states + service account SA has permission P to a GCP folder F, then + user A potentially has access to the GCP folder F. And those + advanced analysis results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Another example, if the request analyzes for who has + permission P to a GCP folder F, and there's an IAM policy + states user A has iam.serviceAccounts.actAs permission to a + service account SA, and there's another IAM policy states + service account SA has permission P to the GCP folder F, + then user A potentially has access to the GCP folder F. And + those advanced analysis results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Default is false. + execution_timeout (~.duration.Duration): + Optional. Amount of time executable has to complete. See + JSON representation of + `Duration `__. + + If this field is set with a value less than the RPC + deadline, and the execution of your query hasn't finished in + the specified execution timeout, you will get a response + with partial result. Otherwise, your query's execution will + continue until the RPC deadline. If it's not finished until + then, you will get a DEADLINE_EXCEEDED error. + + Default is empty. + """ + + expand_groups = proto.Field(proto.BOOL, number=1) + + expand_roles = proto.Field(proto.BOOL, number=2) + + expand_resources = proto.Field(proto.BOOL, number=3) + + output_resource_edges = proto.Field(proto.BOOL, number=4) + + output_group_edges = proto.Field(proto.BOOL, number=5) + + analyze_service_account_impersonation = proto.Field(proto.BOOL, number=6) + + execution_timeout = proto.Field( + proto.MESSAGE, number=7, message=duration.Duration, + ) + + analysis_query = proto.Field( + proto.MESSAGE, number=1, message=IamPolicyAnalysisQuery, + ) + + options = proto.Field(proto.MESSAGE, number=2, message=Options,) + + +class AnalyzeIamPolicyResponse(proto.Message): + r"""A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. + + Attributes: + main_analysis (~.asset_service.AnalyzeIamPolicyResponse.IamPolicyAnalysis): + The main analysis that matches the original + request. + service_account_impersonation_analysis (Sequence[~.asset_service.AnalyzeIamPolicyResponse.IamPolicyAnalysis]): + The service account impersonation analysis if + [AnalyzeIamPolicyRequest.analyze_service_account_impersonation][] + is enabled. + fully_explored (bool): + Represents whether all entries in the + [main_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.main_analysis] + and + [service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis] + have been fully explored to answer the query in the request. + non_critical_errors (Sequence[~.assets.IamPolicyAnalysisResult.AnalysisState]): + A list of non-critical errors happened during the request + handling to explain why ``fully_explored`` is false, or + empty if no error happened. + """ + + class IamPolicyAnalysis(proto.Message): + r"""An analysis message to group the query and results. + + Attributes: + analysis_query (~.asset_service.IamPolicyAnalysisQuery): + The analysis query. + analysis_results (Sequence[~.assets.IamPolicyAnalysisResult]): + A list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + that matches the analysis query, or empty if no result is + found. + fully_explored (bool): + Represents whether all entries in the + [analysis_results][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.IamPolicyAnalysis.analysis_results] + have been fully explored to answer the query. + """ + + analysis_query = proto.Field( + proto.MESSAGE, number=1, message=IamPolicyAnalysisQuery, + ) + + analysis_results = proto.RepeatedField( + proto.MESSAGE, number=2, message=assets.IamPolicyAnalysisResult, + ) + + fully_explored = proto.Field(proto.BOOL, number=3) + + main_analysis = proto.Field(proto.MESSAGE, number=1, message=IamPolicyAnalysis,) + + service_account_impersonation_analysis = proto.RepeatedField( + proto.MESSAGE, number=2, message=IamPolicyAnalysis, + ) + + fully_explored = proto.Field(proto.BOOL, number=3) + + non_critical_errors = proto.RepeatedField( + proto.MESSAGE, number=4, message=assets.IamPolicyAnalysisResult.AnalysisState, + ) + + +class IamPolicyAnalysisOutputConfig(proto.Message): + r"""Output configuration for export IAM policy analysis + destination. + + Attributes: + gcs_destination (~.asset_service.IamPolicyAnalysisOutputConfig.GcsDestination): + Destination on Cloud Storage. + """ + + class GcsDestination(proto.Message): + r"""A Cloud Storage location. + + Attributes: + uri (str): + Required. The uri of the Cloud Storage object. It's the same + uri that is used by gsutil. For example: + "gs://bucket_name/object_name". See `Viewing and Editing + Object + Metadata `__ + for more information. + """ + + uri = proto.Field(proto.STRING, number=1) + + gcs_destination = proto.Field( + proto.MESSAGE, number=1, oneof="destination", message=GcsDestination, + ) + + +class ExportIamPolicyAnalysisRequest(proto.Message): + r"""A request message for + [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. + + Attributes: + analysis_query (~.asset_service.IamPolicyAnalysisQuery): + Required. The request query. + options (~.asset_service.ExportIamPolicyAnalysisRequest.Options): + Optional. The request options. + output_config (~.asset_service.IamPolicyAnalysisOutputConfig): + Required. Output configuration indicating + where the results will be output to. + """ + + class Options(proto.Message): + r"""Contains request options. + + Attributes: + expand_groups (bool): + Optional. If true, the identities section of the result will + expand any Google groups appearing in an IAM policy binding. + + If [identity_selector][] is specified, the identity in the + result will be determined by the selector, and this flag + will have no effect. + + Default is false. + expand_roles (bool): + Optional. If true, the access section of result will expand + any roles appearing in IAM policy bindings to include their + permissions. + + If [access_selector][] is specified, the access section of + the result will be determined by the selector, and this flag + will have no effect. + + Default is false. + expand_resources (bool): + Optional. If true, the resource section of the result will + expand any resource attached to an IAM policy to include + resources lower in the resource hierarchy. + + For example, if the request analyzes for which resources + user A has permission P, and the results include an IAM + policy with P on a GCP folder, the results will also include + resources in that folder with permission P. + + If [resource_selector][] is specified, the resource section + of the result will be determined by the selector, and this + flag will have no effect. Default is false. + output_resource_edges (bool): + Optional. If true, the result will output + resource edges, starting from the policy + attached resource, to any expanded resources. + Default is false. + output_group_edges (bool): + Optional. If true, the result will output + group identity edges, starting from the + binding's group members, to any expanded + identities. Default is false. + analyze_service_account_impersonation (bool): + Optional. If true, the response will include access analysis + from identities to resources via service account + impersonation. This is a very expensive operation, because + many derived queries will be executed. + + For example, if the request analyzes for which resources + user A has permission P, and there's an IAM policy states + user A has iam.serviceAccounts.getAccessToken permission to + a service account SA, and there's another IAM policy states + service account SA has permission P to a GCP folder F, then + user A potentially has access to the GCP folder F. And those + advanced analysis results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Another example, if the request analyzes for who has + permission P to a GCP folder F, and there's an IAM policy + states user A has iam.serviceAccounts.actAs permission to a + service account SA, and there's another IAM policy states + service account SA has permission P to the GCP folder F, + then user A potentially has access to the GCP folder F. And + those advanced analysis results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Default is false. + """ + + expand_groups = proto.Field(proto.BOOL, number=1) + + expand_roles = proto.Field(proto.BOOL, number=2) + + expand_resources = proto.Field(proto.BOOL, number=3) + + output_resource_edges = proto.Field(proto.BOOL, number=4) + + output_group_edges = proto.Field(proto.BOOL, number=5) + + analyze_service_account_impersonation = proto.Field(proto.BOOL, number=6) + + analysis_query = proto.Field( + proto.MESSAGE, number=1, message=IamPolicyAnalysisQuery, + ) + + options = proto.Field(proto.MESSAGE, number=2, message=Options,) + + output_config = proto.Field( + proto.MESSAGE, number=3, message=IamPolicyAnalysisOutputConfig, + ) + + +class ExportIamPolicyAnalysisResponse(proto.Message): + r"""The export IAM policy analysis response. This message is returned by + the [google.longrunning.Operations.GetOperation][] method in the + returned [google.longrunning.Operation.response][] field. + + Attributes: + output_config (~.asset_service.IamPolicyAnalysisOutputConfig): + Output configuration indicating where the + results were output to. + """ + + output_config = proto.Field( + proto.MESSAGE, number=1, message=IamPolicyAnalysisOutputConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p4beta1/types/assets.py b/google/cloud/asset_v1p4beta1/types/assets.py new file mode 100644 index 00000000..af57f224 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/types/assets.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.rpc import code_pb2 as gr_code # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1p4beta1", manifest={"IamPolicyAnalysisResult",}, +) + + +class IamPolicyAnalysisResult(proto.Message): + r"""IAM Policy analysis result, consisting of one IAM policy + binding and derived access control lists. + + Attributes: + attached_resource_full_name (str): + The full name of the resource to which the + [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] + policy attaches. + iam_binding (~.policy.Binding): + The Cloud IAM policy binding under analysis. + access_control_lists (Sequence[~.assets.IamPolicyAnalysisResult.AccessControlList]): + The access control lists derived from the + [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] + that match or potentially match resource and access + selectors specified in the request. + identity_list (~.assets.IamPolicyAnalysisResult.IdentityList): + The identity list derived from members of the + [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] + that match or potentially match identity selector specified + in the request. + fully_explored (bool): + Represents whether all nodes in the transitive closure of + the + [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] + node have been explored. + """ + + class AnalysisState(proto.Message): + r"""Represents analysis state of each node in the result graph or + non-critical errors in the response. + + Attributes: + code (~.gr_code.Code): + The Google standard error code that best describes the + state. For example: + + - OK means the node has been successfully explored; + - PERMISSION_DENIED means an access denied error is + encountered; + - DEADLINE_EXCEEDED means the node hasn't been explored in + time; + cause (str): + The human-readable description of the cause + of failure. + """ + + code = proto.Field(proto.ENUM, number=1, enum=gr_code.Code,) + + cause = proto.Field(proto.STRING, number=2) + + class Resource(proto.Message): + r"""A GCP resource that appears in an access control list. + + Attributes: + full_resource_name (str): + The `full resource + name `__. + analysis_state (~.assets.IamPolicyAnalysisResult.AnalysisState): + The analysis state of this resource node. + """ + + full_resource_name = proto.Field(proto.STRING, number=1) + + analysis_state = proto.Field( + proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.AnalysisState", + ) + + class Access(proto.Message): + r"""A role or permission that appears in an access control list. + + Attributes: + role (str): + The role. + permission (str): + The permission. + analysis_state (~.assets.IamPolicyAnalysisResult.AnalysisState): + The analysis state of this access node. + """ + + role = proto.Field(proto.STRING, number=1, oneof="oneof_access") + + permission = proto.Field(proto.STRING, number=2, oneof="oneof_access") + + analysis_state = proto.Field( + proto.MESSAGE, number=3, message="IamPolicyAnalysisResult.AnalysisState", + ) + + class Edge(proto.Message): + r"""A directional edge. + + Attributes: + source_node (str): + The source node of the edge. + target_node (str): + The target node of the edge. + """ + + source_node = proto.Field(proto.STRING, number=1) + + target_node = proto.Field(proto.STRING, number=2) + + class Identity(proto.Message): + r"""An identity that appears in an access control list. + + Attributes: + name (str): + The identity name in any form of members appear in `IAM + policy + binding `__, + such as: + + - user:foo@google.com + - group:group1@google.com + - serviceAccount:s1@prj1.iam.gserviceaccount.com + - projectOwner:some_project_id + - domain:google.com + - allUsers + - etc. + analysis_state (~.assets.IamPolicyAnalysisResult.AnalysisState): + The analysis state of this identity node. + """ + + name = proto.Field(proto.STRING, number=1) + + analysis_state = proto.Field( + proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.AnalysisState", + ) + + class AccessControlList(proto.Message): + r"""An access control list, derived from the above IAM policy binding, + which contains a set of resources and accesses. May include one item + from each set to compose an access control entry. + + NOTICE that there could be multiple access control lists for one IAM + policy binding. The access control lists are created based on + resource and access combinations. + + For example, assume we have the following cases in one IAM policy + binding: + + - Permission P1 and P2 apply to resource R1 and R2; + - Permission P3 applies to resource R2 and R3; + + This will result in the following access control lists: + + - AccessControlList 1: [R1, R2], [P1, P2] + - AccessControlList 2: [R2, R3], [P3] + + Attributes: + resources (Sequence[~.assets.IamPolicyAnalysisResult.Resource]): + The resources that match one of the following conditions: + + - The resource_selector, if it is specified in request; + - Otherwise, resources reachable from the policy attached + resource. + accesses (Sequence[~.assets.IamPolicyAnalysisResult.Access]): + The accesses that match one of the following conditions: + + - The access_selector, if it is specified in request; + - Otherwise, access specifiers reachable from the policy + binding's role. + resource_edges (Sequence[~.assets.IamPolicyAnalysisResult.Edge]): + Resource edges of the graph starting from the policy + attached resource to any descendant resources. The + [Edge.source_node][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.source_node] + contains the full resource name of a parent resource and + [Edge.target_node][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.target_node] + contains the full resource name of a child resource. This + field is present only if the output_resource_edges option is + enabled in request. + """ + + resources = proto.RepeatedField( + proto.MESSAGE, number=1, message="IamPolicyAnalysisResult.Resource", + ) + + accesses = proto.RepeatedField( + proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.Access", + ) + + resource_edges = proto.RepeatedField( + proto.MESSAGE, number=3, message="IamPolicyAnalysisResult.Edge", + ) + + class IdentityList(proto.Message): + r""" + + Attributes: + identities (Sequence[~.assets.IamPolicyAnalysisResult.Identity]): + Only the identities that match one of the following + conditions will be presented: + + - The identity_selector, if it is specified in request; + - Otherwise, identities reachable from the policy binding's + members. + group_edges (Sequence[~.assets.IamPolicyAnalysisResult.Edge]): + Group identity edges of the graph starting from the + binding's group members to any node of the + [identities][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.IdentityList.identities]. + The + [Edge.source_node][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.source_node] + contains a group, such as "group:parent@google.com". The + [Edge.target_node][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.target_node] + contains a member of the group, such as + "group:child@google.com" or "user:foo@google.com". This + field is present only if the output_group_edges option is + enabled in request. + """ + + identities = proto.RepeatedField( + proto.MESSAGE, number=1, message="IamPolicyAnalysisResult.Identity", + ) + + group_edges = proto.RepeatedField( + proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.Edge", + ) + + attached_resource_full_name = proto.Field(proto.STRING, number=1) + + iam_binding = proto.Field(proto.MESSAGE, number=2, message=policy.Binding,) + + access_control_lists = proto.RepeatedField( + proto.MESSAGE, number=3, message=AccessControlList, + ) + + identity_list = proto.Field(proto.MESSAGE, number=4, message=IdentityList,) + + fully_explored = proto.Field(proto.BOOL, number=5) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p5beta1/__init__.py b/google/cloud/asset_v1p5beta1/__init__.py index fad23f62..e4ca4004 100644 --- a/google/cloud/asset_v1p5beta1/__init__.py +++ b/google/cloud/asset_v1p5beta1/__init__.py @@ -1,41 +1,33 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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 __future__ import absolute_import -import sys -import warnings - -from google.cloud.asset_v1p5beta1 import types -from google.cloud.asset_v1p5beta1.gapic import asset_service_client -from google.cloud.asset_v1p5beta1.gapic import enums - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class AssetServiceClient(asset_service_client.AssetServiceClient): - __doc__ = asset_service_client.AssetServiceClient.__doc__ - enums = enums - - -__all__ = ("enums", "types", "AssetServiceClient") +from .services.asset_service import AssetServiceClient +from .types.asset_service import ContentType +from .types.asset_service import ListAssetsRequest +from .types.asset_service import ListAssetsResponse +from .types.assets import Asset +from .types.assets import Resource + + +__all__ = ( + "Asset", + "ContentType", + "ListAssetsRequest", + "ListAssetsResponse", + "Resource", + "AssetServiceClient", +) diff --git a/google/cloud/asset_v1p5beta1/gapic/__init__.py b/google/cloud/asset_v1p5beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p5beta1/gapic/asset_service_client.py b/google/cloud/asset_v1p5beta1/gapic/asset_service_client.py deleted file mode 100644 index d079daa3..00000000 --- a/google/cloud/asset_v1p5beta1/gapic/asset_service_client.py +++ /dev/null @@ -1,316 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Accesses the google.cloud.asset.v1p5beta1 AssetService API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.page_iterator -import grpc - -from google.cloud.asset_v1p5beta1.gapic import asset_service_client_config -from google.cloud.asset_v1p5beta1.gapic import enums -from google.cloud.asset_v1p5beta1.gapic.transports import asset_service_grpc_transport -from google.cloud.asset_v1p5beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p5beta1.proto import asset_service_pb2_grpc -from google.protobuf import timestamp_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-asset").version - - -class AssetServiceClient(object): - """Asset service definition.""" - - SERVICE_ADDRESS = "cloudasset.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.asset.v1p5beta1.AssetService" - - @classmethod - def from_service_account_file(cls, filename, *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: - AssetServiceClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.AssetServiceGrpcTransport, - Callable[[~.Credentials, type], ~.AssetServiceGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - 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. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = asset_service_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=asset_service_grpc_transport.AssetServiceGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = asset_service_grpc_transport.AssetServiceGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME] - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def list_assets( - self, - parent, - read_time=None, - asset_types=None, - content_type=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists assets with time and resource types and returns paged results in - response. - - Example: - >>> from google.cloud import asset_v1p5beta1 - >>> - >>> client = asset_v1p5beta1.AssetServiceClient() - >>> - >>> # TODO: Initialize `parent`: - >>> parent = '' - >>> - >>> # Iterate over all results - >>> for element in client.list_assets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_assets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Name of the organization or project the assets belong to. - Format: "organizations/[organization-number]" (such as - "organizations/123"), "projects/[project-number]" (such as - "projects/my-project-id"), or "projects/[project-id]" (such as - "projects/12345"). - read_time (Union[dict, ~google.cloud.asset_v1p5beta1.types.Timestamp]): Timestamp to take an asset snapshot. This can only be set to a timestamp - between 2018-10-02 UTC (inclusive) and the current time. If not specified, - the current time will be used. Due to delays in resource data collection - and indexing, there is a volatile window during which running the same - query may get different results. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.asset_v1p5beta1.types.Timestamp` - asset_types (list[str]): A list of asset types of which to take a snapshot for. For example: - "compute.googleapis.com/Disk". If specified, only matching assets will - be returned. See `Introduction to Cloud Asset - Inventory `__ - for all supported asset types. - content_type (~google.cloud.asset_v1p5beta1.types.ContentType): Asset content type. If not specified, no content but the asset name will - be returned. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.asset_v1p5beta1.types.Asset` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_assets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_assets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_assets, - default_retry=self._method_configs["ListAssets"].retry, - default_timeout=self._method_configs["ListAssets"].timeout, - client_info=self._client_info, - ) - - request = asset_service_pb2.ListAssetsRequest( - parent=parent, - read_time=read_time, - asset_types=asset_types, - content_type=content_type, - page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="assets", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator diff --git a/google/cloud/asset_v1p5beta1/gapic/asset_service_client_config.py b/google/cloud/asset_v1p5beta1/gapic/asset_service_client_config.py deleted file mode 100644 index ae4705f6..00000000 --- a/google/cloud/asset_v1p5beta1/gapic/asset_service_client_config.py +++ /dev/null @@ -1,28 +0,0 @@ -config = { - "interfaces": { - "google.cloud.asset.v1p5beta1.AssetService": { - "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } - }, - "methods": { - "ListAssets": { - "timeout_millis": 600000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - } - }, - } - } -} diff --git a/google/cloud/asset_v1p5beta1/gapic/enums.py b/google/cloud/asset_v1p5beta1/gapic/enums.py deleted file mode 100644 index bc92bd1d..00000000 --- a/google/cloud/asset_v1p5beta1/gapic/enums.py +++ /dev/null @@ -1,181 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class ContentType(enum.IntEnum): - """ - Asset content type. - - Attributes: - CONTENT_TYPE_UNSPECIFIED (int): Unspecified content type. - RESOURCE (int): Resource metadata. - IAM_POLICY (int): The actual IAM policy set on a resource. - ORG_POLICY (int): The Cloud Organization Policy set on an asset. - ACCESS_POLICY (int): The Cloud Access context mananger Policy set on an asset. - """ - - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 - ORG_POLICY = 4 - ACCESS_POLICY = 5 - - -class DeviceEncryptionStatus(enum.IntEnum): - """ - The encryption state of the device. - - Attributes: - ENCRYPTION_UNSPECIFIED (int): The encryption status of the device is not specified or not known. - ENCRYPTION_UNSUPPORTED (int): The device does not support encryption. - UNENCRYPTED (int): The device supports encryption, but is currently unencrypted. - ENCRYPTED (int): The device is encrypted. - """ - - ENCRYPTION_UNSPECIFIED = 0 - ENCRYPTION_UNSUPPORTED = 1 - UNENCRYPTED = 2 - ENCRYPTED = 3 - - -class DeviceManagementLevel(enum.IntEnum): - """ - The degree to which the device is managed by the Cloud organization. - - Attributes: - MANAGEMENT_UNSPECIFIED (int): The device's management level is not specified or not known. - NONE (int): The device is not managed. - BASIC (int): Basic management is enabled, which is generally limited to monitoring and - wiping the corporate account. - COMPLETE (int): Complete device management. This includes more thorough monitoring and the - ability to directly manage the device (such as remote wiping). This can be - enabled through the Android Enterprise Platform. - """ - - MANAGEMENT_UNSPECIFIED = 0 - NONE = 1 - BASIC = 2 - COMPLETE = 3 - - -class NullValue(enum.IntEnum): - """ - ``NullValue`` is a singleton enumeration to represent the null value - for the ``Value`` type union. - - The JSON representation for ``NullValue`` is JSON ``null``. - - Attributes: - NULL_VALUE (int): Null value. - """ - - NULL_VALUE = 0 - - -class OsType(enum.IntEnum): - """ - The operating system type of the device. - Next id: 7 - - Attributes: - OS_UNSPECIFIED (int): The operating system of the device is not specified or not known. - DESKTOP_MAC (int): A desktop Mac operating system. - DESKTOP_WINDOWS (int): A desktop Windows operating system. - DESKTOP_LINUX (int): A desktop Linux operating system. - DESKTOP_CHROME_OS (int): A desktop ChromeOS operating system. - ANDROID (int): An Android operating system. - IOS (int): An iOS operating system. - """ - - OS_UNSPECIFIED = 0 - DESKTOP_MAC = 1 - DESKTOP_WINDOWS = 2 - DESKTOP_LINUX = 3 - DESKTOP_CHROME_OS = 6 - ANDROID = 4 - IOS = 5 - - -class BasicLevel(object): - class ConditionCombiningFunction(enum.IntEnum): - """ - Options for how the ``conditions`` list should be combined to - determine if this ``AccessLevel`` is applied. Default is AND. - - Attributes: - AND (int): All ``Conditions`` must be true for the ``BasicLevel`` to be true. - OR (int): If at least one ``Condition`` is true, then the ``BasicLevel`` is - true. - """ - - AND = 0 - OR = 1 - - -class Policy(object): - class ListPolicy(object): - class AllValues(enum.IntEnum): - """ - This enum can be used to set ``Policies`` that apply to all possible - configuration values rather than specific values in ``allowed_values`` - or ``denied_values``. - - Settting this to ``ALLOW`` will mean this ``Policy`` allows all values. - Similarly, setting it to ``DENY`` will mean no values are allowed. If - set to either ``ALLOW`` or - ``DENY,``\ allowed_values\ ``and``\ denied_values\ ``must be unset. Setting this to``\ ALL_VALUES_UNSPECIFIED\ ``allows for setting``\ allowed_values\ ``and``\ denied_values`. - - Attributes: - ALL_VALUES_UNSPECIFIED (int): Indicates that allowed_values or denied_values must be set. - ALLOW (int): A policy with this set allows all values. - DENY (int): A policy with this set denies all values. - """ - - ALL_VALUES_UNSPECIFIED = 0 - ALLOW = 1 - DENY = 2 - - -class ServicePerimeter(object): - class PerimeterType(enum.IntEnum): - """ - Specifies the type of the Perimeter. There are two types: regular and - bridge. Regular Service Perimeter contains resources, access levels, and - restricted services. Every resource can be in at most ONE - regular Service Perimeter. - - In addition to being in a regular service perimeter, a resource can also - be in zero or more perimeter bridges. A perimeter bridge only contains - resources. Cross project operations are permitted if all effected - resources share some perimeter (whether bridge or regular). Perimeter - Bridge does not contain access levels or services: those are governed - entirely by the regular perimeter that resource is in. - - Perimeter Bridges are typically useful when building more complex toplogies - with many independent perimeters that need to share some data with a common - perimeter, but should not be able to share data among themselves. - - Attributes: - PERIMETER_TYPE_REGULAR (int): Regular Perimeter. - PERIMETER_TYPE_BRIDGE (int): Perimeter Bridge. - """ - - PERIMETER_TYPE_REGULAR = 0 - PERIMETER_TYPE_BRIDGE = 1 diff --git a/google/cloud/asset_v1p5beta1/gapic/transports/__init__.py b/google/cloud/asset_v1p5beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p5beta1/gapic/transports/asset_service_grpc_transport.py b/google/cloud/asset_v1p5beta1/gapic/transports/asset_service_grpc_transport.py deleted file mode 100644 index 2114cd9d..00000000 --- a/google/cloud/asset_v1p5beta1/gapic/transports/asset_service_grpc_transport.py +++ /dev/null @@ -1,122 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 google.api_core.grpc_helpers - -from google.cloud.asset_v1p5beta1.proto import asset_service_pb2_grpc - - -class AssetServiceGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.asset.v1p5beta1 AssetService API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, channel=None, credentials=None, address="cloudasset.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.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. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive." - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "asset_service_stub": asset_service_pb2_grpc.AssetServiceStub(channel) - } - - @classmethod - def create_channel( - cls, address="cloudasset.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.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. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def list_assets(self): - """Return the gRPC stub for :meth:`AssetServiceClient.list_assets`. - - Lists assets with time and resource types and returns paged results in - response. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["asset_service_stub"].ListAssets diff --git a/google/cloud/asset_v1p5beta1/proto/__init__.py b/google/cloud/asset_v1p5beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/asset_v1p5beta1/proto/asset_service_pb2.py b/google/cloud/asset_v1p5beta1/proto/asset_service_pb2.py deleted file mode 100644 index 0ba91d04..00000000 --- a/google/cloud/asset_v1p5beta1/proto/asset_service_pb2.py +++ /dev/null @@ -1,432 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1p5beta1/proto/asset_service.proto - -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.cloud.asset_v1p5beta1.proto import ( - assets_pb2 as google_dot_cloud_dot_asset__v1p5beta1_dot_proto_dot_assets__pb2, -) -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1p5beta1/proto/asset_service.proto", - package="google.cloud.asset.v1p5beta1", - syntax="proto3", - serialized_options=b"\n com.google.cloud.asset.v1p5beta1B\021AssetServiceProtoP\001ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p5beta1;asset\252\002\034Google.Cloud.Asset.V1P5Beta1\312\002\034Google\\Cloud\\Asset\\V1p5beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n6google/cloud/asset_v1p5beta1/proto/asset_service.proto\x12\x1cgoogle.cloud.asset.v1p5beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a/google/cloud/asset_v1p5beta1/proto/assets.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xd4\x01\n\x11ListAssetsRequest\x12\x13\n\x06parent\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x13\n\x0b\x61sset_types\x18\x03 \x03(\t\x12?\n\x0c\x63ontent_type\x18\x04 \x01(\x0e\x32).google.cloud.asset.v1p5beta1.ContentType\x12\x11\n\tpage_size\x18\x05 \x01(\x05\x12\x12\n\npage_token\x18\x06 \x01(\t"\x91\x01\n\x12ListAssetsResponse\x12-\n\tread_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x06\x61ssets\x18\x02 \x03(\x0b\x32#.google.cloud.asset.v1p5beta1.Asset\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t*l\n\x0b\x43ontentType\x12\x1c\n\x18\x43ONTENT_TYPE_UNSPECIFIED\x10\x00\x12\x0c\n\x08RESOURCE\x10\x01\x12\x0e\n\nIAM_POLICY\x10\x02\x12\x0e\n\nORG_POLICY\x10\x04\x12\x11\n\rACCESS_POLICY\x10\x05\x32\xf7\x01\n\x0c\x41ssetService\x12\x97\x01\n\nListAssets\x12/.google.cloud.asset.v1p5beta1.ListAssetsRequest\x1a\x30.google.cloud.asset.v1p5beta1.ListAssetsResponse"&\x82\xd3\xe4\x93\x02 \x12\x1e/v1p5beta1/{parent=*/*}/assets\x1aM\xca\x41\x19\x63loudasset.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xb8\x01\n com.google.cloud.asset.v1p5beta1B\x11\x41ssetServiceProtoP\x01ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p5beta1;asset\xaa\x02\x1cGoogle.Cloud.Asset.V1P5Beta1\xca\x02\x1cGoogle\\Cloud\\Asset\\V1p5beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_cloud_dot_asset__v1p5beta1_dot_proto_dot_assets__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - -_CONTENTTYPE = _descriptor.EnumDescriptor( - name="ContentType", - full_name="google.cloud.asset.v1p5beta1.ContentType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="CONTENT_TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RESOURCE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="IAM_POLICY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ORG_POLICY", - index=3, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="ACCESS_POLICY", - index=4, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=621, - serialized_end=729, -) -_sym_db.RegisterEnumDescriptor(_CONTENTTYPE) - -ContentType = enum_type_wrapper.EnumTypeWrapper(_CONTENTTYPE) -CONTENT_TYPE_UNSPECIFIED = 0 -RESOURCE = 1 -IAM_POLICY = 2 -ORG_POLICY = 4 -ACCESS_POLICY = 5 - - -_LISTASSETSREQUEST = _descriptor.Descriptor( - name="ListAssetsRequest", - full_name="google.cloud.asset.v1p5beta1.ListAssetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1p5beta1.ListAssetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.asset.v1p5beta1.ListAssetsRequest.read_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_types", - full_name="google.cloud.asset.v1p5beta1.ListAssetsRequest.asset_types", - index=2, - number=3, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content_type", - full_name="google.cloud.asset.v1p5beta1.ListAssetsRequest.content_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.asset.v1p5beta1.ListAssetsRequest.page_size", - index=4, - number=5, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.asset.v1p5beta1.ListAssetsRequest.page_token", - index=5, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=259, - serialized_end=471, -) - - -_LISTASSETSRESPONSE = _descriptor.Descriptor( - name="ListAssetsResponse", - full_name="google.cloud.asset.v1p5beta1.ListAssetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="read_time", - full_name="google.cloud.asset.v1p5beta1.ListAssetsResponse.read_time", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="assets", - full_name="google.cloud.asset.v1p5beta1.ListAssetsResponse.assets", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.asset.v1p5beta1.ListAssetsResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=474, - serialized_end=619, -) - -_LISTASSETSREQUEST.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTASSETSREQUEST.fields_by_name["content_type"].enum_type = _CONTENTTYPE -_LISTASSETSRESPONSE.fields_by_name[ - "read_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_LISTASSETSRESPONSE.fields_by_name[ - "assets" -].message_type = google_dot_cloud_dot_asset__v1p5beta1_dot_proto_dot_assets__pb2._ASSET -DESCRIPTOR.message_types_by_name["ListAssetsRequest"] = _LISTASSETSREQUEST -DESCRIPTOR.message_types_by_name["ListAssetsResponse"] = _LISTASSETSRESPONSE -DESCRIPTOR.enum_types_by_name["ContentType"] = _CONTENTTYPE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ListAssetsRequest = _reflection.GeneratedProtocolMessageType( - "ListAssetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTASSETSREQUEST, - "__module__": "google.cloud.asset_v1p5beta1.proto.asset_service_pb2", - "__doc__": """ListAssets request. - - Attributes: - parent: - Required. Name of the organization or project the assets - belong to. Format: “organizations/[organization-number]” (such - as “organizations/123”), “projects/[project-number]” (such as - “projects/my-project-id”), or “projects/[project-id]” (such as - “projects/12345”). - read_time: - Timestamp to take an asset snapshot. This can only be set to a - timestamp between 2018-10-02 UTC (inclusive) and the current - time. If not specified, the current time will be used. Due to - delays in resource data collection and indexing, there is a - volatile window during which running the same query may get - different results. - asset_types: - A list of asset types of which to take a snapshot for. For - example: “compute.googleapis.com/Disk”. If specified, only - matching assets will be returned. See `Introduction to Cloud - Asset Inventory `__ for all - supported asset types. - content_type: - Asset content type. If not specified, no content but the asset - name will be returned. - page_size: - The maximum number of assets to be returned in a single - response. Default is 100, minimum is 1, and maximum is 1000. - page_token: - The ``next_page_token`` returned from the previous - ``ListAssetsResponse``, or unspecified for the first - ``ListAssetsRequest``. It is a continuation of a prior - ``ListAssets`` call, and the API should return the next page - of assets. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p5beta1.ListAssetsRequest) - }, -) -_sym_db.RegisterMessage(ListAssetsRequest) - -ListAssetsResponse = _reflection.GeneratedProtocolMessageType( - "ListAssetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTASSETSRESPONSE, - "__module__": "google.cloud.asset_v1p5beta1.proto.asset_service_pb2", - "__doc__": """ListAssets response. - - Attributes: - read_time: - Time the snapshot was taken. - assets: - Assets. - next_page_token: - Token to retrieve the next page of results. Set to empty if - there are no remaining results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p5beta1.ListAssetsResponse) - }, -) -_sym_db.RegisterMessage(ListAssetsResponse) - - -DESCRIPTOR._options = None -_LISTASSETSREQUEST.fields_by_name["parent"]._options = None - -_ASSETSERVICE = _descriptor.ServiceDescriptor( - name="AssetService", - full_name="google.cloud.asset.v1p5beta1.AssetService", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\031cloudasset.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", - create_key=_descriptor._internal_create_key, - serialized_start=732, - serialized_end=979, - methods=[ - _descriptor.MethodDescriptor( - name="ListAssets", - full_name="google.cloud.asset.v1p5beta1.AssetService.ListAssets", - index=0, - containing_service=None, - input_type=_LISTASSETSREQUEST, - output_type=_LISTASSETSRESPONSE, - serialized_options=b"\202\323\344\223\002 \022\036/v1p5beta1/{parent=*/*}/assets", - create_key=_descriptor._internal_create_key, - ) - ], -) -_sym_db.RegisterServiceDescriptor(_ASSETSERVICE) - -DESCRIPTOR.services_by_name["AssetService"] = _ASSETSERVICE - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1p5beta1/proto/asset_service_pb2_grpc.py b/google/cloud/asset_v1p5beta1/proto/asset_service_pb2_grpc.py deleted file mode 100644 index 6c00309e..00000000 --- a/google/cloud/asset_v1p5beta1/proto/asset_service_pb2_grpc.py +++ /dev/null @@ -1,50 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc - -from google.cloud.asset_v1p5beta1.proto import ( - asset_service_pb2 as google_dot_cloud_dot_asset__v1p5beta1_dot_proto_dot_asset__service__pb2, -) - - -class AssetServiceStub(object): - """Asset service definition. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.ListAssets = channel.unary_unary( - "/google.cloud.asset.v1p5beta1.AssetService/ListAssets", - request_serializer=google_dot_cloud_dot_asset__v1p5beta1_dot_proto_dot_asset__service__pb2.ListAssetsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_asset__v1p5beta1_dot_proto_dot_asset__service__pb2.ListAssetsResponse.FromString, - ) - - -class AssetServiceServicer(object): - """Asset service definition. - """ - - def ListAssets(self, request, context): - """Lists assets with time and resource types and returns paged results in - response. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_AssetServiceServicer_to_server(servicer, server): - rpc_method_handlers = { - "ListAssets": grpc.unary_unary_rpc_method_handler( - servicer.ListAssets, - request_deserializer=google_dot_cloud_dot_asset__v1p5beta1_dot_proto_dot_asset__service__pb2.ListAssetsRequest.FromString, - response_serializer=google_dot_cloud_dot_asset__v1p5beta1_dot_proto_dot_asset__service__pb2.ListAssetsResponse.SerializeToString, - ) - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.asset.v1p5beta1.AssetService", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) diff --git a/google/cloud/asset_v1p5beta1/proto/assets_pb2.py b/google/cloud/asset_v1p5beta1/proto/assets_pb2.py deleted file mode 100644 index 75f10fe1..00000000 --- a/google/cloud/asset_v1p5beta1/proto/assets_pb2.py +++ /dev/null @@ -1,534 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/asset_v1p5beta1/proto/assets.proto - -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.orgpolicy.v1 import ( - orgpolicy_pb2 as google_dot_cloud_dot_orgpolicy_dot_v1_dot_orgpolicy__pb2, -) -from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 -from google.identity.accesscontextmanager.v1 import ( - access_level_pb2 as google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__level__pb2, -) -from google.identity.accesscontextmanager.v1 import ( - access_policy_pb2 as google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__policy__pb2, -) -from google.identity.accesscontextmanager.v1 import ( - service_perimeter_pb2 as google_dot_identity_dot_accesscontextmanager_dot_v1_dot_service__perimeter__pb2, -) -from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 -from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/asset_v1p5beta1/proto/assets.proto", - package="google.cloud.asset.v1p5beta1", - syntax="proto3", - serialized_options=b"\n com.google.cloud.asset.v1p5beta1B\nAssetProtoP\001ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p5beta1;asset\370\001\001\252\002\034Google.Cloud.Asset.V1p5Beta1\312\002\034Google\\Cloud\\Asset\\V1p5beta1", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n/google/cloud/asset_v1p5beta1/proto/assets.proto\x12\x1cgoogle.cloud.asset.v1p5beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto\x1a)google/cloud/orgpolicy/v1/orgpolicy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a:google/identity/accesscontextmanager/v1/access_level.proto\x1a;google/identity/accesscontextmanager/v1/access_policy.proto\x1a?google/identity/accesscontextmanager/v1/service_perimeter.proto\x1a\x19google/protobuf/any.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\x90\x04\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\nasset_type\x18\x02 \x01(\t\x12\x38\n\x08resource\x18\x03 \x01(\x0b\x32&.google.cloud.asset.v1p5beta1.Resource\x12)\n\niam_policy\x18\x04 \x01(\x0b\x32\x15.google.iam.v1.Policy\x12\x35\n\norg_policy\x18\x06 \x03(\x0b\x32!.google.cloud.orgpolicy.v1.Policy\x12N\n\raccess_policy\x18\x07 \x01(\x0b\x32\x35.google.identity.accesscontextmanager.v1.AccessPolicyH\x00\x12L\n\x0c\x61\x63\x63\x65ss_level\x18\x08 \x01(\x0b\x32\x34.google.identity.accesscontextmanager.v1.AccessLevelH\x00\x12V\n\x11service_perimeter\x18\t \x01(\x0b\x32\x39.google.identity.accesscontextmanager.v1.ServicePerimeterH\x00\x12\x11\n\tancestors\x18\n \x03(\t:\'\xea\x41$\n\x1f\x63loudasset.googleapis.com/Asset\x12\x01*B\x17\n\x15\x61\x63\x63\x65ss_context_policy"\xa0\x01\n\x08Resource\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x1e\n\x16\x64iscovery_document_uri\x18\x02 \x01(\t\x12\x16\n\x0e\x64iscovery_name\x18\x03 \x01(\t\x12\x14\n\x0cresource_url\x18\x04 \x01(\t\x12\x0e\n\x06parent\x18\x05 \x01(\t\x12%\n\x04\x64\x61ta\x18\x06 \x01(\x0b\x32\x17.google.protobuf.StructB\xb4\x01\n com.google.cloud.asset.v1p5beta1B\nAssetProtoP\x01ZAgoogle.golang.org/genproto/googleapis/cloud/asset/v1p5beta1;asset\xf8\x01\x01\xaa\x02\x1cGoogle.Cloud.Asset.V1p5Beta1\xca\x02\x1cGoogle\\Cloud\\Asset\\V1p5beta1b\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_orgpolicy_dot_v1_dot_orgpolicy__pb2.DESCRIPTOR, - google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR, - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__level__pb2.DESCRIPTOR, - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__policy__pb2.DESCRIPTOR, - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_service__perimeter__pb2.DESCRIPTOR, - google_dot_protobuf_dot_any__pb2.DESCRIPTOR, - google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_ASSET = _descriptor.Descriptor( - name="Asset", - full_name="google.cloud.asset.v1p5beta1.Asset", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.asset.v1p5beta1.Asset.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="asset_type", - full_name="google.cloud.asset.v1p5beta1.Asset.asset_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource", - full_name="google.cloud.asset.v1p5beta1.Asset.resource", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="iam_policy", - full_name="google.cloud.asset.v1p5beta1.Asset.iam_policy", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="org_policy", - full_name="google.cloud.asset.v1p5beta1.Asset.org_policy", - index=4, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="access_policy", - full_name="google.cloud.asset.v1p5beta1.Asset.access_policy", - index=5, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="access_level", - full_name="google.cloud.asset.v1p5beta1.Asset.access_level", - index=6, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="service_perimeter", - full_name="google.cloud.asset.v1p5beta1.Asset.service_perimeter", - index=7, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="ancestors", - full_name="google.cloud.asset.v1p5beta1.Asset.ancestors", - index=8, - number=10, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352A$\n\037cloudasset.googleapis.com/Asset\022\001*", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="access_context_policy", - full_name="google.cloud.asset.v1p5beta1.Asset.access_context_policy", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ) - ], - serialized_start=486, - serialized_end=1014, -) - - -_RESOURCE = _descriptor.Descriptor( - name="Resource", - full_name="google.cloud.asset.v1p5beta1.Resource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="version", - full_name="google.cloud.asset.v1p5beta1.Resource.version", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="discovery_document_uri", - full_name="google.cloud.asset.v1p5beta1.Resource.discovery_document_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="discovery_name", - full_name="google.cloud.asset.v1p5beta1.Resource.discovery_name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="resource_url", - full_name="google.cloud.asset.v1p5beta1.Resource.resource_url", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.asset.v1p5beta1.Resource.parent", - index=4, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="data", - full_name="google.cloud.asset.v1p5beta1.Resource.data", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1017, - serialized_end=1177, -) - -_ASSET.fields_by_name["resource"].message_type = _RESOURCE -_ASSET.fields_by_name[ - "iam_policy" -].message_type = ( - google_dot_iam_dot_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._POLICY -) -_ASSET.fields_by_name[ - "org_policy" -].message_type = google_dot_cloud_dot_orgpolicy_dot_v1_dot_orgpolicy__pb2._POLICY -_ASSET.fields_by_name[ - "access_policy" -].message_type = ( - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__policy__pb2._ACCESSPOLICY -) -_ASSET.fields_by_name[ - "access_level" -].message_type = ( - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_access__level__pb2._ACCESSLEVEL -) -_ASSET.fields_by_name[ - "service_perimeter" -].message_type = ( - google_dot_identity_dot_accesscontextmanager_dot_v1_dot_service__perimeter__pb2._SERVICEPERIMETER -) -_ASSET.oneofs_by_name["access_context_policy"].fields.append( - _ASSET.fields_by_name["access_policy"] -) -_ASSET.fields_by_name["access_policy"].containing_oneof = _ASSET.oneofs_by_name[ - "access_context_policy" -] -_ASSET.oneofs_by_name["access_context_policy"].fields.append( - _ASSET.fields_by_name["access_level"] -) -_ASSET.fields_by_name["access_level"].containing_oneof = _ASSET.oneofs_by_name[ - "access_context_policy" -] -_ASSET.oneofs_by_name["access_context_policy"].fields.append( - _ASSET.fields_by_name["service_perimeter"] -) -_ASSET.fields_by_name["service_perimeter"].containing_oneof = _ASSET.oneofs_by_name[ - "access_context_policy" -] -_RESOURCE.fields_by_name[ - "data" -].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT -DESCRIPTOR.message_types_by_name["Asset"] = _ASSET -DESCRIPTOR.message_types_by_name["Resource"] = _RESOURCE -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Asset = _reflection.GeneratedProtocolMessageType( - "Asset", - (_message.Message,), - { - "DESCRIPTOR": _ASSET, - "__module__": "google.cloud.asset_v1p5beta1.proto.assets_pb2", - "__doc__": """Cloud asset. This includes all Google Cloud Platform resources, Cloud - IAM policies, and other non-GCP assets. - - Attributes: - name: - - The full name of the asset. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See https://cloud.google.com/apis/design/resource_names#full_resource_name - for more information. - asset_type: - Type of the asset. Example: “compute.googleapis.com/Disk”. - resource: - Representation of the resource. - iam_policy: - Representation of the actual Cloud IAM policy set on a cloud - resource. For each resource, there must be at most one Cloud - IAM policy set on it. - org_policy: - Representation of the Cloud Organization Policy set on an - asset. For each asset, there could be multiple Organization - policies with different constraints. - access_context_policy: - Representation of the Cloud Organization access policy. - ancestors: - Asset’s ancestry path in Cloud Resource Manager (CRM) - hierarchy, represented as a list of relative resource names. - Ancestry path starts with the closest CRM ancestor and ends at - root. If the asset is a CRM project/folder/organization, this - starts from the asset itself. Example: [“projects/123456789”, - “folders/5432”, “organizations/1234”] - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p5beta1.Asset) - }, -) -_sym_db.RegisterMessage(Asset) - -Resource = _reflection.GeneratedProtocolMessageType( - "Resource", - (_message.Message,), - { - "DESCRIPTOR": _RESOURCE, - "__module__": "google.cloud.asset_v1p5beta1.proto.assets_pb2", - "__doc__": """Representation of a cloud resource. - - Attributes: - version: - The API version. Example: “v1”. - discovery_document_uri: - The URL of the discovery document containing the resource’s - JSON schema. For example: ``"https://www.googleapis.com/discov - ery/v1/apis/compute/v1/rest"``. It will be left unspecified - for resources without a discovery-based API, such as Cloud - Bigtable. - discovery_name: - The JSON schema name listed in the discovery document. - Example: “Project”. It will be left unspecified for resources - (such as Cloud Bigtable) without a discovery-based API. - resource_url: - The REST URL for accessing the resource. An HTTP GET operation - using this URL returns the resource itself. Example: - ``https://cloudresourcemanager.googleapis.com/v1/projects/my- - project-123``. It will be left unspecified for resources - without a REST API. - parent: - The full name of the immediate parent of this resource. See - `Resource Names `__ for more information. For GCP - assets, it is the parent resource defined in the `Cloud IAM - policy hierarchy `__. For example: ``"//cloudresourcemanager.go - ogleapis.com/projects/my_project_123"``. For third-party - assets, it is up to the users to define. - data: - The content of the resource, in which some sensitive fields - are scrubbed away and may not be present. - """, - # @@protoc_insertion_point(class_scope:google.cloud.asset.v1p5beta1.Resource) - }, -) -_sym_db.RegisterMessage(Resource) - - -DESCRIPTOR._options = None -_ASSET._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/asset_v1p5beta1/proto/assets_pb2_grpc.py b/google/cloud/asset_v1p5beta1/proto/assets_pb2_grpc.py deleted file mode 100644 index 07cb78fe..00000000 --- a/google/cloud/asset_v1p5beta1/proto/assets_pb2_grpc.py +++ /dev/null @@ -1,2 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -import grpc diff --git a/google/cloud/asset_v1p5beta1/py.typed b/google/cloud/asset_v1p5beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/google/cloud/asset_v1p5beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/google/cloud/asset_v1p5beta1/services/__init__.py b/google/cloud/asset_v1p5beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py b/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py new file mode 100644 index 00000000..ec3c27d2 --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient + +__all__ = ( + "AssetServiceClient", + "AssetServiceAsyncClient", +) diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py b/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..cdbd03cd --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.asset_v1p5beta1.services.asset_service import pagers +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets + +from .transports.base import AssetServiceTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = AssetServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(AssetServiceClient).get_transport_class, type(AssetServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = AssetServiceClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def list_assets( + self, + request: asset_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + Args: + request (:class:`~.asset_service.ListAssetsRequest`): + The request object. ListAssets request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListAssetsAsyncPager: + ListAssets response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = asset_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # 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),)), + ) + + # 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.ListAssetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceAsyncClient",) diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/client.py b/google/cloud/asset_v1p5beta1/services/asset_service/client.py new file mode 100644 index 00000000..3fa2a148 --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/asset_service/client.py @@ -0,0 +1,289 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.asset_v1p5beta1.services.asset_service import pagers +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets + +from .transports.base import AssetServiceTransport +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "cloudasset.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the asset service 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 (Union[str, ~.AssetServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, AssetServiceTransport): + # transport is a AssetServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def list_assets( + self, + request: asset_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + Args: + request (:class:`~.asset_service.ListAssetsRequest`): + The request object. ListAssets request. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListAssetsPager: + ListAssets response. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ListAssetsRequest): + request = asset_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_assets] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAssetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("AssetServiceClient",) diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py b/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py new file mode 100644 index 00000000..734e01aa --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.ListAssetsResponse` + 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[..., asset_service.ListAssetsResponse], + request: asset_service.ListAssetsRequest, + response: asset_service.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.asset_service.ListAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[asset_service.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[assets.Asset]: + for page in self.pages: + yield from page.assets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`~.asset_service.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`~.asset_service.ListAssetsResponse` + 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[asset_service.ListAssetsResponse]], + request: asset_service.ListAssetsRequest, + response: asset_service.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.asset_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.asset_service.ListAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = asset_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[asset_service.ListAssetsResponse]: + 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, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[assets.Asset]: + async def async_generator(): + async for page in self.pages: + for response in page.assets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..624eab74 --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry["grpc"] = AssetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + + +__all__ = ( + "AssetServiceTransport", + "AssetServiceGrpcTransport", + "AssetServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..fd85d70b --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing +import pkg_resources + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.asset_v1p5beta1.types import asset_service + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + } + + @property + def list_assets( + self, + ) -> typing.Callable[ + [asset_service.ListAssetsRequest], + typing.Union[ + asset_service.ListAssetsResponse, + typing.Awaitable[asset_service.ListAssetsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("AssetServiceTransport",) diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..656f1944 --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,234 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.asset_v1p5beta1.types import asset_service + +from .base import AssetServiceTransport + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + @classmethod + def create_channel( + cls, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def list_assets( + self, + ) -> Callable[[asset_service.ListAssetsRequest], asset_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists assets with time and resource types and returns + paged results in response. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + 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_assets" not in self._stubs: + self._stubs["list_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p5beta1.AssetService/ListAssets", + request_serializer=asset_service.ListAssetsRequest.serialize, + response_deserializer=asset_service.ListAssetsResponse.deserialize, + ) + return self._stubs["list_assets"] + + +__all__ = ("AssetServiceGrpcTransport",) diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..e3e5ccad --- /dev/null +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,229 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1p5beta1.types import asset_service + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = "cloudasset.googleapis.com", + credentials: 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: + address (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 ignored if ``channel`` 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`. + 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "cloudasset.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` 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 ``channel`` 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def list_assets( + self, + ) -> Callable[ + [asset_service.ListAssetsRequest], Awaitable[asset_service.ListAssetsResponse] + ]: + r"""Return a callable for the list assets method over gRPC. + + Lists assets with time and resource types and returns + paged results in response. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + 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_assets" not in self._stubs: + self._stubs["list_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.asset.v1p5beta1.AssetService/ListAssets", + request_serializer=asset_service.ListAssetsRequest.serialize, + response_deserializer=asset_service.ListAssetsResponse.deserialize, + ) + return self._stubs["list_assets"] + + +__all__ = ("AssetServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/asset_v1p5beta1/types.py b/google/cloud/asset_v1p5beta1/types.py deleted file mode 100644 index fd1222cb..00000000 --- a/google/cloud/asset_v1p5beta1/types.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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 __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.identity.accesscontextmanager.v1 import access_level_pb2 -from google.identity.accesscontextmanager.v1 import access_policy_pb2 -from google.cloud.asset_v1p5beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p5beta1.proto import assets_pb2 -from google.cloud.orgpolicy.v1 import orgpolicy_pb2 -from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 -from google.iam.v1 import policy_pb2 -from google.protobuf import struct_pb2 -from google.protobuf import timestamp_pb2 -from google.type import expr_pb2 - - -_shared_modules = [ - access_level_pb2, - access_policy_pb2, - orgpolicy_pb2, - service_perimeter_pb2, - policy_pb2, - struct_pb2, - timestamp_pb2, - expr_pb2, -] - -_local_modules = [asset_service_pb2, assets_pb2] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.asset_v1p5beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/asset_v1p2beta1/gapic/enums.py b/google/cloud/asset_v1p5beta1/types/__init__.py similarity index 55% rename from google/cloud/asset_v1p2beta1/gapic/enums.py rename to google/cloud/asset_v1p5beta1/types/__init__.py index 2b6e94ce..4f19a666 100644 --- a/google/cloud/asset_v1p2beta1/gapic/enums.py +++ b/google/cloud/asset_v1p5beta1/types/__init__.py @@ -1,34 +1,33 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 # -# https://www.apache.org/licenses/LICENSE-2.0 +# 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. +# -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class ContentType(enum.IntEnum): - """ - Asset content type. +from .assets import ( + Asset, + Resource, +) +from .asset_service import ( + ListAssetsRequest, + ListAssetsResponse, +) - Attributes: - CONTENT_TYPE_UNSPECIFIED (int): Unspecified content type. - RESOURCE (int): Resource metadata. - IAM_POLICY (int): The actual IAM policy set on a resource. - """ - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 +__all__ = ( + "Asset", + "Resource", + "ListAssetsRequest", + "ListAssetsResponse", +) diff --git a/google/cloud/asset_v1p5beta1/types/asset_service.py b/google/cloud/asset_v1p5beta1/types/asset_service.py new file mode 100644 index 00000000..69ae1423 --- /dev/null +++ b/google/cloud/asset_v1p5beta1/types/asset_service.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.asset_v1p5beta1.types import assets as gca_assets +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1p5beta1", + manifest={"ContentType", "ListAssetsRequest", "ListAssetsResponse",}, +) + + +class ContentType(proto.Enum): + r"""Asset content type.""" + CONTENT_TYPE_UNSPECIFIED = 0 + RESOURCE = 1 + IAM_POLICY = 2 + ORG_POLICY = 4 + ACCESS_POLICY = 5 + + +class ListAssetsRequest(proto.Message): + r"""ListAssets request. + + Attributes: + parent (str): + Required. Name of the organization or project the assets + belong to. Format: "organizations/[organization-number]" + (such as "organizations/123"), "projects/[project-number]" + (such as "projects/my-project-id"), or + "projects/[project-id]" (such as "projects/12345"). + read_time (~.timestamp.Timestamp): + Timestamp to take an asset snapshot. This can + only be set to a timestamp between 2018-10-02 + UTC (inclusive) and the current time. If not + specified, the current time will be used. Due to + delays in resource data collection and indexing, + there is a volatile window during which running + the same query may get different results. + asset_types (Sequence[str]): + A list of asset types of which to take a snapshot for. For + example: "compute.googleapis.com/Disk". If specified, only + matching assets will be returned. See `Introduction to Cloud + Asset + Inventory `__ + for all supported asset types. + content_type (~.asset_service.ContentType): + Asset content type. If not specified, no + content but the asset name will be returned. + page_size (int): + The maximum number of assets to be returned + in a single response. Default is 100, minimum is + 1, and maximum is 1000. + page_token (str): + The ``next_page_token`` returned from the previous + ``ListAssetsResponse``, or unspecified for the first + ``ListAssetsRequest``. It is a continuation of a prior + ``ListAssets`` call, and the API should return the next page + of assets. + """ + + parent = proto.Field(proto.STRING, number=1) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + asset_types = proto.RepeatedField(proto.STRING, number=3) + + content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) + + page_size = proto.Field(proto.INT32, number=5) + + page_token = proto.Field(proto.STRING, number=6) + + +class ListAssetsResponse(proto.Message): + r"""ListAssets response. + + Attributes: + read_time (~.timestamp.Timestamp): + Time the snapshot was taken. + assets (Sequence[~.gca_assets.Asset]): + Assets. + next_page_token (str): + Token to retrieve the next page of results. + Set to empty if there are no remaining results. + """ + + @property + def raw_page(self): + return self + + read_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) + + assets = proto.RepeatedField(proto.MESSAGE, number=2, message=gca_assets.Asset,) + + next_page_token = proto.Field(proto.STRING, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p5beta1/types/assets.py b/google/cloud/asset_v1p5beta1/types/assets.py new file mode 100644 index 00000000..dd32160e --- /dev/null +++ b/google/cloud/asset_v1p5beta1/types/assets.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.orgpolicy.v1 import orgpolicy_pb2 as orgpolicy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.identity.accesscontextmanager.v1 import access_level_pb2 as giav_access_level # type: ignore +from google.identity.accesscontextmanager.v1 import access_policy_pb2 as giav_access_policy # type: ignore +from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 as giav_service_perimeter # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.asset.v1p5beta1", manifest={"Asset", "Resource",}, +) + + +class Asset(proto.Message): + r"""Cloud asset. This includes all Google Cloud Platform + resources, Cloud IAM policies, and other non-GCP assets. + + Attributes: + name (str): + The full name of the asset. For example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more information. + asset_type (str): + Type of the asset. Example: + "compute.googleapis.com/Disk". + resource (~.assets.Resource): + Representation of the resource. + iam_policy (~.policy.Policy): + Representation of the actual Cloud IAM policy + set on a cloud resource. For each resource, + there must be at most one Cloud IAM policy set + on it. + org_policy (Sequence[~.orgpolicy.Policy]): + Representation of the Cloud Organization + Policy set on an asset. For each asset, there + could be multiple Organization policies with + different constraints. + access_policy (~.giav_access_policy.AccessPolicy): + + access_level (~.giav_access_level.AccessLevel): + + service_perimeter (~.giav_service_perimeter.ServicePerimeter): + + ancestors (Sequence[str]): + Asset's ancestry path in Cloud Resource Manager (CRM) + hierarchy, represented as a list of relative resource names. + Ancestry path starts with the closest CRM ancestor and ends + at root. If the asset is a CRM project/folder/organization, + this starts from the asset itself. + + Example: ["projects/123456789", "folders/5432", + "organizations/1234"] + """ + + name = proto.Field(proto.STRING, number=1) + + asset_type = proto.Field(proto.STRING, number=2) + + resource = proto.Field(proto.MESSAGE, number=3, message="Resource",) + + iam_policy = proto.Field(proto.MESSAGE, number=4, message=policy.Policy,) + + org_policy = proto.RepeatedField(proto.MESSAGE, number=6, message=orgpolicy.Policy,) + + access_policy = proto.Field( + proto.MESSAGE, + number=7, + oneof="access_context_policy", + message=giav_access_policy.AccessPolicy, + ) + + access_level = proto.Field( + proto.MESSAGE, + number=8, + oneof="access_context_policy", + message=giav_access_level.AccessLevel, + ) + + service_perimeter = proto.Field( + proto.MESSAGE, + number=9, + oneof="access_context_policy", + message=giav_service_perimeter.ServicePerimeter, + ) + + ancestors = proto.RepeatedField(proto.STRING, number=10) + + +class Resource(proto.Message): + r"""Representation of a cloud resource. + + Attributes: + version (str): + The API version. Example: "v1". + discovery_document_uri (str): + The URL of the discovery document containing the resource's + JSON schema. For example: + ``"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"``. + It will be left unspecified for resources without a + discovery-based API, such as Cloud Bigtable. + discovery_name (str): + The JSON schema name listed in the discovery + document. Example: "Project". It will be left + unspecified for resources (such as Cloud + Bigtable) without a discovery-based API. + resource_url (str): + The REST URL for accessing the resource. An HTTP GET + operation using this URL returns the resource itself. + Example: + ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123``. + It will be left unspecified for resources without a REST + API. + parent (str): + The full name of the immediate parent of this resource. See + `Resource + Names `__ + for more information. + + For GCP assets, it is the parent resource defined in the + `Cloud IAM policy + hierarchy `__. + For example: + ``"//cloudresourcemanager.googleapis.com/projects/my_project_123"``. + + For third-party assets, it is up to the users to define. + data (~.struct.Struct): + The content of the resource, in which some + sensitive fields are scrubbed away and may not + be present. + """ + + version = proto.Field(proto.STRING, number=1) + + discovery_document_uri = proto.Field(proto.STRING, number=2) + + discovery_name = proto.Field(proto.STRING, number=3) + + resource_url = proto.Field(proto.STRING, number=4) + + parent = proto.Field(proto.STRING, number=5) + + data = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/noxfile.py b/noxfile.py index ece032ad..be1aee2f 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,8 +27,8 @@ BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -70,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") @@ -77,7 +79,7 @@ def default(session): session.run( "py.test", "--quiet", - "--cov=google.cloud.cloudasset", + "--cov=google.cloud.asset", "--cov=google.cloud", "--cov=tests.unit", "--cov-append", @@ -100,6 +102,10 @@ def system(session): """Run the system test suite.""" system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") @@ -135,7 +141,7 @@ def cover(session): test runs (not system test runs), and then erases coverage data. """ session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=80") + session.run("coverage", "report", "--show-missing", "--fail-under=99") session.run("coverage", "erase") @@ -150,9 +156,42 @@ def docs(session): shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( "sphinx-build", - "-W", # warnings as errors + # "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "alabaster", "recommonmark", "sphinx-docfx-yaml") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", "-T", # show full traceback on exception "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), "-b", "html", "-d", diff --git a/samples/snippets/conftest.py b/samples/snippets/conftest.py new file mode 100644 index 00000000..723827de --- /dev/null +++ b/samples/snippets/conftest.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# +# Copyright 2020 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 os +import uuid + +import backoff +from google.api_core.exceptions import InternalServerError +from google.api_core.exceptions import NotFound +from google.cloud import pubsub_v1 +import pytest + +import quickstart_createfeed +import quickstart_deletefeed + + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] + + +@pytest.fixture(scope="module") +def test_topic(): + topic_id = f"topic-{uuid.uuid4().hex}" + publisher = pubsub_v1.PublisherClient() + topic_path = publisher.topic_path(PROJECT, topic_id) + topic = publisher.create_topic(topic_path) + + yield topic + + publisher.delete_topic(topic_path) + + +@pytest.fixture(scope="module") +def another_topic(): + topic_id = f"topic-{uuid.uuid4().hex}" + publisher = pubsub_v1.PublisherClient() + topic_path = publisher.topic_path(PROJECT, topic_id) + topic = publisher.create_topic(topic_path) + + yield topic + + publisher.delete_topic(topic_path) + + +@pytest.fixture(scope="module") +def test_feed(test_topic): + feed_id = f"feed-{uuid.uuid4().hex}" + asset_name = f"assets-{uuid.uuid4().hex}" + + @backoff.on_exception(backoff.expo, InternalServerError, max_time=60) + def create_feed(): + return quickstart_createfeed.create_feed( + PROJECT, feed_id, [asset_name], test_topic.name + ) + + feed = create_feed() + + yield feed + + try: + quickstart_deletefeed.delete_feed(feed.name) + except NotFound as e: + print(f"Ignoring NotFound: {e}") + + +@pytest.fixture(scope="module") +def deleter(): + feeds_to_delete = [] + + yield feeds_to_delete + + for feed_name in feeds_to_delete: + try: + quickstart_deletefeed.delete_feed(feed_name) + except NotFound as e: + print(f"Ignoring NotFound: {e}") diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py new file mode 100644 index 00000000..5660f08b --- /dev/null +++ b/samples/snippets/noxfile.py @@ -0,0 +1,222 @@ +# Copyright 2019 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 __future__ import print_function + +import os +from pathlib import Path +import sys + +import nox + + +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING +# DO NOT EDIT THIS FILE EVER! +# WARNING - WARNING - WARNING - WARNING - WARNING +# WARNING - WARNING - WARNING - WARNING - WARNING + +# Copy `noxfile_config.py` to your directory and modify it instead. + + +# `TEST_CONFIG` dict is a configuration hook that allows users to +# modify the test configurations. The values here should be in sync +# with `noxfile_config.py`. Users will copy `noxfile_config.py` into +# their directory and modify it. + +TEST_CONFIG = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7"], + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {}, +} + + +try: + # Ensure we can import noxfile_config in the project's directory. + sys.path.append(".") + from noxfile_config import TEST_CONFIG_OVERRIDE +except ImportError as e: + print("No user noxfile_config found: detail: {}".format(e)) + TEST_CONFIG_OVERRIDE = {} + +# Update the TEST_CONFIG with the user supplied values. +TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) + + +def get_pytest_env_vars(): + """Returns a dict for pytest invocation.""" + ret = {} + + # Override the GCLOUD_PROJECT and the alias. + env_key = TEST_CONFIG["gcloud_project_env"] + # This should error out if not set. + ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] + + # Apply user supplied envs. + ret.update(TEST_CONFIG["envs"]) + return ret + + +# DO NOT EDIT - automatically generated. +# All versions used to tested samples. +ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] + +# Any default versions that should be ignored. +IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] + +TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) + +INSTALL_LIBRARY_FROM_SOURCE = bool(os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False)) +# +# Style Checks +# + + +def _determine_local_import_names(start_dir): + """Determines all import names that should be considered "local". + + This is used when running the linter to insure that import order is + properly checked. + """ + file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] + return [ + basename + for basename, extension in file_ext_pairs + if extension == ".py" + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") + ] + + +# Linting with flake8. +# +# We ignore the following rules: +# E203: whitespace before ‘:’ +# E266: too many leading ‘#’ for block comment +# E501: line too long +# I202: Additional newline in a section of imports +# +# We also need to specify the rules which are ignored by default: +# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] +FLAKE8_COMMON_ARGS = [ + "--show-source", + "--builtin=gettext", + "--max-complexity=20", + "--import-order-style=google", + "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", + "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", + "--max-line-length=88", +] + + +@nox.session +def lint(session): + session.install("flake8", "flake8-import-order") + + local_names = _determine_local_import_names(".") + args = FLAKE8_COMMON_ARGS + [ + "--application-import-names", + ",".join(local_names), + ".", + ] + session.run("flake8", *args) + + +# +# Sample Tests +# + + +PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] + + +def _session_tests(session, post_install=None): + """Runs py.test for a particular project.""" + if os.path.exists("requirements.txt"): + session.install("-r", "requirements.txt") + + if os.path.exists("requirements-test.txt"): + session.install("-r", "requirements-test.txt") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # Pytest will return 5 when no tests are collected. This can happen + # on travis where slow and flaky tests are excluded. + # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html + success_codes=[0, 5], + env=get_pytest_env_vars() + ) + + +@nox.session(python=ALL_VERSIONS) +def py(session): + """Runs py.test for a sample using the specified version of Python.""" + if session.python in TESTED_VERSIONS: + _session_tests(session) + else: + session.skip( + "SKIPPED: {} tests are disabled for this sample.".format(session.python) + ) + + +# +# Readmegen +# + + +def _get_repo_root(): + """ Returns the root folder of the project. """ + # Get root of this repository. Assume we don't have directories nested deeper than 10 items. + p = Path(os.getcwd()) + for i in range(10): + if p is None: + break + if Path(p / ".git").exists(): + return str(p) + p = p.parent + raise Exception("Unable to detect repository root.") + + +GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) + + +@nox.session +@nox.parametrize("path", GENERATED_READMES) +def readmegen(session, path): + """(Re-)generates the readme for a sample.""" + session.install("jinja2", "pyyaml") + dir_ = os.path.dirname(path) + + if os.path.exists(os.path.join(dir_, "requirements.txt")): + session.install("-r", os.path.join(dir_, "requirements.txt")) + + in_file = os.path.join(dir_, "README.rst.in") + session.run( + "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file + ) diff --git a/samples/snippets/quickstart_batchgetassetshistory.py b/samples/snippets/quickstart_batchgetassetshistory.py new file mode 100644 index 00000000..3ee70e30 --- /dev/null +++ b/samples/snippets/quickstart_batchgetassetshistory.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# Copyright 2018 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 argparse + + +def batch_get_assets_history(project_id, asset_names): + # [START asset_quickstart_batch_get_assets_history] + from google.cloud import asset_v1 + + # TODO project_id = 'Your Google Cloud Project ID' + # TODO asset_names = 'Your asset names list, e.g.: + # ["//storage.googleapis.com/[BUCKET_NAME]",]' + + client = asset_v1.AssetServiceClient() + parent = "projects/{}".format(project_id) + content_type = asset_v1.ContentType.RESOURCE + read_time_window = asset_v1.TimeWindow() + response = client.batch_get_assets_history( + request={ + "parent": parent, + "asset_names": asset_names, + "content_type": content_type, + "read_time_window": read_time_window, + } + ) + print("assets: {}".format(response.assets)) + # [END asset_quickstart_batch_get_assets_history] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="Your Google Cloud project ID") + parser.add_argument( + "asset_names", + help="The asset names for which history will be fetched, comma " + "delimited, e.g.: //storage.googleapis.com/[BUCKET_NAME]", + ) + + args = parser.parse_args() + + asset_name_list = args.asset_names.split(",") + + batch_get_assets_history(args.project_id, asset_name_list) diff --git a/samples/snippets/quickstart_batchgetassetshistory_test.py b/samples/snippets/quickstart_batchgetassetshistory_test.py new file mode 100644 index 00000000..fd7622c1 --- /dev/null +++ b/samples/snippets/quickstart_batchgetassetshistory_test.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +# Copyright 2018 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 os +import uuid + +import backoff +from google.api_core.exceptions import InvalidArgument +from google.cloud import storage +import pytest + +import quickstart_batchgetassetshistory + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] +BUCKET = "assets-{}".format(uuid.uuid4().hex) + + +@pytest.fixture(scope="module") +def storage_client(): + yield storage.Client() + + +@pytest.fixture(scope="module") +def asset_bucket(storage_client): + bucket = storage_client.create_bucket(BUCKET) + + yield BUCKET + + try: + bucket.delete(force=True) + except Exception as e: + print("Failed to delete bucket{}".format(BUCKET)) + raise e + + +def test_batch_get_assets_history(asset_bucket, capsys): + bucket_asset_name = "//storage.googleapis.com/{}".format(BUCKET) + asset_names = [ + bucket_asset_name, + ] + + @backoff.on_exception(backoff.expo, (AssertionError, InvalidArgument), max_time=30) + def eventually_consistent_test(): + quickstart_batchgetassetshistory.batch_get_assets_history(PROJECT, asset_names) + out, _ = capsys.readouterr() + + assert bucket_asset_name in out + + eventually_consistent_test() diff --git a/samples/snippets/quickstart_createfeed.py b/samples/snippets/quickstart_createfeed.py new file mode 100644 index 00000000..8e592bde --- /dev/null +++ b/samples/snippets/quickstart_createfeed.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# Copyright 2019 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 argparse + + +def create_feed(project_id, feed_id, asset_names, topic): + # [START asset_quickstart_create_feed] + from google.cloud import asset_v1 + + # TODO project_id = 'Your Google Cloud Project ID' + # TODO feed_id = 'Feed ID you want to create' + # TODO asset_names = 'List of asset names the feed listen to' + # TODO topic = "Topic name of the feed" + + client = asset_v1.AssetServiceClient() + parent = "projects/{}".format(project_id) + feed = asset_v1.Feed() + feed.asset_names.extend(asset_names) + feed.feed_output_config.pubsub_destination.topic = topic + response = client.create_feed( + request={"parent": parent, "feed_id": feed_id, "feed": feed} + ) + print("feed: {}".format(response)) + # [END asset_quickstart_create_feed] + return response + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="Your Google Cloud project ID") + parser.add_argument("feed_id", help="Feed ID you want to create") + parser.add_argument("asset_names", help="List of asset names the feed listen to") + parser.add_argument("topic", help="Topic name of the feed") + args = parser.parse_args() + create_feed(args.project_id, args.feed_id, args.asset_names, args.topic) diff --git a/samples/snippets/quickstart_createfeed_test.py b/samples/snippets/quickstart_createfeed_test.py new file mode 100644 index 00000000..d53f11fa --- /dev/null +++ b/samples/snippets/quickstart_createfeed_test.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python + +# Copyright 2018 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 os +import uuid + +import quickstart_createfeed + + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] +ASSET_NAME = "assets-{}".format(uuid.uuid4().hex) +FEED_ID = "feed-{}".format(uuid.uuid4().hex) + + +def test_create_feed(capsys, test_topic, deleter): + feed = quickstart_createfeed.create_feed( + PROJECT, FEED_ID, [ASSET_NAME], test_topic.name + ) + deleter.append(feed.name) + out, _ = capsys.readouterr() + assert "feed" in out diff --git a/samples/snippets/quickstart_deletefeed.py b/samples/snippets/quickstart_deletefeed.py new file mode 100644 index 00000000..9aab5429 --- /dev/null +++ b/samples/snippets/quickstart_deletefeed.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +# Copyright 2018 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 argparse + + +def delete_feed(feed_name): + # [START asset_quickstart_delete_feed] + from google.cloud import asset_v1 + + # TODO feed_name = 'Feed name you want to delete' + + client = asset_v1.AssetServiceClient() + client.delete_feed(request={"name": feed_name}) + print("deleted_feed") + # [END asset_quickstart_delete_feed] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("feed_name", help="Feed name you want to delete") + args = parser.parse_args() + delete_feed(args.feed_name) diff --git a/samples/snippets/quickstart_deletefeed_test.py b/samples/snippets/quickstart_deletefeed_test.py new file mode 100644 index 00000000..3c5a113a --- /dev/null +++ b/samples/snippets/quickstart_deletefeed_test.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python + +# Copyright 2018 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 os + +import quickstart_deletefeed + + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_delete_feed(capsys, test_feed): + + quickstart_deletefeed.delete_feed(test_feed.name) + + out, _ = capsys.readouterr() + assert "deleted_feed" in out diff --git a/samples/snippets/quickstart_exportassets.py b/samples/snippets/quickstart_exportassets.py new file mode 100644 index 00000000..f9784a90 --- /dev/null +++ b/samples/snippets/quickstart_exportassets.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python + +# Copyright 2018 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 argparse + + +def export_assets(project_id, dump_file_path): + # [START asset_quickstart_export_assets] + from google.cloud import asset_v1 + + # TODO project_id = 'Your Google Cloud Project ID' + # TODO dump_file_path = 'Your asset dump file path' + + client = asset_v1.AssetServiceClient() + parent = "projects/{}".format(project_id) + output_config = asset_v1.OutputConfig() + output_config.gcs_destination.uri = dump_file_path + response = client.export_assets( + request={"parent": parent, "output_config": output_config} + ) + print(response.result()) + # [END asset_quickstart_export_assets] + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="Your Google Cloud project ID") + parser.add_argument( + "dump_file_path", + help="The file ExportAssets API will dump assets to, " + "e.g.: gs:///asset_dump_file", + ) + + args = parser.parse_args() + + export_assets(args.project_id, args.dump_file_path) diff --git a/samples/snippets/quickstart_exportassets_test.py b/samples/snippets/quickstart_exportassets_test.py new file mode 100644 index 00000000..9c03d5d5 --- /dev/null +++ b/samples/snippets/quickstart_exportassets_test.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# Copyright 2018 Google LLC. All Rights Reserved. +# +# 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 os +import uuid + +from google.cloud import storage +import pytest + +import quickstart_exportassets + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] +BUCKET = "assets-{}".format(uuid.uuid4().hex) + + +@pytest.fixture(scope="module") +def storage_client(): + yield storage.Client() + + +@pytest.fixture(scope="module") +def asset_bucket(storage_client): + bucket = storage_client.create_bucket(BUCKET) + + yield BUCKET + + try: + bucket.delete(force=True) + except Exception as e: + print("Failed to delete bucket{}".format(BUCKET)) + raise e + + +def test_export_assets(asset_bucket, capsys): + dump_file_path = "gs://{}/assets-dump.txt".format(asset_bucket) + quickstart_exportassets.export_assets(PROJECT, dump_file_path) + out, _ = capsys.readouterr() + + assert dump_file_path in out diff --git a/samples/snippets/quickstart_getfeed.py b/samples/snippets/quickstart_getfeed.py new file mode 100644 index 00000000..aebe7621 --- /dev/null +++ b/samples/snippets/quickstart_getfeed.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +# Copyright 2018 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 argparse + + +def get_feed(feed_name): + # [START asset_quickstart_get_feed] + from google.cloud import asset_v1 + + # TODO feed_name = 'Feed Name you want to get' + + client = asset_v1.AssetServiceClient() + response = client.get_feed(request={"name": feed_name}) + print("gotten_feed: {}".format(response)) + # [START asset_quickstart_get_feed] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("feed_name", help="Feed Name you want to get") + args = parser.parse_args() + get_feed(args.feed_name) diff --git a/samples/snippets/quickstart_getfeed_test.py b/samples/snippets/quickstart_getfeed_test.py new file mode 100644 index 00000000..dd2a92bd --- /dev/null +++ b/samples/snippets/quickstart_getfeed_test.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +# Copyright 2018 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 quickstart_getfeed + + +def test_get_feed(capsys, test_feed): + quickstart_getfeed.get_feed(test_feed.name) + out, _ = capsys.readouterr() + + assert "gotten_feed" in out diff --git a/samples/snippets/quickstart_listassets.py b/samples/snippets/quickstart_listassets.py new file mode 100644 index 00000000..9c5e191a --- /dev/null +++ b/samples/snippets/quickstart_listassets.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python + +# Copyright 2020 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 argparse + + +def list_assets(project_id, asset_types, page_size): + # [START asset_quickstart_list_assets] + from google.cloud import asset_v1p5beta1 + + # TODO project_id = 'Your Google Cloud Project ID' + # TODO asset_types = 'Your asset type list, e.g., + # ["storage.googleapis.com/Bucket","bigquery.googleapis.com/Table"]' + # TODO page_size = 'Num of assets in one page, which must be between 1 and + # 1000 (both inclusively)' + + project_resource = "projects/{}".format(project_id) + content_type = asset_v1p5beta1.ContentType.RESOURCE + client = asset_v1p5beta1.AssetServiceClient() + + # Call ListAssets v1p5beta1 to list assets. + response = client.list_assets( + request={ + "parent": project_resource, + "read_time": None, + "asset_types": asset_types, + "content_type": content_type, + "page_size": page_size, + } + ) + + for asset in response: + print(asset) + # [END asset_quickstart_list_assets] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("project_id", help="Your Google Cloud project ID") + parser.add_argument( + "asset_types", + help="The types of the assets to list, comma delimited, e.g., " + "storage.googleapis.com/Bucket", + ) + parser.add_argument( + "page_size", + help="Num of assets in one page, which must be between 1 and 1000 " + "(both inclusively)", + ) + + args = parser.parse_args() + + asset_type_list = args.asset_types.split(",") + + list_assets(args.project_id, asset_type_list, int(args.page_size)) diff --git a/samples/snippets/quickstart_listassets_test.py b/samples/snippets/quickstart_listassets_test.py new file mode 100644 index 00000000..da3f56a0 --- /dev/null +++ b/samples/snippets/quickstart_listassets_test.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +# Copyright 2020 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 os + +import quickstart_listassets + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_list_assets(capsys): + quickstart_listassets.list_assets( + project_id=PROJECT, asset_types=["iam.googleapis.com/Role"], page_size=10 + ) + out, _ = capsys.readouterr() + assert "asset" in out diff --git a/samples/snippets/quickstart_listfeeds.py b/samples/snippets/quickstart_listfeeds.py new file mode 100644 index 00000000..c432d358 --- /dev/null +++ b/samples/snippets/quickstart_listfeeds.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python + +# Copyright 2018 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 argparse + + +def list_feeds(parent_resource): + # [START asset_quickstart_list_feeds] + from google.cloud import asset_v1 + + # TODO parent_resource = 'Parent resource you want to list all feeds' + + client = asset_v1.AssetServiceClient() + response = client.list_feeds(request={"parent": parent_resource}) + print("feeds: {}".format(response.feeds)) + # [END asset_quickstart_list_feeds] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument( + "parent_resource", help="Parent resource you want to list all feeds" + ) + args = parser.parse_args() + list_feeds(args.parent_resource) diff --git a/samples/snippets/quickstart_listfeeds_test.py b/samples/snippets/quickstart_listfeeds_test.py new file mode 100644 index 00000000..19c44297 --- /dev/null +++ b/samples/snippets/quickstart_listfeeds_test.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python + +# Copyright 2018 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 os + +import quickstart_listfeeds + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_list_feeds(capsys): + parent_resource = "projects/{}".format(PROJECT) + quickstart_listfeeds.list_feeds(parent_resource) + out, _ = capsys.readouterr() + assert "feeds" in out diff --git a/samples/snippets/quickstart_searchalliampolicies.py b/samples/snippets/quickstart_searchalliampolicies.py new file mode 100644 index 00000000..3782ebb6 --- /dev/null +++ b/samples/snippets/quickstart_searchalliampolicies.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python + +# Copyright 2020 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 argparse + + +def search_all_iam_policies(scope, query=None, page_size=None): + # [START asset_quickstart_search_all_iam_policies] + from google.cloud import asset_v1 + + # TODO scope = 'Scope of the search' + # TODO query = 'Query statement' + # TODO page_size = Size of each result page + + client = asset_v1.AssetServiceClient() + response = client.search_all_iam_policies( + request={"scope": scope, "query": query, "page_size": page_size} + ) + for policy in response: + print(policy) + break + # [END asset_quickstart_search_all_iam_policies] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument( + "scope", help="The search is limited to the resources within the scope." + ) + parser.add_argument("--query", help="The query statement.") + parser.add_argument( + "--page_size", type=int, help="The page size for search result pagination." + ) + args = parser.parse_args() + search_all_iam_policies(args.scope, args.query, args.page_size) diff --git a/samples/snippets/quickstart_searchalliampolicies_test.py b/samples/snippets/quickstart_searchalliampolicies_test.py new file mode 100644 index 00000000..c9d313ea --- /dev/null +++ b/samples/snippets/quickstart_searchalliampolicies_test.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +# Copyright 2020 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 os + +import quickstart_searchalliampolicies + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] + + +def test_search_all_iam_policies(capsys): + scope = "projects/{}".format(PROJECT) + query = "policy:roles/owner" + quickstart_searchalliampolicies.search_all_iam_policies(scope, query=query) + out, _ = capsys.readouterr() + assert "roles/owner" in out diff --git a/samples/snippets/quickstart_searchallresources.py b/samples/snippets/quickstart_searchallresources.py new file mode 100644 index 00000000..afecca7b --- /dev/null +++ b/samples/snippets/quickstart_searchallresources.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python + +# Copyright 2020 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 argparse + + +def search_all_resources( + scope, query=None, asset_types=None, page_size=None, order_by=None +): + # [START asset_quickstart_search_all_resources] + from google.cloud import asset_v1 + + # TODO scope = 'Scope of the search' + # TODO query = 'Query statement' + # TODO asset_types = 'List of asset types to search for' + # TODO page_size = Size of each result page + # TODO order_by = 'Fields to sort the results' + + client = asset_v1.AssetServiceClient() + response = client.search_all_resources( + request={ + "scope": scope, + "query": query, + "asset_types": asset_types, + "page_size": page_size, + "order_by": order_by, + } + ) + for resource in response: + print(resource) + break + # [END asset_quickstart_search_all_resources] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument( + "scope", help="The search is limited to the resources within the scope." + ) + parser.add_argument("--query", help="The query statement.") + parser.add_argument( + "--asset_types", nargs="+", help="A list of asset types to search for." + ) + parser.add_argument( + "--page_size", type=int, help="The page size for search result pagination." + ) + parser.add_argument( + "--order_by", help="Fields specifying the sorting order of the results." + ) + args = parser.parse_args() + search_all_resources( + args.scope, args.query, args.asset_types, args.page_size, args.order_by + ) diff --git a/samples/snippets/quickstart_searchallresources_test.py b/samples/snippets/quickstart_searchallresources_test.py new file mode 100644 index 00000000..e594a72a --- /dev/null +++ b/samples/snippets/quickstart_searchallresources_test.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +# Copyright 2020 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 os +import uuid + +import backoff +from google.api_core.exceptions import NotFound +from google.cloud import bigquery +import pytest + +import quickstart_searchallresources + +PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] +DATASET = "dataset_{}".format(uuid.uuid4().hex) + + +@pytest.fixture(scope="module") +def bigquery_client(): + yield bigquery.Client() + + +@pytest.fixture(scope="module") +def asset_dataset(bigquery_client): + dataset = bigquery_client.create_dataset(DATASET) + + yield DATASET + + try: + bigquery_client.delete_dataset(dataset) + except NotFound as e: + print("Failed to delete dataset {}".format(DATASET)) + raise e + + +def test_search_all_resources(asset_dataset, capsys): + scope = "projects/{}".format(PROJECT) + query = "name:{}".format(DATASET) + + # Dataset creation takes some time to propagate, so the dataset is not + # immediately searchable. Need some time before the snippet will pass. + @backoff.on_exception(backoff.expo, (AssertionError), max_time=120) + def eventually_consistent_test(): + quickstart_searchallresources.search_all_resources(scope, query=query) + out, _ = capsys.readouterr() + + assert DATASET in out + + eventually_consistent_test() diff --git a/samples/snippets/quickstart_updatefeed.py b/samples/snippets/quickstart_updatefeed.py new file mode 100644 index 00000000..3ad638ec --- /dev/null +++ b/samples/snippets/quickstart_updatefeed.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +# Copyright 2018 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 argparse + + +def update_feed(feed_name, topic): + # [START asset_quickstart_update_feed] + from google.cloud import asset_v1 + from google.protobuf import field_mask_pb2 + + # TODO feed_name = 'Feed Name you want to update' + # TODO topic = "Topic name you want to update with" + + client = asset_v1.AssetServiceClient() + feed = asset_v1.Feed() + feed.name = feed_name + feed.feed_output_config.pubsub_destination.topic = topic + update_mask = field_mask_pb2.FieldMask() + # In this example, we update topic of the feed + update_mask.paths.append("feed_output_config.pubsub_destination.topic") + response = client.update_feed(request={"feed": feed, "update_mask": update_mask}) + print("updated_feed: {}".format(response)) + # [END asset_quickstart_update_feed] + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("feed_name", help="Feed Name you want to update") + parser.add_argument("topic", help="Topic name you want to update with") + args = parser.parse_args() + update_feed(args.feed_name, args.topic) diff --git a/samples/snippets/quickstart_updatefeed_test.py b/samples/snippets/quickstart_updatefeed_test.py new file mode 100644 index 00000000..e09cb191 --- /dev/null +++ b/samples/snippets/quickstart_updatefeed_test.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python + +# Copyright 2018 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 quickstart_updatefeed + + +def test_update_feed(capsys, test_feed, another_topic): + quickstart_updatefeed.update_feed(test_feed.name, another_topic.name) + out, _ = capsys.readouterr() + + assert "updated_feed" in out diff --git a/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt new file mode 100644 index 00000000..678aa129 --- /dev/null +++ b/samples/snippets/requirements-test.txt @@ -0,0 +1,2 @@ +backoff==1.10.0 +pytest==5.4.3 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt new file mode 100644 index 00000000..9623430a --- /dev/null +++ b/samples/snippets/requirements.txt @@ -0,0 +1,5 @@ +google-cloud-storage==1.29.0 +google-cloud-asset==1.3.0 +google-cloud-resource-manager==0.30.2 +google-cloud-pubsub==1.7.0 +google-cloud-bigquery==1.25.0 diff --git a/scripts/fixup_asset_v1_keywords.py b/scripts/fixup_asset_v1_keywords.py new file mode 100644 index 00000000..8c525868 --- /dev/null +++ b/scripts/fixup_asset_v1_keywords.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_get_assets_history': ('parent', 'asset_names', 'content_type', 'read_time_window', ), + 'create_feed': ('parent', 'feed_id', 'feed', ), + 'delete_feed': ('name', ), + 'export_assets': ('parent', 'output_config', 'read_time', 'asset_types', 'content_type', ), + 'get_feed': ('name', ), + 'list_feeds': ('parent', ), + 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), + 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', ), + 'update_feed': ('feed', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=assetCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the asset client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_asset_v1beta1_keywords.py b/scripts/fixup_asset_v1beta1_keywords.py new file mode 100644 index 00000000..f53578bc --- /dev/null +++ b/scripts/fixup_asset_v1beta1_keywords.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_get_assets_history': ('parent', 'asset_names', 'content_type', 'read_time_window', ), + 'export_assets': ('parent', 'output_config', 'read_time', 'asset_types', 'content_type', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=assetCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the asset client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_asset_v1p1beta1_keywords.py b/scripts/fixup_asset_v1p1beta1_keywords.py new file mode 100644 index 00000000..d15e8ce8 --- /dev/null +++ b/scripts/fixup_asset_v1p1beta1_keywords.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), + 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=assetCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the asset client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_asset_v1p2beta1_keywords.py b/scripts/fixup_asset_v1p2beta1_keywords.py new file mode 100644 index 00000000..edf8be71 --- /dev/null +++ b/scripts/fixup_asset_v1p2beta1_keywords.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_feed': ('parent', 'feed_id', 'feed', ), + 'delete_feed': ('name', ), + 'get_feed': ('name', ), + 'list_feeds': ('parent', ), + 'update_feed': ('feed', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=assetCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the asset client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_asset_v1p4beta1_keywords.py b/scripts/fixup_asset_v1p4beta1_keywords.py new file mode 100644 index 00000000..a422fe32 --- /dev/null +++ b/scripts/fixup_asset_v1p4beta1_keywords.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'analyze_iam_policy': ('analysis_query', 'options', ), + 'export_iam_policy_analysis': ('analysis_query', 'output_config', 'options', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=assetCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the asset client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_asset_v1p5beta1_keywords.py b/scripts/fixup_asset_v1p5beta1_keywords.py new file mode 100644 index 00000000..da88d60e --- /dev/null +++ b/scripts/fixup_asset_v1p5beta1_keywords.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=assetCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the asset client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index 2b74c3a7..e9191326 100644 --- a/setup.py +++ b/setup.py @@ -21,18 +21,19 @@ name = "google-cloud-asset" description = "Cloud Asset API API client library" -version = "1.3.0" +version = "2.0.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.14.0, < 2.0.0dev", - 'enum34; python_version < "3.4"', + "google-api-core[grpc] >= 1.22.0, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", "google-cloud-access-context-manager >= 0.1.2, < 0.2.0dev", "google-cloud-org-policy >= 0.1.2, < 0.2.0dev", + "proto-plus >= 0.4.0", + "libcst >= 0.2.5", ] # Setup boilerplate below this line. @@ -46,7 +47,9 @@ # Only include packages under the 'google' namespace. Do not include tests, # benchmarks, etc. packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] # Determine which namespaces are needed. @@ -68,12 +71,10 @@ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -81,7 +82,15 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", + scripts=[ + "scripts/fixup_asset_v1_keywords.py", + "scripts/fixup_asset_v1beta1_keywords.py", + "scripts/fixup_asset_v1p1beta1_keywords.py", + "scripts/fixup_asset_v1p2beta1_keywords.py", + "scripts/fixup_asset_v1p4beta1_keywords.py", + "scripts/fixup_asset_v1p5beta1_keywords.py", + ], include_package_data=True, zip_safe=False, ) diff --git a/synth.metadata b/synth.metadata index 8ed80398..a221182d 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,22 @@ { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-asset.git", - "sha": "f786ab34a70355da4d6714e2313932840033d30e" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "b882b8e6bfcd708042ff00f7adc67ce750817dd0", - "internalRef": "318028816" + "remote": "https://github.com/googleapis/python-asset.git", + "sha": "741d0bfc5b162a8a467ce030f910a800f43c56f6" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "db4f15fedc76e04018e6e43ec403e804e1142158" + "sha": "f1d8e6619ca2b9ebbc68c13af4ec5dba2803fc44" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "db4f15fedc76e04018e6e43ec403e804e1142158" + "sha": "f1d8e6619ca2b9ebbc68c13af4ec5dba2803fc44" } } ], diff --git a/synth.py b/synth.py index 6b1d01e4..573a946f 100644 --- a/synth.py +++ b/synth.py @@ -16,6 +16,7 @@ import synthtool as s from synthtool import gcp +from synthtool.languages import python gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() @@ -35,146 +36,33 @@ s.move(library, excludes=excludes) -s.replace( - "google/cloud/asset_v*/proto/assets_pb2.py", - "from google.iam.v1 import policy_pb2 as", - "from google.iam.v1 import iam_policy_pb2_grpc as", -) - -s.replace( - "google/cloud/asset_v*/proto/assets_pb2.py", - "from google.iam.v1 import iam_policy_pb2_grpc " - "as google_dot_iam_dot_v1_dot_policy__pb2", - "from google.iam.v1 import iam_policy_pb2 " - "as google_dot_iam_dot_v1_dot_policy__pb2", -) - -s.replace( - "google/cloud/asset_v*/proto/assets_pb2.py", - "_ASSET\.fields_by_name\['iam_policy'\]\.message_type " - "= google_dot_iam_dot_v1_dot_policy__pb2\._POLICY", - "_ASSET.fields_by_name['iam_policy'].message_type = google_dot_iam_dot" - "_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._POLICY", -) - -s.replace( - "google/cloud/asset_v*/proto/assets_pb2.py", - "_IAMPOLICYSEARCHRESULT\.fields_by_name\['policy'\]\.message_type " - "= google_dot_iam_dot_v1_dot_policy__pb2\._POLICY", - "_IAMPOLICYSEARCHRESULT.fields_by_name['policy'].message_type = google_dot_iam_dot" - "_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._POLICY", -) - -s.replace( - "google/cloud/asset_v*/proto/assets_pb2.py", - "_IAMPOLICYANALYSISRESULT\.fields_by_name\['iam_binding'\]\.message_type " - "= google_dot_iam_dot_v1_dot_policy__pb2\._BINDING", - "_IAMPOLICYANALYSISRESULT.fields_by_name['iam_binding'].message_type = google_dot_iam_dot" - "_v1_dot_policy__pb2.google_dot_iam_dot_v1_dot_policy__pb2._BINDING", +# ---------------------------------------------------------------------------- +# Add templated files +# ---------------------------------------------------------------------------- +templated_files = common.py_library( + samples=True, # set to True only if there are samples + microgenerator=True, + cov_level=99, ) +s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file -_BORKED_ASSET_DOCSTRING = """\ - The full name of the asset. For example: ``//compute.googleapi - s.com/projects/my_project_123/zones/zone1/instances/instance1` - `. See `Resource Names `__ for more information. -""" - -_FIXED_ASSET_DOCSTRING = """ - The full name of the asset. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See https://cloud.google.com/apis/design/resource_names#full_resource_name - for more information. -""" - -s.replace( - "google/cloud/asset_v*/proto/assets_pb2.py", - _BORKED_ASSET_DOCSTRING, - _FIXED_ASSET_DOCSTRING, -) +# ---------------------------------------------------------------------------- +# Samples templates +# ---------------------------------------------------------------------------- -s.replace( - "google/cloud/**/asset_service_client.py", - "google-cloud-cloudasset", - "google-cloud-asset", -) -# Fix docstrings with no summary line -s.replace( - "google/cloud/**/proto/*_pb2.py", - r''''__doc__': """Attributes:''', - ''''__doc__' : """ - Attributes:''', -) +python.py_samples(skip_readmes=True) -# Fix accesscontextmanager and orgpolicy imports -s.replace( - "google/cloud/asset_v*/types.py", - "from google\.cloud\.asset_(v.*)\.proto import ((access_level_pb2)|(service_perimeter_pb2)|(access_policy_pb2))", - "from google.identity.accesscontextmanager.v1 import \g<2>", -) +# TODO(busunkim): Use latest sphinx after microgenerator transition +s.replace("noxfile.py", '''["']sphinx["']''', '"sphinx<3.0.0"') s.replace( - "google/cloud/asset_v*/types.py", - "from google\.cloud\.asset_v.*\.proto import orgpolicy_pb2", - "from google.cloud.orgpolicy.v1 import orgpolicy_pb2", + "noxfile.py", + "google.cloud.cloudasset", + "google.cloud.asset", ) -# Glue in Project Path Method. -# TODO: Remove during microgenerator transition -count = s.replace( - [ - "google/cloud/asset_v1/gapic/asset_service_client.py", - "google/cloud/asset_v1beta1/gapic/asset_service_client.py", - ], - "(def __init__\()", - '''@classmethod - def project_path(cls, project): - """Return a fully-qualified project string.""" - return google.api_core.path_template.expand( - "projects/{project}", project=project - ) - \g<1>''', -) -if count != 2: - raise Exception("``project_path`` method not added.") - -# Keep same parameter order to avoid breaking existing calls -# Not re-ordering the docstring as that is more likely to break -# TODO: Remove during microgenerator transition -count = s.replace( - [ - "google/cloud/asset_v1/gapic/asset_service_client.py", - "google/cloud/asset_v1beta1/gapic/asset_service_client.py", - ], - """def batch_get_assets_history\( - self, - parent, - asset_names=None, - content_type=None, - read_time_window=None, - retry=google\.api_core\.gapic_v1\.method\.DEFAULT, - timeout=google\.api_core\.gapic_v1\.method\.DEFAULT, - metadata=None\):""", - """def batch_get_assets_history( - self, - parent, - content_type=None, - read_time_window=None, - asset_names=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None):""", -) -if count != 2: - raise Exception("Parameter order replace not made.") - -# ---------------------------------------------------------------------------- -# Add templated files -# ---------------------------------------------------------------------------- -templated_files = gcp.CommonTemplates().py_library(unit_cov_level=79, cov_level=80, samples=False) -s.move(templated_files) - -# TODO(busunkim): Use latest sphinx after microgenerator transition -s.replace("noxfile.py", '''["']sphinx["']''', '"sphinx<3.0.0"') +# Temporarily disable warnings due to +# https://github.com/googleapis/gapic-generator-python/issues/525 +s.replace("noxfile.py", '[\"\']-W[\"\']', '# "-W"') s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/tests/system/test_vpcsc.py b/tests/system/test_vpcsc.py index bfe9f824..02256baa 100644 --- a/tests/system/test_vpcsc.py +++ b/tests/system/test_vpcsc.py @@ -21,7 +21,6 @@ from google.api_core import exceptions from google.cloud import asset_v1 -from google.cloud.asset_v1 import enums from test_utils.vpcsc_config import vpcsc_config _VPCSC_PROHIBITED_MESSAGE = "Request is prohibited by organization's policy" @@ -51,13 +50,17 @@ def parent_outside(): @vpcsc_config.skip_unless_inside_vpcsc def test_export_assets_inside(client, output_config, parent_inside): with pytest.raises(exceptions.InvalidArgument): - client.export_assets(parent_inside, output_config) + client.export_assets( + request={"parent": parent_inside, "output_config": output_config} + ) @vpcsc_config.skip_unless_inside_vpcsc def test_export_assets_outside(client, output_config, parent_outside): with pytest.raises(exceptions.PermissionDenied) as exc: - client.export_assets(parent_outside, output_config) + client.export_assets( + request={"parent": parent_outside, "output_config": output_config} + ) assert _VPCSC_PROHIBITED_MESSAGE in exc.value.message @@ -66,21 +69,25 @@ def test_export_assets_outside(client, output_config, parent_outside): def test_batch_get_assets_history_inside(client, parent_inside): read_time_window = {} client.batch_get_assets_history( - parent_inside, - content_type=enums.ContentType.CONTENT_TYPE_UNSPECIFIED, - read_time_window={}, + request={ + "parent": parent_inside, + "asset_names": asset_v1.ContentType.CONTENT_TYPE_UNSPECIFIED, + "content_type": {}, + } ) @vpcsc_config.skip_unless_inside_vpcsc def test_batch_get_assets_history_outside(client, parent_outside): - content_type = enums.ContentType.CONTENT_TYPE_UNSPECIFIED + content_type = asset_v1.ContentType.CONTENT_TYPE_UNSPECIFIED read_time_window = {} with pytest.raises(exceptions.PermissionDenied) as exc: client.batch_get_assets_history( - parent_outside, - content_type=enums.ContentType.CONTENT_TYPE_UNSPECIFIED, - read_time_window={}, + request={ + "parent": parent_outside, + "asset_names": asset_v1.ContentType.CONTENT_TYPE_UNSPECIFIED, + "content_type": {}, + } ) assert _VPCSC_PROHIBITED_MESSAGE in exc.value.message diff --git a/tests/unit/gapic/asset_v1/__init__.py b/tests/unit/gapic/asset_v1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/asset_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/asset_v1/test_asset_service.py b/tests/unit/gapic/asset_v1/test_asset_service.py new file mode 100644 index 00000000..c2134e90 --- /dev/null +++ b/tests/unit/gapic/asset_v1/test_asset_service.py @@ -0,0 +1,2711 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.asset_v1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1.services.asset_service import pagers +from google.cloud.asset_v1.services.asset_service import transports +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AssetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient]) +def test_asset_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + assert transport == transports.AssetServiceGrpcTransport + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient) +) +@mock.patch.object( + AssetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AssetServiceAsyncClient), +) +def test_asset_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_asset_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.asset_v1.services.asset_service.transports.AssetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_export_assets( + transport: str = "grpc", request_type=asset_service.ExportAssetsRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.export_assets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.ExportAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_assets_from_dict(): + test_export_assets(request_type=dict) + + +@pytest.mark.asyncio +async def test_export_assets_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.ExportAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.export_assets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_assets_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ExportAssetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.export_assets), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_export_assets_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ExportAssetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.export_assets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_batch_get_assets_history( + transport: str = "grpc", request_type=asset_service.BatchGetAssetsHistoryRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_get_assets_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.BatchGetAssetsHistoryResponse() + + response = client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.BatchGetAssetsHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) + + +def test_batch_get_assets_history_from_dict(): + test_batch_get_assets_history(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_get_assets_history_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.BatchGetAssetsHistoryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_get_assets_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.BatchGetAssetsHistoryResponse() + ) + + response = await client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) + + +def test_batch_get_assets_history_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.BatchGetAssetsHistoryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_get_assets_history), "__call__" + ) as call: + call.return_value = asset_service.BatchGetAssetsHistoryResponse() + + client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_get_assets_history_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.BatchGetAssetsHistoryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_get_assets_history), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.BatchGetAssetsHistoryResponse() + ) + + await client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_feed( + transport: str = "grpc", request_type=asset_service.CreateFeedRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + + response = client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.CreateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_create_feed_from_dict(): + test_create_feed(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_feed_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.CreateFeedRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + ) + + response = await client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_create_feed_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateFeedRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_feed), "__call__") as call: + call.return_value = asset_service.Feed() + + client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_feed_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateFeedRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_feed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + + await client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_feed_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_feed(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_create_feed_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_feed( + asset_service.CreateFeedRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_create_feed_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_feed(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_create_feed_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_feed( + asset_service.CreateFeedRequest(), parent="parent_value", + ) + + +def test_get_feed(transport: str = "grpc", request_type=asset_service.GetFeedRequest): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + + response = client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.GetFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_get_feed_from_dict(): + test_get_feed(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_feed_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.GetFeedRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + ) + + response = await client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_get_feed_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetFeedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_feed), "__call__") as call: + call.return_value = asset_service.Feed() + + client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_feed_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetFeedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_feed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + + await client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_feed_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_feed(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_feed_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_feed( + asset_service.GetFeedRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_feed_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_feed(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_feed_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_feed( + asset_service.GetFeedRequest(), name="name_value", + ) + + +def test_list_feeds( + transport: str = "grpc", request_type=asset_service.ListFeedsRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_feeds), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + + response = client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.ListFeedsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +def test_list_feeds_from_dict(): + test_list_feeds(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_feeds_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.ListFeedsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_feeds), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.ListFeedsResponse() + ) + + response = await client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +def test_list_feeds_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListFeedsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_feeds), "__call__") as call: + call.return_value = asset_service.ListFeedsResponse() + + client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_feeds_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListFeedsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_feeds), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.ListFeedsResponse() + ) + + await client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_feeds_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_feeds), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_feeds(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_feeds_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_feeds( + asset_service.ListFeedsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_feeds_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_feeds), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.ListFeedsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_feeds(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_feeds_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_feeds( + asset_service.ListFeedsRequest(), parent="parent_value", + ) + + +def test_update_feed( + transport: str = "grpc", request_type=asset_service.UpdateFeedRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + + response = client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.UpdateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_update_feed_from_dict(): + test_update_feed(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_feed_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.UpdateFeedRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + ) + + response = await client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_update_feed_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateFeedRequest() + request.feed.name = "feed.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_feed), "__call__") as call: + call.return_value = asset_service.Feed() + + client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "feed.name=feed.name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_feed_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateFeedRequest() + request.feed.name = "feed.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_feed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + + await client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "feed.name=feed.name/value",) in kw["metadata"] + + +def test_update_feed_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_feed(feed=asset_service.Feed(name="name_value"),) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].feed == asset_service.Feed(name="name_value") + + +def test_update_feed_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_update_feed_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_feed(feed=asset_service.Feed(name="name_value"),) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].feed == asset_service.Feed(name="name_value") + + +@pytest.mark.asyncio +async def test_update_feed_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name="name_value"), + ) + + +def test_delete_feed( + transport: str = "grpc", request_type=asset_service.DeleteFeedRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.DeleteFeedRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_feed_from_dict(): + test_delete_feed(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_feed_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.DeleteFeedRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_feed_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteFeedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_feed), "__call__") as call: + call.return_value = None + + client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_feed_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteFeedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_feed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_feed_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_feed(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_feed_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_feed( + asset_service.DeleteFeedRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_feed_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_feed(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_feed_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_feed( + asset_service.DeleteFeedRequest(), name="name_value", + ) + + +def test_search_all_resources( + transport: str = "grpc", request_type=asset_service.SearchAllResourcesRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse( + next_page_token="next_page_token_value", + ) + + response = client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.SearchAllResourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_resources_from_dict(): + test_search_all_resources(request_type=dict) + + +@pytest.mark.asyncio +async def test_search_all_resources_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.SearchAllResourcesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_resources_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllResourcesRequest() + request.scope = "scope/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + call.return_value = asset_service.SearchAllResourcesResponse() + + client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "scope=scope/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_search_all_resources_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllResourcesRequest() + request.scope = "scope/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllResourcesResponse() + ) + + await client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "scope=scope/value",) in kw["metadata"] + + +def test_search_all_resources_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_all_resources( + scope="scope_value", query="query_value", asset_types=["asset_types_value"], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].scope == "scope_value" + + assert args[0].query == "query_value" + + assert args[0].asset_types == ["asset_types_value"] + + +def test_search_all_resources_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope="scope_value", + query="query_value", + asset_types=["asset_types_value"], + ) + + +@pytest.mark.asyncio +async def test_search_all_resources_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_all_resources( + scope="scope_value", query="query_value", asset_types=["asset_types_value"], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].scope == "scope_value" + + assert args[0].query == "query_value" + + assert args[0].asset_types == ["asset_types_value"] + + +@pytest.mark.asyncio +async def test_search_all_resources_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope="scope_value", + query="query_value", + asset_types=["asset_types_value"], + ) + + +def test_search_all_resources_pager(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllResourcesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.ResourceSearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.ResourceSearchResult(), assets.ResourceSearchResult(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", ""),)), + ) + pager = client.search_all_resources(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.ResourceSearchResult) for i in results) + + +def test_search_all_resources_pages(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllResourcesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.ResourceSearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.ResourceSearchResult(), assets.ResourceSearchResult(),], + ), + RuntimeError, + ) + pages = list(client.search_all_resources(request={}).pages) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_search_all_resources_async_pager(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllResourcesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.ResourceSearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.ResourceSearchResult(), assets.ResourceSearchResult(),], + ), + RuntimeError, + ) + async_pager = await client.search_all_resources(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, assets.ResourceSearchResult) for i in responses) + + +@pytest.mark.asyncio +async def test_search_all_resources_async_pages(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllResourcesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.ResourceSearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.ResourceSearchResult(), assets.ResourceSearchResult(),], + ), + RuntimeError, + ) + pages = [] + async for page in (await client.search_all_resources(request={})).pages: + pages.append(page) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +def test_search_all_iam_policies( + transport: str = "grpc", request_type=asset_service.SearchAllIamPoliciesRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse( + next_page_token="next_page_token_value", + ) + + response = client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.SearchAllIamPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_iam_policies_from_dict(): + test_search_all_iam_policies(request_type=dict) + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.SearchAllIamPoliciesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllIamPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_iam_policies_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllIamPoliciesRequest() + request.scope = "scope/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + call.return_value = asset_service.SearchAllIamPoliciesResponse() + + client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "scope=scope/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllIamPoliciesRequest() + request.scope = "scope/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllIamPoliciesResponse() + ) + + await client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "scope=scope/value",) in kw["metadata"] + + +def test_search_all_iam_policies_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_all_iam_policies( + scope="scope_value", query="query_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].scope == "scope_value" + + assert args[0].query == "query_value" + + +def test_search_all_iam_policies_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope="scope_value", + query="query_value", + ) + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllIamPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_all_iam_policies( + scope="scope_value", query="query_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].scope == "scope_value" + + assert args[0].query == "query_value" + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope="scope_value", + query="query_value", + ) + + +def test_search_all_iam_policies_pager(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[assets.IamPolicySearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", ""),)), + ) + pager = client.search_all_iam_policies(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) for i in results) + + +def test_search_all_iam_policies_pages(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[assets.IamPolicySearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search_all_iam_policies(request={}).pages) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async_pager(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[assets.IamPolicySearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_all_iam_policies(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) for i in responses) + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async_pages(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[assets.IamPolicySearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page in (await client.search_all_iam_policies(request={})).pages: + pages.append(page) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.AssetServiceGrpcTransport,) + + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.asset_v1.services.asset_service.transports.AssetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "export_assets", + "batch_get_assets_history", + "create_feed", + "get_feed", + "list_feeds", + "update_feed", + "delete_feed", + "search_all_resources", + "search_all_iam_policies", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_asset_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_asset_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_host_no_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:8000" + + +def test_asset_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_asset_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_asset_service_grpc_lro_client(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_asset_service_grpc_lro_async_client(): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_feed_path(): + project = "squid" + feed = "clam" + + expected = "projects/{project}/feeds/{feed}".format(project=project, feed=feed,) + actual = AssetServiceClient.feed_path(project, feed) + assert expected == actual + + +def test_parse_feed_path(): + expected = { + "project": "whelk", + "feed": "octopus", + } + path = AssetServiceClient.feed_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_feed_path(path) + assert expected == actual diff --git a/tests/unit/gapic/asset_v1beta1/__init__.py b/tests/unit/gapic/asset_v1beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/asset_v1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/asset_v1beta1/test_asset_service.py b/tests/unit/gapic/asset_v1beta1/test_asset_service.py new file mode 100644 index 00000000..5318fbfe --- /dev/null +++ b/tests/unit/gapic/asset_v1beta1/test_asset_service.py @@ -0,0 +1,946 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.asset_v1beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1beta1.services.asset_service import transports +from google.cloud.asset_v1beta1.types import asset_service +from google.cloud.asset_v1beta1.types import assets +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AssetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient]) +def test_asset_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + assert transport == transports.AssetServiceGrpcTransport + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient) +) +@mock.patch.object( + AssetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AssetServiceAsyncClient), +) +def test_asset_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_asset_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.asset_v1beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_export_assets( + transport: str = "grpc", request_type=asset_service.ExportAssetsRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.export_assets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.ExportAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_assets_from_dict(): + test_export_assets(request_type=dict) + + +@pytest.mark.asyncio +async def test_export_assets_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.ExportAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.export_assets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_assets_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ExportAssetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.export_assets), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_export_assets_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ExportAssetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.export_assets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_batch_get_assets_history( + transport: str = "grpc", request_type=asset_service.BatchGetAssetsHistoryRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_get_assets_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.BatchGetAssetsHistoryResponse() + + response = client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.BatchGetAssetsHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) + + +def test_batch_get_assets_history_from_dict(): + test_batch_get_assets_history(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_get_assets_history_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.BatchGetAssetsHistoryRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_get_assets_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.BatchGetAssetsHistoryResponse() + ) + + response = await client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) + + +def test_batch_get_assets_history_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.BatchGetAssetsHistoryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_get_assets_history), "__call__" + ) as call: + call.return_value = asset_service.BatchGetAssetsHistoryResponse() + + client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_get_assets_history_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.BatchGetAssetsHistoryRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_get_assets_history), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.BatchGetAssetsHistoryResponse() + ) + + await client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.AssetServiceGrpcTransport,) + + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.asset_v1beta1.services.asset_service.transports.AssetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "export_assets", + "batch_get_assets_history", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_asset_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.asset_v1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_asset_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_host_no_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:8000" + + +def test_asset_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_asset_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_asset_service_grpc_lro_client(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_asset_service_grpc_lro_async_client(): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client diff --git a/tests/unit/gapic/asset_v1p1beta1/__init__.py b/tests/unit/gapic/asset_v1p1beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/asset_v1p1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py new file mode 100644 index 00000000..7168899e --- /dev/null +++ b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py @@ -0,0 +1,1436 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.asset_v1p1beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1p1beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1p1beta1.services.asset_service import pagers +from google.cloud.asset_v1p1beta1.services.asset_service import transports +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets +from google.oauth2 import service_account + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AssetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient]) +def test_asset_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + assert transport == transports.AssetServiceGrpcTransport + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient) +) +@mock.patch.object( + AssetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AssetServiceAsyncClient), +) +def test_asset_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_asset_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_search_all_resources( + transport: str = "grpc", request_type=asset_service.SearchAllResourcesRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse( + next_page_token="next_page_token_value", + ) + + response = client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.SearchAllResourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_resources_from_dict(): + test_search_all_resources(request_type=dict) + + +@pytest.mark.asyncio +async def test_search_all_resources_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.SearchAllResourcesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_resources_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllResourcesRequest() + request.scope = "scope/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + call.return_value = asset_service.SearchAllResourcesResponse() + + client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "scope=scope/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_search_all_resources_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllResourcesRequest() + request.scope = "scope/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllResourcesResponse() + ) + + await client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "scope=scope/value",) in kw["metadata"] + + +def test_search_all_resources_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_all_resources( + scope="scope_value", query="query_value", asset_types=["asset_types_value"], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].scope == "scope_value" + + assert args[0].query == "query_value" + + assert args[0].asset_types == ["asset_types_value"] + + +def test_search_all_resources_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope="scope_value", + query="query_value", + asset_types=["asset_types_value"], + ) + + +@pytest.mark.asyncio +async def test_search_all_resources_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_all_resources( + scope="scope_value", query="query_value", asset_types=["asset_types_value"], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].scope == "scope_value" + + assert args[0].query == "query_value" + + assert args[0].asset_types == ["asset_types_value"] + + +@pytest.mark.asyncio +async def test_search_all_resources_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope="scope_value", + query="query_value", + asset_types=["asset_types_value"], + ) + + +def test_search_all_resources_pager(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token="abc", + ), + asset_service.SearchAllResourcesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.StandardResourceMetadata(),], next_page_token="ghi", + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", ""),)), + ) + pager = client.search_all_resources(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.StandardResourceMetadata) for i in results) + + +def test_search_all_resources_pages(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token="abc", + ), + asset_service.SearchAllResourcesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.StandardResourceMetadata(),], next_page_token="ghi", + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + RuntimeError, + ) + pages = list(client.search_all_resources(request={}).pages) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_search_all_resources_async_pager(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token="abc", + ), + asset_service.SearchAllResourcesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.StandardResourceMetadata(),], next_page_token="ghi", + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_all_resources(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, assets.StandardResourceMetadata) for i in responses) + + +@pytest.mark.asyncio +async def test_search_all_resources_async_pages(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token="abc", + ), + asset_service.SearchAllResourcesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllResourcesResponse( + results=[assets.StandardResourceMetadata(),], next_page_token="ghi", + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + RuntimeError, + ) + pages = [] + async for page in (await client.search_all_resources(request={})).pages: + pages.append(page) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +def test_search_all_iam_policies( + transport: str = "grpc", request_type=asset_service.SearchAllIamPoliciesRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse( + next_page_token="next_page_token_value", + ) + + response = client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.SearchAllIamPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_iam_policies_from_dict(): + test_search_all_iam_policies(request_type=dict) + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.SearchAllIamPoliciesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllIamPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_iam_policies_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllIamPoliciesRequest() + request.scope = "scope/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + call.return_value = asset_service.SearchAllIamPoliciesResponse() + + client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "scope=scope/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllIamPoliciesRequest() + request.scope = "scope/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllIamPoliciesResponse() + ) + + await client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "scope=scope/value",) in kw["metadata"] + + +def test_search_all_iam_policies_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_all_iam_policies( + scope="scope_value", query="query_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].scope == "scope_value" + + assert args[0].query == "query_value" + + +def test_search_all_iam_policies_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope="scope_value", + query="query_value", + ) + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.SearchAllIamPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_all_iam_policies( + scope="scope_value", query="query_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].scope == "scope_value" + + assert args[0].query == "query_value" + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope="scope_value", + query="query_value", + ) + + +def test_search_all_iam_policies_pager(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[assets.IamPolicySearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("scope", ""),)), + ) + pager = client.search_all_iam_policies(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) for i in results) + + +def test_search_all_iam_policies_pages(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.search_all_iam_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[assets.IamPolicySearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search_all_iam_policies(request={}).pages) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async_pager(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[assets.IamPolicySearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_all_iam_policies(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) for i in responses) + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async_pages(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.search_all_iam_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token="abc", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], next_page_token="def", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[assets.IamPolicySearchResult(),], next_page_token="ghi", + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + async for page in (await client.search_all_iam_policies(request={})).pages: + pages.append(page) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.AssetServiceGrpcTransport,) + + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "search_all_resources", + "search_all_iam_policies", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_asset_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_asset_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_host_no_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:8000" + + +def test_asset_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_asset_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/gapic/asset_v1p2beta1/__init__.py b/tests/unit/gapic/asset_v1p2beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/asset_v1p2beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py new file mode 100644 index 00000000..609c3fbd --- /dev/null +++ b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py @@ -0,0 +1,1683 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.asset_v1p2beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1p2beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1p2beta1.services.asset_service import transports +from google.cloud.asset_v1p2beta1.types import asset_service +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AssetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient]) +def test_asset_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + assert transport == transports.AssetServiceGrpcTransport + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient) +) +@mock.patch.object( + AssetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AssetServiceAsyncClient), +) +def test_asset_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_asset_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_create_feed( + transport: str = "grpc", request_type=asset_service.CreateFeedRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + + response = client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.CreateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_create_feed_from_dict(): + test_create_feed(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_feed_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.CreateFeedRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + ) + + response = await client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_create_feed_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateFeedRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_feed), "__call__") as call: + call.return_value = asset_service.Feed() + + client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_feed_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateFeedRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_feed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + + await client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_feed_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_feed(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_create_feed_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_feed( + asset_service.CreateFeedRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_create_feed_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_feed(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_create_feed_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_feed( + asset_service.CreateFeedRequest(), parent="parent_value", + ) + + +def test_get_feed(transport: str = "grpc", request_type=asset_service.GetFeedRequest): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + + response = client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.GetFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_get_feed_from_dict(): + test_get_feed(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_feed_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.GetFeedRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + ) + + response = await client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_get_feed_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetFeedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_feed), "__call__") as call: + call.return_value = asset_service.Feed() + + client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_feed_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetFeedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_feed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + + await client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_feed_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_feed(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_feed_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_feed( + asset_service.GetFeedRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_feed_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_feed(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_feed_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_feed( + asset_service.GetFeedRequest(), name="name_value", + ) + + +def test_list_feeds( + transport: str = "grpc", request_type=asset_service.ListFeedsRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_feeds), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + + response = client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.ListFeedsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +def test_list_feeds_from_dict(): + test_list_feeds(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_feeds_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.ListFeedsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_feeds), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.ListFeedsResponse() + ) + + response = await client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +def test_list_feeds_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListFeedsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_feeds), "__call__") as call: + call.return_value = asset_service.ListFeedsResponse() + + client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_feeds_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListFeedsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_feeds), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.ListFeedsResponse() + ) + + await client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_feeds_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_feeds), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_feeds(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_feeds_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_feeds( + asset_service.ListFeedsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_feeds_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_feeds), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.ListFeedsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_feeds(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_feeds_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_feeds( + asset_service.ListFeedsRequest(), parent="parent_value", + ) + + +def test_update_feed( + transport: str = "grpc", request_type=asset_service.UpdateFeedRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + + response = client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.UpdateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_update_feed_from_dict(): + test_update_feed(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_feed_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.UpdateFeedRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.Feed( + name="name_value", + asset_names=["asset_names_value"], + asset_types=["asset_types_value"], + content_type=asset_service.ContentType.RESOURCE, + ) + ) + + response = await client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + + assert response.name == "name_value" + + assert response.asset_names == ["asset_names_value"] + + assert response.asset_types == ["asset_types_value"] + + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_update_feed_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateFeedRequest() + request.feed.name = "feed.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_feed), "__call__") as call: + call.return_value = asset_service.Feed() + + client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "feed.name=feed.name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_feed_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateFeedRequest() + request.feed.name = "feed.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_feed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + + await client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "feed.name=feed.name/value",) in kw["metadata"] + + +def test_update_feed_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_feed(feed=asset_service.Feed(name="name_value"),) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].feed == asset_service.Feed(name="name_value") + + +def test_update_feed_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_update_feed_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_feed(feed=asset_service.Feed(name="name_value"),) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].feed == asset_service.Feed(name="name_value") + + +@pytest.mark.asyncio +async def test_update_feed_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name="name_value"), + ) + + +def test_delete_feed( + transport: str = "grpc", request_type=asset_service.DeleteFeedRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.DeleteFeedRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_feed_from_dict(): + test_delete_feed(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_feed_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.DeleteFeedRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_feed_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteFeedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_feed), "__call__") as call: + call.return_value = None + + client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_feed_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteFeedRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_feed), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_feed_flattened(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_feed), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_feed(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_feed_flattened_error(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_feed( + asset_service.DeleteFeedRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_feed_flattened_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_feed), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_feed(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_feed_flattened_error_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_feed( + asset_service.DeleteFeedRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.AssetServiceGrpcTransport,) + + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_feed", + "get_feed", + "list_feeds", + "update_feed", + "delete_feed", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_asset_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_asset_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_host_no_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:8000" + + +def test_asset_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_asset_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_feed_path(): + project = "squid" + feed = "clam" + + expected = "projects/{project}/feeds/{feed}".format(project=project, feed=feed,) + actual = AssetServiceClient.feed_path(project, feed) + assert expected == actual + + +def test_parse_feed_path(): + expected = { + "project": "whelk", + "feed": "octopus", + } + path = AssetServiceClient.feed_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_feed_path(path) + assert expected == actual diff --git a/tests/unit/gapic/asset_v1p4beta1/__init__.py b/tests/unit/gapic/asset_v1p4beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/asset_v1p4beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py new file mode 100644 index 00000000..dd659ade --- /dev/null +++ b/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py @@ -0,0 +1,966 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1p4beta1.services.asset_service import transports +from google.cloud.asset_v1p4beta1.types import asset_service +from google.cloud.asset_v1p4beta1.types import assets +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 as duration # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AssetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient]) +def test_asset_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + assert transport == transports.AssetServiceGrpcTransport + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient) +) +@mock.patch.object( + AssetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AssetServiceAsyncClient), +) +def test_asset_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_asset_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.asset_v1p4beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_analyze_iam_policy( + transport: str = "grpc", request_type=asset_service.AnalyzeIamPolicyRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.analyze_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeIamPolicyResponse(fully_explored=True,) + + response = client.analyze_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.AnalyzeIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) + + assert response.fully_explored is True + + +def test_analyze_iam_policy_from_dict(): + test_analyze_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_analyze_iam_policy_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.AnalyzeIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.analyze_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.AnalyzeIamPolicyResponse(fully_explored=True,) + ) + + response = await client.analyze_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) + + assert response.fully_explored is True + + +def test_analyze_iam_policy_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeIamPolicyRequest() + request.analysis_query.parent = "analysis_query.parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.analyze_iam_policy), "__call__" + ) as call: + call.return_value = asset_service.AnalyzeIamPolicyResponse() + + client.analyze_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "analysis_query.parent=analysis_query.parent/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_analyze_iam_policy_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeIamPolicyRequest() + request.analysis_query.parent = "analysis_query.parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.analyze_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.AnalyzeIamPolicyResponse() + ) + + await client.analyze_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "analysis_query.parent=analysis_query.parent/value", + ) in kw["metadata"] + + +def test_export_iam_policy_analysis( + transport: str = "grpc", request_type=asset_service.ExportIamPolicyAnalysisRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.export_iam_policy_analysis), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.export_iam_policy_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.ExportIamPolicyAnalysisRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_iam_policy_analysis_from_dict(): + test_export_iam_policy_analysis(request_type=dict) + + +@pytest.mark.asyncio +async def test_export_iam_policy_analysis_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.ExportIamPolicyAnalysisRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.export_iam_policy_analysis), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.export_iam_policy_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_iam_policy_analysis_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ExportIamPolicyAnalysisRequest() + request.analysis_query.parent = "analysis_query.parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.export_iam_policy_analysis), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.export_iam_policy_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "analysis_query.parent=analysis_query.parent/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_export_iam_policy_analysis_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ExportIamPolicyAnalysisRequest() + request.analysis_query.parent = "analysis_query.parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.export_iam_policy_analysis), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.export_iam_policy_analysis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "analysis_query.parent=analysis_query.parent/value", + ) in kw["metadata"] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.AssetServiceGrpcTransport,) + + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.asset_v1p4beta1.services.asset_service.transports.AssetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "analyze_iam_policy", + "export_iam_policy_analysis", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_asset_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.asset_v1p4beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_asset_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_host_no_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:8000" + + +def test_asset_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_asset_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_asset_service_grpc_lro_client(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_asset_service_grpc_lro_async_client(): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client diff --git a/tests/unit/gapic/asset_v1p5beta1/__init__.py b/tests/unit/gapic/asset_v1p5beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/asset_v1p5beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py new file mode 100644 index 00000000..1dd05d29 --- /dev/null +++ b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py @@ -0,0 +1,914 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.asset_v1p5beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1p5beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1p5beta1.services.asset_service import pagers +from google.cloud.asset_v1p5beta1.services.asset_service import transports +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AssetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient]) +def test_asset_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + assert transport == transports.AssetServiceGrpcTransport + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient) +) +@mock.patch.object( + AssetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AssetServiceAsyncClient), +) +def test_asset_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=client_cert_source_callback, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", and default_client_cert_source is provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is + # "auto", but client_cert_source and default_client_cert_source are None. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "auto"}): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + ( + AssetServiceAsyncClient, + transports.AssetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_asset_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + api_mtls_endpoint=client.DEFAULT_ENDPOINT, + client_cert_source=None, + quota_project_id=None, + ) + + +def test_asset_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + api_mtls_endpoint="squid.clam.whelk", + client_cert_source=None, + quota_project_id=None, + ) + + +def test_list_assets( + transport: str = "grpc", request_type=asset_service.ListAssetsRequest +): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_assets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListAssetsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == asset_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_assets_from_dict(): + test_list_assets(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = "grpc_asyncio"): + client = AssetServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = asset_service.ListAssetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_assets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.ListAssetsResponse(next_page_token="next_page_token_value",) + ) + + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_assets_field_headers(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListAssetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_assets), "__call__") as call: + call.return_value = asset_service.ListAssetsResponse() + + client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_assets_field_headers_async(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListAssetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_assets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + asset_service.ListAssetsResponse() + ) + + await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_assets_pager(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_assets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[assets.Asset(), assets.Asset(), assets.Asset(),], + next_page_token="abc", + ), + asset_service.ListAssetsResponse(assets=[], next_page_token="def",), + asset_service.ListAssetsResponse( + assets=[assets.Asset(),], next_page_token="ghi", + ), + asset_service.ListAssetsResponse(assets=[assets.Asset(), assets.Asset(),],), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_assets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.Asset) for i in results) + + +def test_list_assets_pages(): + client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_assets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[assets.Asset(), assets.Asset(), assets.Asset(),], + next_page_token="abc", + ), + asset_service.ListAssetsResponse(assets=[], next_page_token="def",), + asset_service.ListAssetsResponse( + assets=[assets.Asset(),], next_page_token="ghi", + ), + asset_service.ListAssetsResponse(assets=[assets.Asset(), assets.Asset(),],), + RuntimeError, + ) + pages = list(client.list_assets(request={}).pages) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_assets_async_pager(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_assets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[assets.Asset(), assets.Asset(), assets.Asset(),], + next_page_token="abc", + ), + asset_service.ListAssetsResponse(assets=[], next_page_token="def",), + asset_service.ListAssetsResponse( + assets=[assets.Asset(),], next_page_token="ghi", + ), + asset_service.ListAssetsResponse(assets=[assets.Asset(), assets.Asset(),],), + RuntimeError, + ) + async_pager = await client.list_assets(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, assets.Asset) for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_assets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[assets.Asset(), assets.Asset(), assets.Asset(),], + next_page_token="abc", + ), + asset_service.ListAssetsResponse(assets=[], next_page_token="def",), + asset_service.ListAssetsResponse( + assets=[assets.Asset(),], next_page_token="ghi", + ), + asset_service.ListAssetsResponse(assets=[assets.Asset(), assets.Asset(),],), + RuntimeError, + ) + pages = [] + async for page in (await client.list_assets(request={})).pages: + pages.append(page) + for page, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.AssetServiceGrpcTransport,) + + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("list_assets",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_asset_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_asset_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_asset_service_host_no_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:443" + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="cloudasset.googleapis.com:8000" + ), + ) + assert client._transport._host == "cloudasset.googleapis.com:8000" + + +def test_asset_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +def test_asset_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that if channel is provided, mtls endpoint and client_cert_source + # won't be used. + callback = mock.MagicMock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=callback, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert not callback.called + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@mock.patch("grpc.ssl_channel_credentials", autospec=True) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_client_cert_source( + grpc_create_channel, grpc_ssl_channel_cred +): + # Check that if channel is None, but api_mtls_endpoint and client_cert_source + # are provided, then a mTLS channel will be created. + mock_cred = mock.Mock() + + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) +def test_asset_service_grpc_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] +) +@mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) +def test_asset_service_grpc_asyncio_transport_channel_mtls_with_adc( + grpc_create_channel, api_mtls_endpoint +): + # Check that if channel and client_cert_source are None, but api_mtls_endpoint + # is provided, then a mTLS channel will be created with SSL ADC. + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + # Mock google.auth.transport.grpc.SslCredentials class. + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + mock_cred = mock.Mock() + transport = transports.AssetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint=api_mtls_endpoint, + client_cert_source=None, + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/gapic/v1/test_asset_service_client_v1.py b/tests/unit/gapic/v1/test_asset_service_client_v1.py deleted file mode 100644 index 3902d2a6..00000000 --- a/tests/unit/gapic/v1/test_asset_service_client_v1.py +++ /dev/null @@ -1,442 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import asset_v1 -from google.cloud.asset_v1.proto import asset_service_pb2 -from google.cloud.asset_v1.proto import assets_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestAssetServiceClient(object): - def test_export_assets(self): - # Setup Expected Response - expected_response = {} - expected_response = asset_service_pb2.ExportAssetsResponse(**expected_response) - operation = operations_pb2.Operation( - name="operations/test_export_assets", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - output_config = {} - - response = client.export_assets(parent, output_config) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.ExportAssetsRequest( - parent=parent, output_config=output_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_export_assets_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_export_assets_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - output_config = {} - - response = client.export_assets(parent, output_config) - exception = response.exception() - assert exception.errors[0] == error - - def test_batch_get_assets_history(self): - # Setup Expected Response - expected_response = {} - expected_response = asset_service_pb2.BatchGetAssetsHistoryResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - - response = client.batch_get_assets_history(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.BatchGetAssetsHistoryRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_get_assets_history_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup request - parent = "parent-995424086" - - with pytest.raises(CustomException): - client.batch_get_assets_history(parent) - - def test_create_feed(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = asset_service_pb2.Feed(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - feed_id = "feedId-976011428" - feed = {} - - response = client.create_feed(parent, feed_id, feed) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.CreateFeedRequest( - parent=parent, feed_id=feed_id, feed=feed - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_feed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup request - parent = "parent-995424086" - feed_id = "feedId-976011428" - feed = {} - - with pytest.raises(CustomException): - client.create_feed(parent, feed_id, feed) - - def test_get_feed(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = asset_service_pb2.Feed(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - name = "name3373707" - - response = client.get_feed(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.GetFeedRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_feed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup request - name = "name3373707" - - with pytest.raises(CustomException): - client.get_feed(name) - - def test_list_feeds(self): - # Setup Expected Response - expected_response = {} - expected_response = asset_service_pb2.ListFeedsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - - response = client.list_feeds(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.ListFeedsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_feeds_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup request - parent = "parent-995424086" - - with pytest.raises(CustomException): - client.list_feeds(parent) - - def test_update_feed(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = asset_service_pb2.Feed(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - feed = {} - update_mask = {} - - response = client.update_feed(feed, update_mask) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.UpdateFeedRequest( - feed=feed, update_mask=update_mask - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_feed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup request - feed = {} - update_mask = {} - - with pytest.raises(CustomException): - client.update_feed(feed, update_mask) - - def test_delete_feed(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - name = "name3373707" - - client.delete_feed(name) - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.DeleteFeedRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_feed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup request - name = "name3373707" - - with pytest.raises(CustomException): - client.delete_feed(name) - - def test_search_all_resources(self): - # Setup Expected Response - next_page_token = "" - results_element = {} - results = [results_element] - expected_response = {"next_page_token": next_page_token, "results": results} - expected_response = asset_service_pb2.SearchAllResourcesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - scope = "scope109264468" - - paged_list_response = client.search_all_resources(scope) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.SearchAllResourcesRequest(scope=scope) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_search_all_resources_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup request - scope = "scope109264468" - - paged_list_response = client.search_all_resources(scope) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_search_all_iam_policies(self): - # Setup Expected Response - next_page_token = "" - results_element = {} - results = [results_element] - expected_response = {"next_page_token": next_page_token, "results": results} - expected_response = asset_service_pb2.SearchAllIamPoliciesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup Request - scope = "scope109264468" - - paged_list_response = client.search_all_iam_policies(scope) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.SearchAllIamPoliciesRequest(scope=scope) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_search_all_iam_policies_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1.AssetServiceClient() - - # Setup request - scope = "scope109264468" - - paged_list_response = client.search_all_iam_policies(scope) - with pytest.raises(CustomException): - list(paged_list_response) diff --git a/tests/unit/gapic/v1beta1/test_asset_service_client_v1beta1.py b/tests/unit/gapic/v1beta1/test_asset_service_client_v1beta1.py deleted file mode 100644 index 1876a3c6..00000000 --- a/tests/unit/gapic/v1beta1/test_asset_service_client_v1beta1.py +++ /dev/null @@ -1,157 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import asset_v1beta1 -from google.cloud.asset_v1beta1.proto import asset_service_pb2 -from google.longrunning import operations_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestAssetServiceClient(object): - def test_export_assets(self): - # Setup Expected Response - expected_response = {} - expected_response = asset_service_pb2.ExportAssetsResponse(**expected_response) - operation = operations_pb2.Operation( - name="operations/test_export_assets", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1beta1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - output_config = {} - - response = client.export_assets(parent, output_config) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.ExportAssetsRequest( - parent=parent, output_config=output_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_export_assets_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_export_assets_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1beta1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - output_config = {} - - response = client.export_assets(parent, output_config) - exception = response.exception() - assert exception.errors[0] == error - - def test_batch_get_assets_history(self): - # Setup Expected Response - expected_response = {} - expected_response = asset_service_pb2.BatchGetAssetsHistoryResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1beta1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - - response = client.batch_get_assets_history(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.BatchGetAssetsHistoryRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_get_assets_history_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1beta1.AssetServiceClient() - - # Setup request - parent = "parent-995424086" - - with pytest.raises(CustomException): - client.batch_get_assets_history(parent) diff --git a/tests/unit/gapic/v1p1beta1/test_asset_service_client_v1p1beta1.py b/tests/unit/gapic/v1p1beta1/test_asset_service_client_v1p1beta1.py deleted file mode 100644 index 8cecd6eb..00000000 --- a/tests/unit/gapic/v1p1beta1/test_asset_service_client_v1p1beta1.py +++ /dev/null @@ -1,152 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import asset_v1p1beta1 -from google.cloud.asset_v1p1beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p1beta1.proto import assets_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestAssetServiceClient(object): - def test_search_all_resources(self): - # Setup Expected Response - next_page_token = "" - results_element = {} - results = [results_element] - expected_response = {"next_page_token": next_page_token, "results": results} - expected_response = asset_service_pb2.SearchAllResourcesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p1beta1.AssetServiceClient() - - # Setup Request - scope = "scope109264468" - - paged_list_response = client.search_all_resources(scope) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.SearchAllResourcesRequest(scope=scope) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_search_all_resources_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p1beta1.AssetServiceClient() - - # Setup request - scope = "scope109264468" - - paged_list_response = client.search_all_resources(scope) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_search_all_iam_policies(self): - # Setup Expected Response - next_page_token = "" - results_element = {} - results = [results_element] - expected_response = {"next_page_token": next_page_token, "results": results} - expected_response = asset_service_pb2.SearchAllIamPoliciesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p1beta1.AssetServiceClient() - - # Setup Request - scope = "scope109264468" - - paged_list_response = client.search_all_iam_policies(scope) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.SearchAllIamPoliciesRequest(scope=scope) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_search_all_iam_policies_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p1beta1.AssetServiceClient() - - # Setup request - scope = "scope109264468" - - paged_list_response = client.search_all_iam_policies(scope) - with pytest.raises(CustomException): - list(paged_list_response) diff --git a/tests/unit/gapic/v1p2beta1/test_asset_service_client_v1p2beta1.py b/tests/unit/gapic/v1p2beta1/test_asset_service_client_v1p2beta1.py deleted file mode 100644 index 16b62bae..00000000 --- a/tests/unit/gapic/v1p2beta1/test_asset_service_client_v1p2beta1.py +++ /dev/null @@ -1,255 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import asset_v1p2beta1 -from google.cloud.asset_v1p2beta1.proto import asset_service_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestAssetServiceClient(object): - def test_delete_feed(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup Request - name = "name3373707" - - client.delete_feed(name) - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.DeleteFeedRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_feed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup request - name = "name3373707" - - with pytest.raises(CustomException): - client.delete_feed(name) - - def test_create_feed(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = asset_service_pb2.Feed(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - feed_id = "feedId-976011428" - feed = {} - - response = client.create_feed(parent, feed_id, feed) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.CreateFeedRequest( - parent=parent, feed_id=feed_id, feed=feed - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_feed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup request - parent = "parent-995424086" - feed_id = "feedId-976011428" - feed = {} - - with pytest.raises(CustomException): - client.create_feed(parent, feed_id, feed) - - def test_get_feed(self): - # Setup Expected Response - name_2 = "name2-1052831874" - expected_response = {"name": name_2} - expected_response = asset_service_pb2.Feed(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup Request - name = "name3373707" - - response = client.get_feed(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.GetFeedRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_feed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup request - name = "name3373707" - - with pytest.raises(CustomException): - client.get_feed(name) - - def test_list_feeds(self): - # Setup Expected Response - expected_response = {} - expected_response = asset_service_pb2.ListFeedsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - - response = client.list_feeds(parent) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.ListFeedsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_feeds_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup request - parent = "parent-995424086" - - with pytest.raises(CustomException): - client.list_feeds(parent) - - def test_update_feed(self): - # Setup Expected Response - name = "name3373707" - expected_response = {"name": name} - expected_response = asset_service_pb2.Feed(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup Request - feed = {} - update_mask = {} - - response = client.update_feed(feed, update_mask) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.UpdateFeedRequest( - feed=feed, update_mask=update_mask - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_feed_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p2beta1.AssetServiceClient() - - # Setup request - feed = {} - update_mask = {} - - with pytest.raises(CustomException): - client.update_feed(feed, update_mask) diff --git a/tests/unit/gapic/v1p4beta1/test_asset_service_client_v1p4beta1.py b/tests/unit/gapic/v1p4beta1/test_asset_service_client_v1p4beta1.py deleted file mode 100644 index 0268174b..00000000 --- a/tests/unit/gapic/v1p4beta1/test_asset_service_client_v1p4beta1.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import asset_v1p4beta1 -from google.cloud.asset_v1p4beta1.proto import asset_service_pb2 -from google.longrunning import operations_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestAssetServiceClient(object): - def test_export_iam_policy_analysis(self): - # Setup Expected Response - expected_response = {} - expected_response = asset_service_pb2.ExportIamPolicyAnalysisResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_export_iam_policy_analysis", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p4beta1.AssetServiceClient() - - # Setup Request - analysis_query = {} - output_config = {} - - response = client.export_iam_policy_analysis(analysis_query, output_config) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.ExportIamPolicyAnalysisRequest( - analysis_query=analysis_query, output_config=output_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_export_iam_policy_analysis_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_export_iam_policy_analysis_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p4beta1.AssetServiceClient() - - # Setup Request - analysis_query = {} - output_config = {} - - response = client.export_iam_policy_analysis(analysis_query, output_config) - exception = response.exception() - assert exception.errors[0] == error - - def test_analyze_iam_policy(self): - # Setup Expected Response - fully_explored = True - expected_response = {"fully_explored": fully_explored} - expected_response = asset_service_pb2.AnalyzeIamPolicyResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p4beta1.AssetServiceClient() - - # Setup Request - analysis_query = {} - - response = client.analyze_iam_policy(analysis_query) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.AnalyzeIamPolicyRequest( - analysis_query=analysis_query - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_analyze_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p4beta1.AssetServiceClient() - - # Setup request - analysis_query = {} - - with pytest.raises(CustomException): - client.analyze_iam_policy(analysis_query) diff --git a/tests/unit/gapic/v1p5beta1/test_asset_service_client_v1p5beta1.py b/tests/unit/gapic/v1p5beta1/test_asset_service_client_v1p5beta1.py deleted file mode 100644 index db1b1600..00000000 --- a/tests/unit/gapic/v1p5beta1/test_asset_service_client_v1p5beta1.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 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 -# -# https://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. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import asset_v1p5beta1 -from google.cloud.asset_v1p5beta1.proto import asset_service_pb2 -from google.cloud.asset_v1p5beta1.proto import assets_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestAssetServiceClient(object): - def test_list_assets(self): - # Setup Expected Response - next_page_token = "" - assets_element = {} - assets = [assets_element] - expected_response = {"next_page_token": next_page_token, "assets": assets} - expected_response = asset_service_pb2.ListAssetsResponse(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p5beta1.AssetServiceClient() - - # Setup Request - parent = "parent-995424086" - - paged_list_response = client.list_assets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.assets[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = asset_service_pb2.ListAssetsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = asset_v1p5beta1.AssetServiceClient() - - # Setup request - parent = "parent-995424086" - - paged_list_response = client.list_assets(parent) - with pytest.raises(CustomException): - list(paged_list_response)