diff --git a/docs/osconfig_v1/os_config_zonal_service.rst b/docs/osconfig_v1/os_config_zonal_service.rst new file mode 100644 index 0000000..fb0b5d1 --- /dev/null +++ b/docs/osconfig_v1/os_config_zonal_service.rst @@ -0,0 +1,10 @@ +OsConfigZonalService +-------------------------------------- + +.. automodule:: google.cloud.osconfig_v1.services.os_config_zonal_service + :members: + :inherited-members: + +.. automodule:: google.cloud.osconfig_v1.services.os_config_zonal_service.pagers + :members: + :inherited-members: diff --git a/docs/osconfig_v1/services.rst b/docs/osconfig_v1/services.rst index e0dad88..8c1733a 100644 --- a/docs/osconfig_v1/services.rst +++ b/docs/osconfig_v1/services.rst @@ -4,3 +4,4 @@ Services for Google Cloud Osconfig v1 API :maxdepth: 2 os_config_service + os_config_zonal_service diff --git a/google/cloud/osconfig/__init__.py b/google/cloud/osconfig/__init__.py index 39c2c0d..26f2833 100644 --- a/google/cloud/osconfig/__init__.py +++ b/google/cloud/osconfig/__init__.py @@ -20,8 +20,18 @@ from google.cloud.osconfig_v1.services.os_config_service.async_client import ( OsConfigServiceAsyncClient, ) +from google.cloud.osconfig_v1.services.os_config_zonal_service.client import ( + OsConfigZonalServiceClient, +) +from google.cloud.osconfig_v1.services.os_config_zonal_service.async_client import ( + OsConfigZonalServiceAsyncClient, +) +from google.cloud.osconfig_v1.types.inventory import GetInventoryRequest from google.cloud.osconfig_v1.types.inventory import Inventory +from google.cloud.osconfig_v1.types.inventory import ListInventoriesRequest +from google.cloud.osconfig_v1.types.inventory import ListInventoriesResponse +from google.cloud.osconfig_v1.types.inventory import InventoryView from google.cloud.osconfig_v1.types.osconfig_common import FixedOrPercent from google.cloud.osconfig_v1.types.patch_deployments import ( CreatePatchDeploymentRequest, @@ -63,11 +73,24 @@ from google.cloud.osconfig_v1.types.patch_jobs import WindowsUpdateSettings from google.cloud.osconfig_v1.types.patch_jobs import YumSettings from google.cloud.osconfig_v1.types.patch_jobs import ZypperSettings +from google.cloud.osconfig_v1.types.vulnerability import CVSSv3 +from google.cloud.osconfig_v1.types.vulnerability import GetVulnerabilityReportRequest +from google.cloud.osconfig_v1.types.vulnerability import ListVulnerabilityReportsRequest +from google.cloud.osconfig_v1.types.vulnerability import ( + ListVulnerabilityReportsResponse, +) +from google.cloud.osconfig_v1.types.vulnerability import VulnerabilityReport __all__ = ( "OsConfigServiceClient", "OsConfigServiceAsyncClient", + "OsConfigZonalServiceClient", + "OsConfigZonalServiceAsyncClient", + "GetInventoryRequest", "Inventory", + "ListInventoriesRequest", + "ListInventoriesResponse", + "InventoryView", "FixedOrPercent", "CreatePatchDeploymentRequest", "DeletePatchDeploymentRequest", @@ -101,4 +124,9 @@ "WindowsUpdateSettings", "YumSettings", "ZypperSettings", + "CVSSv3", + "GetVulnerabilityReportRequest", + "ListVulnerabilityReportsRequest", + "ListVulnerabilityReportsResponse", + "VulnerabilityReport", ) diff --git a/google/cloud/osconfig_v1/__init__.py b/google/cloud/osconfig_v1/__init__.py index b67c795..5e8a826 100644 --- a/google/cloud/osconfig_v1/__init__.py +++ b/google/cloud/osconfig_v1/__init__.py @@ -16,8 +16,14 @@ from .services.os_config_service import OsConfigServiceClient from .services.os_config_service import OsConfigServiceAsyncClient +from .services.os_config_zonal_service import OsConfigZonalServiceClient +from .services.os_config_zonal_service import OsConfigZonalServiceAsyncClient +from .types.inventory import GetInventoryRequest from .types.inventory import Inventory +from .types.inventory import ListInventoriesRequest +from .types.inventory import ListInventoriesResponse +from .types.inventory import InventoryView from .types.osconfig_common import FixedOrPercent from .types.patch_deployments import CreatePatchDeploymentRequest from .types.patch_deployments import DeletePatchDeploymentRequest @@ -51,10 +57,17 @@ from .types.patch_jobs import WindowsUpdateSettings from .types.patch_jobs import YumSettings from .types.patch_jobs import ZypperSettings +from .types.vulnerability import CVSSv3 +from .types.vulnerability import GetVulnerabilityReportRequest +from .types.vulnerability import ListVulnerabilityReportsRequest +from .types.vulnerability import ListVulnerabilityReportsResponse +from .types.vulnerability import VulnerabilityReport __all__ = ( "OsConfigServiceAsyncClient", + "OsConfigZonalServiceAsyncClient", "AptSettings", + "CVSSv3", "CancelPatchJobRequest", "CreatePatchDeploymentRequest", "DeletePatchDeploymentRequest", @@ -63,20 +76,28 @@ "ExecutePatchJobRequest", "FixedOrPercent", "GcsObject", + "GetInventoryRequest", "GetPatchDeploymentRequest", "GetPatchJobRequest", + "GetVulnerabilityReportRequest", "GooSettings", "Instance", "Inventory", + "InventoryView", + "ListInventoriesRequest", + "ListInventoriesResponse", "ListPatchDeploymentsRequest", "ListPatchDeploymentsResponse", "ListPatchJobInstanceDetailsRequest", "ListPatchJobInstanceDetailsResponse", "ListPatchJobsRequest", "ListPatchJobsResponse", + "ListVulnerabilityReportsRequest", + "ListVulnerabilityReportsResponse", "MonthlySchedule", "OneTimeSchedule", "OsConfigServiceClient", + "OsConfigZonalServiceClient", "PatchConfig", "PatchDeployment", "PatchInstanceFilter", @@ -84,6 +105,7 @@ "PatchJobInstanceDetails", "PatchRollout", "RecurringSchedule", + "VulnerabilityReport", "WeekDayOfMonth", "WeeklySchedule", "WindowsUpdateSettings", diff --git a/google/cloud/osconfig_v1/gapic_metadata.json b/google/cloud/osconfig_v1/gapic_metadata.json index 8f824ed..1f20b04 100644 --- a/google/cloud/osconfig_v1/gapic_metadata.json +++ b/google/cloud/osconfig_v1/gapic_metadata.json @@ -108,6 +108,60 @@ } } } + }, + "OsConfigZonalService": { + "clients": { + "grpc": { + "libraryClient": "OsConfigZonalServiceClient", + "rpcs": { + "GetInventory": { + "methods": [ + "get_inventory" + ] + }, + "GetVulnerabilityReport": { + "methods": [ + "get_vulnerability_report" + ] + }, + "ListInventories": { + "methods": [ + "list_inventories" + ] + }, + "ListVulnerabilityReports": { + "methods": [ + "list_vulnerability_reports" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OsConfigZonalServiceAsyncClient", + "rpcs": { + "GetInventory": { + "methods": [ + "get_inventory" + ] + }, + "GetVulnerabilityReport": { + "methods": [ + "get_vulnerability_report" + ] + }, + "ListInventories": { + "methods": [ + "list_inventories" + ] + }, + "ListVulnerabilityReports": { + "methods": [ + "list_vulnerability_reports" + ] + } + } + } + } } } } diff --git a/google/cloud/osconfig_v1/services/os_config_zonal_service/__init__.py b/google/cloud/osconfig_v1/services/os_config_zonal_service/__init__.py new file mode 100644 index 0000000..0948ebe --- /dev/null +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 OsConfigZonalServiceClient +from .async_client import OsConfigZonalServiceAsyncClient + +__all__ = ( + "OsConfigZonalServiceClient", + "OsConfigZonalServiceAsyncClient", +) diff --git a/google/cloud/osconfig_v1/services/os_config_zonal_service/async_client.py b/google/cloud/osconfig_v1/services/os_config_zonal_service/async_client.py new file mode 100644 index 0000000..67bc12a --- /dev/null +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/async_client.py @@ -0,0 +1,534 @@ +# -*- 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 as core_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 as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.osconfig_v1.services.os_config_zonal_service import pagers +from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import vulnerability +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport +from .client import OsConfigZonalServiceClient + + +class OsConfigZonalServiceAsyncClient: + """Zonal OS Config API + The OS Config service is the server-side component that allows + users to manage package installations and patch jobs for Compute + Engine VM instances. + """ + + _client: OsConfigZonalServiceClient + + DEFAULT_ENDPOINT = OsConfigZonalServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OsConfigZonalServiceClient.DEFAULT_MTLS_ENDPOINT + + instance_path = staticmethod(OsConfigZonalServiceClient.instance_path) + parse_instance_path = staticmethod(OsConfigZonalServiceClient.parse_instance_path) + inventory_path = staticmethod(OsConfigZonalServiceClient.inventory_path) + parse_inventory_path = staticmethod(OsConfigZonalServiceClient.parse_inventory_path) + vulnerability_report_path = staticmethod( + OsConfigZonalServiceClient.vulnerability_report_path + ) + parse_vulnerability_report_path = staticmethod( + OsConfigZonalServiceClient.parse_vulnerability_report_path + ) + common_billing_account_path = staticmethod( + OsConfigZonalServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + OsConfigZonalServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(OsConfigZonalServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + OsConfigZonalServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + OsConfigZonalServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + OsConfigZonalServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(OsConfigZonalServiceClient.common_project_path) + parse_common_project_path = staticmethod( + OsConfigZonalServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(OsConfigZonalServiceClient.common_location_path) + parse_common_location_path = staticmethod( + OsConfigZonalServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + OsConfigZonalServiceAsyncClient: The constructed client. + """ + return OsConfigZonalServiceClient.from_service_account_info.__func__(OsConfigZonalServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + OsConfigZonalServiceAsyncClient: The constructed client. + """ + return OsConfigZonalServiceClient.from_service_account_file.__func__(OsConfigZonalServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> OsConfigZonalServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OsConfigZonalServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(OsConfigZonalServiceClient).get_transport_class, + type(OsConfigZonalServiceClient), + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, OsConfigZonalServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the os config zonal 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, ~.OsConfigZonalServiceTransport]): 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_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = OsConfigZonalServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_inventory( + self, + request: inventory.GetInventoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> inventory.Inventory: + r"""Get inventory data for the specified VM instance. If the VM has + no associated inventory, the message ``NOT_FOUND`` is returned. + + Args: + request (:class:`google.cloud.osconfig_v1.types.GetInventoryRequest`): + The request object. A request message for getting + inventory data for the specified VM. + name (:class:`str`): + Required. API resource name for inventory resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/inventory`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. + + 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: + google.cloud.osconfig_v1.types.Inventory: + This API resource represents the available inventory data for a + Compute Engine virtual machine (VM) instance at a + given point in time. + + You can use this API resource to determine the + inventory data of your VM. + + For more information, see [Information provided by OS + inventory + management](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#data-collected). + + """ + # 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." + ) + + request = inventory.GetInventoryRequest(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_inventory, + default_timeout=None, + client_info=DEFAULT_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_inventories( + self, + request: inventory.ListInventoriesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInventoriesAsyncPager: + r"""List inventory data for all VM instances in the + specified zone. + + Args: + request (:class:`google.cloud.osconfig_v1.types.ListInventoriesRequest`): + The request object. A request message for listing + inventory data for all VMs in the specified location. + parent (:class:`str`): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/-`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. + + 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: + google.cloud.osconfig_v1.services.os_config_zonal_service.pagers.ListInventoriesAsyncPager: + A response message for listing + inventory data for all VMs in a + specified location. + 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([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." + ) + + request = inventory.ListInventoriesRequest(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_inventories, + default_timeout=None, + client_info=DEFAULT_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.ListInventoriesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_vulnerability_report( + self, + request: vulnerability.GetVulnerabilityReportRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vulnerability.VulnerabilityReport: + r"""Gets the vulnerability report for the specified VM + instance. Only VMs with inventory data have + vulnerability reports associated with them. + + Args: + request (:class:`google.cloud.osconfig_v1.types.GetVulnerabilityReportRequest`): + The request object. A request message for getting the + vulnerability report for the specified VM. + name (:class:`str`): + Required. API resource name for vulnerability resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. + + 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: + google.cloud.osconfig_v1.types.VulnerabilityReport: + This API resource represents the vulnerability report for a specified + Compute Engine virtual machine (VM) instance at a + given point in time. + + For more information, see [Vulnerability + reports](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#vulnerability-reports). + + """ + # 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." + ) + + request = vulnerability.GetVulnerabilityReportRequest(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_vulnerability_report, + default_timeout=None, + client_info=DEFAULT_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_vulnerability_reports( + self, + request: vulnerability.ListVulnerabilityReportsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVulnerabilityReportsAsyncPager: + r"""List vulnerability reports for all VM instances in + the specified zone. + + Args: + request (:class:`google.cloud.osconfig_v1.types.ListVulnerabilityReportsRequest`): + The request object. A request message for listing + vulnerability reports for all VM instances in the + specified location. + parent (:class:`str`): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/-`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. + + 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: + google.cloud.osconfig_v1.services.os_config_zonal_service.pagers.ListVulnerabilityReportsAsyncPager: + A response message for listing + vulnerability reports for all VM + instances in the specified location. + 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([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." + ) + + request = vulnerability.ListVulnerabilityReportsRequest(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_vulnerability_reports, + default_timeout=None, + client_info=DEFAULT_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.ListVulnerabilityReportsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-os-config",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("OsConfigZonalServiceAsyncClient",) diff --git a/google/cloud/osconfig_v1/services/os_config_zonal_service/client.py b/google/cloud/osconfig_v1/services/os_config_zonal_service/client.py new file mode 100644 index 0000000..6bf7211 --- /dev/null +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/client.py @@ -0,0 +1,750 @@ +# -*- 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_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 as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.osconfig_v1.services.os_config_zonal_service import pagers +from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import vulnerability +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OsConfigZonalServiceGrpcTransport +from .transports.grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport + + +class OsConfigZonalServiceClientMeta(type): + """Metaclass for the OsConfigZonalService 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[OsConfigZonalServiceTransport]] + _transport_registry["grpc"] = OsConfigZonalServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OsConfigZonalServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[OsConfigZonalServiceTransport]: + """Returns 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 OsConfigZonalServiceClient(metaclass=OsConfigZonalServiceClientMeta): + """Zonal OS Config API + The OS Config service is the server-side component that allows + users to manage package installations and patch jobs for Compute + Engine VM instances. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts 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 = "osconfig.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + OsConfigZonalServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @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: + OsConfigZonalServiceClient: 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 + + @property + def transport(self) -> OsConfigZonalServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OsConfigZonalServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def instance_path(project: str, zone: str, instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/zones/{zone}/instances/{instance}".format( + project=project, zone=zone, instance=instance, + ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str, str]: + """Parses a instance path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/zones/(?P.+?)/instances/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def inventory_path(project: str, location: str, instance: str,) -> str: + """Returns a fully-qualified inventory string.""" + return "projects/{project}/locations/{location}/instances/{instance}/inventory".format( + project=project, location=location, instance=instance, + ) + + @staticmethod + def parse_inventory_path(path: str) -> Dict[str, str]: + """Parses a inventory path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def vulnerability_report_path(project: str, location: str, instance: str,) -> str: + """Returns a fully-qualified vulnerability_report string.""" + return "projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport".format( + project=project, location=location, instance=instance, + ) + + @staticmethod + def parse_vulnerability_report_path(path: str) -> Dict[str, str]: + """Parses a vulnerability_report path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/vulnerabilityReport$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, OsConfigZonalServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the os config zonal 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, OsConfigZonalServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.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_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT 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, OsConfigZonalServiceTransport): + # transport is a OsConfigZonalServiceTransport 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=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=( + Transport == type(self).get_transport_class("grpc") + or Transport == type(self).get_transport_class("grpc_asyncio") + ), + ) + + def get_inventory( + self, + request: inventory.GetInventoryRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> inventory.Inventory: + r"""Get inventory data for the specified VM instance. If the VM has + no associated inventory, the message ``NOT_FOUND`` is returned. + + Args: + request (google.cloud.osconfig_v1.types.GetInventoryRequest): + The request object. A request message for getting + inventory data for the specified VM. + name (str): + Required. API resource name for inventory resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/inventory`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. + + 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: + google.cloud.osconfig_v1.types.Inventory: + This API resource represents the available inventory data for a + Compute Engine virtual machine (VM) instance at a + given point in time. + + You can use this API resource to determine the + inventory data of your VM. + + For more information, see [Information provided by OS + inventory + management](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#data-collected). + + """ + # 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 inventory.GetInventoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, inventory.GetInventoryRequest): + request = inventory.GetInventoryRequest(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_inventory] + + # 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_inventories( + self, + request: inventory.ListInventoriesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListInventoriesPager: + r"""List inventory data for all VM instances in the + specified zone. + + Args: + request (google.cloud.osconfig_v1.types.ListInventoriesRequest): + The request object. A request message for listing + inventory data for all VMs in the specified location. + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/-`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. + + 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: + google.cloud.osconfig_v1.services.os_config_zonal_service.pagers.ListInventoriesPager: + A response message for listing + inventory data for all VMs in a + specified location. + 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([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 inventory.ListInventoriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, inventory.ListInventoriesRequest): + request = inventory.ListInventoriesRequest(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_inventories] + + # 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.ListInventoriesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_vulnerability_report( + self, + request: vulnerability.GetVulnerabilityReportRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> vulnerability.VulnerabilityReport: + r"""Gets the vulnerability report for the specified VM + instance. Only VMs with inventory data have + vulnerability reports associated with them. + + Args: + request (google.cloud.osconfig_v1.types.GetVulnerabilityReportRequest): + The request object. A request message for getting the + vulnerability report for the specified VM. + name (str): + Required. API resource name for vulnerability resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. + + 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: + google.cloud.osconfig_v1.types.VulnerabilityReport: + This API resource represents the vulnerability report for a specified + Compute Engine virtual machine (VM) instance at a + given point in time. + + For more information, see [Vulnerability + reports](\ https://cloud.google.com/compute/docs/instances/os-inventory-management#vulnerability-reports). + + """ + # 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 vulnerability.GetVulnerabilityReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, vulnerability.GetVulnerabilityReportRequest): + request = vulnerability.GetVulnerabilityReportRequest(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_vulnerability_report] + + # 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_vulnerability_reports( + self, + request: vulnerability.ListVulnerabilityReportsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVulnerabilityReportsPager: + r"""List vulnerability reports for all VM instances in + the specified zone. + + Args: + request (google.cloud.osconfig_v1.types.ListVulnerabilityReportsRequest): + The request object. A request message for listing + vulnerability reports for all VM instances in the + specified location. + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/-`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. + + 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: + google.cloud.osconfig_v1.services.os_config_zonal_service.pagers.ListVulnerabilityReportsPager: + A response message for listing + vulnerability reports for all VM + instances in the specified location. + 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([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 vulnerability.ListVulnerabilityReportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, vulnerability.ListVulnerabilityReportsRequest): + request = vulnerability.ListVulnerabilityReportsRequest(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_vulnerability_reports + ] + + # 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.ListVulnerabilityReportsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-os-config",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("OsConfigZonalServiceClient",) diff --git a/google/cloud/osconfig_v1/services/os_config_zonal_service/pagers.py b/google/cloud/osconfig_v1/services/os_config_zonal_service/pagers.py new file mode 100644 index 0000000..0eff993 --- /dev/null +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/pagers.py @@ -0,0 +1,288 @@ +# -*- 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, + Optional, +) + +from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import vulnerability + + +class ListInventoriesPager: + """A pager for iterating through ``list_inventories`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListInventoriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``inventories`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListInventories`` requests and continue to iterate + through the ``inventories`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListInventoriesResponse` + 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[..., inventory.ListInventoriesResponse], + request: inventory.ListInventoriesRequest, + response: inventory.ListInventoriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListInventoriesRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListInventoriesResponse): + 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 = inventory.ListInventoriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[inventory.ListInventoriesResponse]: + 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[inventory.Inventory]: + for page in self.pages: + yield from page.inventories + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListInventoriesAsyncPager: + """A pager for iterating through ``list_inventories`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListInventoriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``inventories`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListInventories`` requests and continue to iterate + through the ``inventories`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListInventoriesResponse` + 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[inventory.ListInventoriesResponse]], + request: inventory.ListInventoriesRequest, + response: inventory.ListInventoriesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListInventoriesRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListInventoriesResponse): + 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 = inventory.ListInventoriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[inventory.ListInventoriesResponse]: + 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[inventory.Inventory]: + async def async_generator(): + async for page in self.pages: + for response in page.inventories: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListVulnerabilityReportsPager: + """A pager for iterating through ``list_vulnerability_reports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListVulnerabilityReportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``vulnerability_reports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVulnerabilityReports`` requests and continue to iterate + through the ``vulnerability_reports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListVulnerabilityReportsResponse` + 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[..., vulnerability.ListVulnerabilityReportsResponse], + request: vulnerability.ListVulnerabilityReportsRequest, + response: vulnerability.ListVulnerabilityReportsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListVulnerabilityReportsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListVulnerabilityReportsResponse): + 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 = vulnerability.ListVulnerabilityReportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[vulnerability.ListVulnerabilityReportsResponse]: + 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[vulnerability.VulnerabilityReport]: + for page in self.pages: + yield from page.vulnerability_reports + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListVulnerabilityReportsAsyncPager: + """A pager for iterating through ``list_vulnerability_reports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListVulnerabilityReportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``vulnerability_reports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVulnerabilityReports`` requests and continue to iterate + through the ``vulnerability_reports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListVulnerabilityReportsResponse` + 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[vulnerability.ListVulnerabilityReportsResponse] + ], + request: vulnerability.ListVulnerabilityReportsRequest, + response: vulnerability.ListVulnerabilityReportsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.osconfig_v1.types.ListVulnerabilityReportsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListVulnerabilityReportsResponse): + 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 = vulnerability.ListVulnerabilityReportsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[vulnerability.ListVulnerabilityReportsResponse]: + 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[vulnerability.VulnerabilityReport]: + async def async_generator(): + async for page in self.pages: + for response in page.vulnerability_reports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/__init__.py b/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/__init__.py new file mode 100644 index 0000000..c070e43 --- /dev/null +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- 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 OsConfigZonalServiceTransport +from .grpc import OsConfigZonalServiceGrpcTransport +from .grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[OsConfigZonalServiceTransport]] +_transport_registry["grpc"] = OsConfigZonalServiceGrpcTransport +_transport_registry["grpc_asyncio"] = OsConfigZonalServiceGrpcAsyncIOTransport + +__all__ = ( + "OsConfigZonalServiceTransport", + "OsConfigZonalServiceGrpcTransport", + "OsConfigZonalServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/base.py b/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/base.py new file mode 100644 index 0000000..055b8d8 --- /dev/null +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/base.py @@ -0,0 +1,220 @@ +# -*- 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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 as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import vulnerability + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-os-config",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +class OsConfigZonalServiceTransport(abc.ABC): + """Abstract transport class for OsConfigZonalService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "osconfig.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + **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. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # If the credentials is service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_inventory: gapic_v1.method.wrap_method( + self.get_inventory, default_timeout=None, client_info=client_info, + ), + self.list_inventories: gapic_v1.method.wrap_method( + self.list_inventories, default_timeout=None, client_info=client_info, + ), + self.get_vulnerability_report: gapic_v1.method.wrap_method( + self.get_vulnerability_report, + default_timeout=None, + client_info=client_info, + ), + self.list_vulnerability_reports: gapic_v1.method.wrap_method( + self.list_vulnerability_reports, + default_timeout=None, + client_info=client_info, + ), + } + + @property + def get_inventory( + self, + ) -> Callable[ + [inventory.GetInventoryRequest], + Union[inventory.Inventory, Awaitable[inventory.Inventory]], + ]: + raise NotImplementedError() + + @property + def list_inventories( + self, + ) -> Callable[ + [inventory.ListInventoriesRequest], + Union[ + inventory.ListInventoriesResponse, + Awaitable[inventory.ListInventoriesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_vulnerability_report( + self, + ) -> Callable[ + [vulnerability.GetVulnerabilityReportRequest], + Union[ + vulnerability.VulnerabilityReport, + Awaitable[vulnerability.VulnerabilityReport], + ], + ]: + raise NotImplementedError() + + @property + def list_vulnerability_reports( + self, + ) -> Callable[ + [vulnerability.ListVulnerabilityReportsRequest], + Union[ + vulnerability.ListVulnerabilityReportsResponse, + Awaitable[vulnerability.ListVulnerabilityReportsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("OsConfigZonalServiceTransport",) diff --git a/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/grpc.py b/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/grpc.py new file mode 100644 index 0000000..95d31c7 --- /dev/null +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/grpc.py @@ -0,0 +1,349 @@ +# -*- 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 warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import vulnerability +from .base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO + + +class OsConfigZonalServiceGrpcTransport(OsConfigZonalServiceTransport): + """gRPC backend transport for OsConfigZonalService. + + Zonal OS Config API + The OS Config service is the server-side component that allows + users to manage package installations and patch jobs for Compute + Engine VM instances. + + 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 = "osconfig.googleapis.com", + credentials: ga_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, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> 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]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "osconfig.googleapis.com", + credentials: ga_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: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_inventory( + self, + ) -> Callable[[inventory.GetInventoryRequest], inventory.Inventory]: + r"""Return a callable for the get inventory method over gRPC. + + Get inventory data for the specified VM instance. If the VM has + no associated inventory, the message ``NOT_FOUND`` is returned. + + Returns: + Callable[[~.GetInventoryRequest], + ~.Inventory]: + 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_inventory" not in self._stubs: + self._stubs["get_inventory"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/GetInventory", + request_serializer=inventory.GetInventoryRequest.serialize, + response_deserializer=inventory.Inventory.deserialize, + ) + return self._stubs["get_inventory"] + + @property + def list_inventories( + self, + ) -> Callable[ + [inventory.ListInventoriesRequest], inventory.ListInventoriesResponse + ]: + r"""Return a callable for the list inventories method over gRPC. + + List inventory data for all VM instances in the + specified zone. + + Returns: + Callable[[~.ListInventoriesRequest], + ~.ListInventoriesResponse]: + 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_inventories" not in self._stubs: + self._stubs["list_inventories"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListInventories", + request_serializer=inventory.ListInventoriesRequest.serialize, + response_deserializer=inventory.ListInventoriesResponse.deserialize, + ) + return self._stubs["list_inventories"] + + @property + def get_vulnerability_report( + self, + ) -> Callable[ + [vulnerability.GetVulnerabilityReportRequest], vulnerability.VulnerabilityReport + ]: + r"""Return a callable for the get vulnerability report method over gRPC. + + Gets the vulnerability report for the specified VM + instance. Only VMs with inventory data have + vulnerability reports associated with them. + + Returns: + Callable[[~.GetVulnerabilityReportRequest], + ~.VulnerabilityReport]: + 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_vulnerability_report" not in self._stubs: + self._stubs["get_vulnerability_report"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/GetVulnerabilityReport", + request_serializer=vulnerability.GetVulnerabilityReportRequest.serialize, + response_deserializer=vulnerability.VulnerabilityReport.deserialize, + ) + return self._stubs["get_vulnerability_report"] + + @property + def list_vulnerability_reports( + self, + ) -> Callable[ + [vulnerability.ListVulnerabilityReportsRequest], + vulnerability.ListVulnerabilityReportsResponse, + ]: + r"""Return a callable for the list vulnerability reports method over gRPC. + + List vulnerability reports for all VM instances in + the specified zone. + + Returns: + Callable[[~.ListVulnerabilityReportsRequest], + ~.ListVulnerabilityReportsResponse]: + 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_vulnerability_reports" not in self._stubs: + self._stubs["list_vulnerability_reports"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListVulnerabilityReports", + request_serializer=vulnerability.ListVulnerabilityReportsRequest.serialize, + response_deserializer=vulnerability.ListVulnerabilityReportsResponse.deserialize, + ) + return self._stubs["list_vulnerability_reports"] + + +__all__ = ("OsConfigZonalServiceGrpcTransport",) diff --git a/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/grpc_asyncio.py b/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..73258d4 --- /dev/null +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/transports/grpc_asyncio.py @@ -0,0 +1,353 @@ +# -*- 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 warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import vulnerability +from .base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OsConfigZonalServiceGrpcTransport + + +class OsConfigZonalServiceGrpcAsyncIOTransport(OsConfigZonalServiceTransport): + """gRPC AsyncIO backend transport for OsConfigZonalService. + + Zonal OS Config API + The OS Config service is the server-side component that allows + users to manage package installations and patch jobs for Compute + Engine VM instances. + + 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 = "osconfig.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + 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. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "osconfig.googleapis.com", + credentials: ga_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, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> 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]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_inventory( + self, + ) -> Callable[[inventory.GetInventoryRequest], Awaitable[inventory.Inventory]]: + r"""Return a callable for the get inventory method over gRPC. + + Get inventory data for the specified VM instance. If the VM has + no associated inventory, the message ``NOT_FOUND`` is returned. + + Returns: + Callable[[~.GetInventoryRequest], + Awaitable[~.Inventory]]: + 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_inventory" not in self._stubs: + self._stubs["get_inventory"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/GetInventory", + request_serializer=inventory.GetInventoryRequest.serialize, + response_deserializer=inventory.Inventory.deserialize, + ) + return self._stubs["get_inventory"] + + @property + def list_inventories( + self, + ) -> Callable[ + [inventory.ListInventoriesRequest], Awaitable[inventory.ListInventoriesResponse] + ]: + r"""Return a callable for the list inventories method over gRPC. + + List inventory data for all VM instances in the + specified zone. + + Returns: + Callable[[~.ListInventoriesRequest], + Awaitable[~.ListInventoriesResponse]]: + 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_inventories" not in self._stubs: + self._stubs["list_inventories"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListInventories", + request_serializer=inventory.ListInventoriesRequest.serialize, + response_deserializer=inventory.ListInventoriesResponse.deserialize, + ) + return self._stubs["list_inventories"] + + @property + def get_vulnerability_report( + self, + ) -> Callable[ + [vulnerability.GetVulnerabilityReportRequest], + Awaitable[vulnerability.VulnerabilityReport], + ]: + r"""Return a callable for the get vulnerability report method over gRPC. + + Gets the vulnerability report for the specified VM + instance. Only VMs with inventory data have + vulnerability reports associated with them. + + Returns: + Callable[[~.GetVulnerabilityReportRequest], + Awaitable[~.VulnerabilityReport]]: + 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_vulnerability_report" not in self._stubs: + self._stubs["get_vulnerability_report"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/GetVulnerabilityReport", + request_serializer=vulnerability.GetVulnerabilityReportRequest.serialize, + response_deserializer=vulnerability.VulnerabilityReport.deserialize, + ) + return self._stubs["get_vulnerability_report"] + + @property + def list_vulnerability_reports( + self, + ) -> Callable[ + [vulnerability.ListVulnerabilityReportsRequest], + Awaitable[vulnerability.ListVulnerabilityReportsResponse], + ]: + r"""Return a callable for the list vulnerability reports method over gRPC. + + List vulnerability reports for all VM instances in + the specified zone. + + Returns: + Callable[[~.ListVulnerabilityReportsRequest], + Awaitable[~.ListVulnerabilityReportsResponse]]: + 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_vulnerability_reports" not in self._stubs: + self._stubs["list_vulnerability_reports"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListVulnerabilityReports", + request_serializer=vulnerability.ListVulnerabilityReportsRequest.serialize, + response_deserializer=vulnerability.ListVulnerabilityReportsResponse.deserialize, + ) + return self._stubs["list_vulnerability_reports"] + + +__all__ = ("OsConfigZonalServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/osconfig_v1/types/__init__.py b/google/cloud/osconfig_v1/types/__init__.py index 34ff16d..6ea7245 100644 --- a/google/cloud/osconfig_v1/types/__init__.py +++ b/google/cloud/osconfig_v1/types/__init__.py @@ -13,7 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .inventory import Inventory +from .inventory import ( + GetInventoryRequest, + Inventory, + ListInventoriesRequest, + ListInventoriesResponse, + InventoryView, +) from .osconfig_common import FixedOrPercent from .patch_deployments import ( CreatePatchDeploymentRequest, @@ -51,9 +57,20 @@ YumSettings, ZypperSettings, ) +from .vulnerability import ( + CVSSv3, + GetVulnerabilityReportRequest, + ListVulnerabilityReportsRequest, + ListVulnerabilityReportsResponse, + VulnerabilityReport, +) __all__ = ( + "GetInventoryRequest", "Inventory", + "ListInventoriesRequest", + "ListInventoriesResponse", + "InventoryView", "FixedOrPercent", "CreatePatchDeploymentRequest", "DeletePatchDeploymentRequest", @@ -87,4 +104,9 @@ "WindowsUpdateSettings", "YumSettings", "ZypperSettings", + "CVSSv3", + "GetVulnerabilityReportRequest", + "ListVulnerabilityReportsRequest", + "ListVulnerabilityReportsResponse", + "VulnerabilityReport", ) diff --git a/google/cloud/osconfig_v1/types/inventory.py b/google/cloud/osconfig_v1/types/inventory.py index e829fca..513e95c 100644 --- a/google/cloud/osconfig_v1/types/inventory.py +++ b/google/cloud/osconfig_v1/types/inventory.py @@ -20,13 +20,41 @@ __protobuf__ = proto.module( - package="google.cloud.osconfig.v1", manifest={"Inventory",}, + package="google.cloud.osconfig.v1", + manifest={ + "InventoryView", + "Inventory", + "GetInventoryRequest", + "ListInventoriesRequest", + "ListInventoriesResponse", + }, ) +class InventoryView(proto.Enum): + r"""The view for inventory objects.""" + INVENTORY_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + class Inventory(proto.Message): - r"""The inventory details of a VM. + r"""This API resource represents the available inventory data for a + Compute Engine virtual machine (VM) instance at a given point in + time. + + You can use this API resource to determine the inventory data of + your VM. + + For more information, see `Information provided by OS inventory + management `__. + Attributes: + name (str): + Output only. The ``Inventory`` API resource name. + + Format: + ``projects/{project_number}/locations/{location}/instances/{instance_id}/inventory`` os_info (google.cloud.osconfig_v1.types.Inventory.OsInfo): Base level operating system information for the VM. @@ -36,6 +64,9 @@ class Inventory(proto.Message): item. The identifier is unique to each distinct and addressable inventory item and will change, when there is a new package version. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp of the last reported + inventory for the VM. """ class OsInfo(proto.Message): @@ -166,7 +197,7 @@ class SoftwarePackage(proto.Message): cos_package (google.cloud.osconfig_v1.types.Inventory.VersionedPackage): Details of a COS package. windows_application (google.cloud.osconfig_v1.types.Inventory.WindowsApplication): - Details of a Windows Application + Details of Windows Application. """ yum_package = proto.Field( @@ -240,6 +271,25 @@ class VersionedPackage(proto.Message): architecture = proto.Field(proto.STRING, number=2,) version = proto.Field(proto.STRING, number=3,) + class ZypperPatch(proto.Message): + r"""Details related to a Zypper Patch. + Attributes: + patch_name (str): + The name of the patch. + category (str): + The category of the patch. + severity (str): + The severity specified for this patch + summary (str): + Any summary information provided about this + patch. + """ + + patch_name = proto.Field(proto.STRING, number=5,) + category = proto.Field(proto.STRING, number=2,) + severity = proto.Field(proto.STRING, number=3,) + summary = proto.Field(proto.STRING, number=4,) + class WindowsUpdatePackage(proto.Message): r"""Details related to a Windows Update package. Field data and names are taken from Windows Update API IUpdate Interface: @@ -305,25 +355,6 @@ class WindowsUpdateCategory(proto.Message): proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, ) - class ZypperPatch(proto.Message): - r"""Details related to a Zypper Patch. - Attributes: - patch_name (str): - The name of the patch. - category (str): - The category of the patch. - severity (str): - The severity specified for this patch - summary (str): - Any summary information provided about this - patch. - """ - - patch_name = proto.Field(proto.STRING, number=5,) - category = proto.Field(proto.STRING, number=2,) - severity = proto.Field(proto.STRING, number=3,) - summary = proto.Field(proto.STRING, number=4,) - class WindowsQuickFixEngineeringPackage(proto.Message): r"""Information related to a Quick Fix Engineering package. Fields are taken from Windows QuickFixEngineering Interface and @@ -385,8 +416,91 @@ class WindowsApplication(proto.Message): install_date = proto.Field(proto.MESSAGE, number=4, message=date_pb2.Date,) help_link = proto.Field(proto.STRING, number=5,) + name = proto.Field(proto.STRING, number=3,) os_info = proto.Field(proto.MESSAGE, number=1, message=OsInfo,) items = proto.MapField(proto.STRING, proto.MESSAGE, number=2, message=Item,) + update_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + + +class GetInventoryRequest(proto.Message): + r"""A request message for getting inventory data for the + specified VM. + + Attributes: + name (str): + Required. API resource name for inventory resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/inventory`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, either + Compute Engine ``instance-id`` or ``instance-name`` can be + provided. + view (google.cloud.osconfig_v1.types.InventoryView): + Inventory view indicating what information + should be included in the inventory resource. If + unspecified, the default view is BASIC. + """ + + name = proto.Field(proto.STRING, number=1,) + view = proto.Field(proto.ENUM, number=2, enum="InventoryView",) + + +class ListInventoriesRequest(proto.Message): + r"""A request message for listing inventory data for all VMs in + the specified location. + + Attributes: + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/-`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. + view (google.cloud.osconfig_v1.types.InventoryView): + Inventory view indicating what information + should be included in the inventory resource. If + unspecified, the default view is BASIC. + page_size (int): + The maximum number of results to return. + page_token (str): + A pagination token returned from a previous call to + ``ListInventories`` that indicates where this listing should + continue from. + filter (str): + If provided, this field specifies the criteria that must be + met by a ``Inventory`` API resource to be included in the + response. + """ + + parent = proto.Field(proto.STRING, number=1,) + view = proto.Field(proto.ENUM, number=2, enum="InventoryView",) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) + filter = proto.Field(proto.STRING, number=5,) + + +class ListInventoriesResponse(proto.Message): + r"""A response message for listing inventory data for all VMs in + a specified location. + + Attributes: + inventories (Sequence[google.cloud.osconfig_v1.types.Inventory]): + List of inventory objects. + next_page_token (str): + The pagination token to retrieve the next + page of inventory objects. + """ + + @property + def raw_page(self): + return self + + inventories = proto.RepeatedField(proto.MESSAGE, number=1, message="Inventory",) + next_page_token = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/osconfig_v1/types/osconfig_zonal_service.py b/google/cloud/osconfig_v1/types/osconfig_zonal_service.py new file mode 100644 index 0000000..5a02c6a --- /dev/null +++ b/google/cloud/osconfig_v1/types/osconfig_zonal_service.py @@ -0,0 +1,21 @@ +# -*- 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. +# + + +__protobuf__ = proto.module(package="google.cloud.osconfig.v1", manifest={},) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/osconfig_v1/types/vulnerability.py b/google/cloud/osconfig_v1/types/vulnerability.py new file mode 100644 index 0000000..ac4120e --- /dev/null +++ b/google/cloud/osconfig_v1/types/vulnerability.py @@ -0,0 +1,354 @@ +# -*- 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 timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.osconfig.v1", + manifest={ + "VulnerabilityReport", + "GetVulnerabilityReportRequest", + "ListVulnerabilityReportsRequest", + "ListVulnerabilityReportsResponse", + "CVSSv3", + }, +) + + +class VulnerabilityReport(proto.Message): + r"""This API resource represents the vulnerability report for a + specified Compute Engine virtual machine (VM) instance at a given + point in time. + + For more information, see `Vulnerability + reports `__. + + Attributes: + name (str): + Output only. The ``vulnerabilityReport`` API resource name. + + Format: + ``projects/{project_number}/locations/{location}/instances/{instance_id}/vulnerabilityReport`` + vulnerabilities (Sequence[google.cloud.osconfig_v1.types.VulnerabilityReport.Vulnerability]): + Output only. List of vulnerabilities + affecting the VM. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp for when the last + vulnerability report was generated for the VM. + """ + + class Vulnerability(proto.Message): + r"""A vulnerability affecting the VM instance. + Attributes: + details (google.cloud.osconfig_v1.types.VulnerabilityReport.Vulnerability.Details): + Contains metadata as per the upstream feed of + the operating system and NVD. + installed_inventory_item_ids (Sequence[str]): + Corresponds to the ``INSTALLED_PACKAGE`` inventory item on + the VM. This field displays the inventory items affected by + this vulnerability. If the vulnerability report was not + updated after the VM inventory update, these values might + not display in VM inventory. For some distros, this field + may be empty. + available_inventory_item_ids (Sequence[str]): + Corresponds to the ``AVAILABLE_PACKAGE`` inventory item on + the VM. If the vulnerability report was not updated after + the VM inventory update, these values might not display in + VM inventory. If there is no available fix, the field is + empty. The ``inventory_item`` value specifies the latest + ``SoftwarePackage`` available to the VM that fixes the + vulnerability. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp for when the vulnerability was + first detected. + update_time (google.protobuf.timestamp_pb2.Timestamp): + The timestamp for when the vulnerability was + last modified. + """ + + class Details(proto.Message): + r"""Contains metadata information for the vulnerability. This + information is collected from the upstream feed of the operating + system. + + Attributes: + cve (str): + The CVE of the vulnerability. CVE cannot be + empty and the combination of should be unique across + vulnerabilities for a VM. + cvss_v2_score (float): + The CVSS V2 score of this vulnerability. CVSS + V2 score is on a scale of 0 - 10 where 0 + indicates low severity and 10 indicates high + severity. + cvss_v3 (google.cloud.osconfig_v1.types.CVSSv3): + The full description of the CVSSv3 for this + vulnerability from NVD. + severity (str): + Assigned severity/impact ranking from the + distro. + description (str): + The note or description describing the + vulnerability from the distro. + references (Sequence[google.cloud.osconfig_v1.types.VulnerabilityReport.Vulnerability.Details.Reference]): + Corresponds to the references attached to the + ``VulnerabilityDetails``. + """ + + class Reference(proto.Message): + r"""A reference for this vulnerability. + Attributes: + url (str): + The url of the reference. + source (str): + The source of the reference e.g. NVD. + """ + + url = proto.Field(proto.STRING, number=1,) + source = proto.Field(proto.STRING, number=2,) + + cve = proto.Field(proto.STRING, number=1,) + cvss_v2_score = proto.Field(proto.FLOAT, number=2,) + cvss_v3 = proto.Field(proto.MESSAGE, number=3, message="CVSSv3",) + severity = proto.Field(proto.STRING, number=4,) + description = proto.Field(proto.STRING, number=5,) + references = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="VulnerabilityReport.Vulnerability.Details.Reference", + ) + + details = proto.Field( + proto.MESSAGE, + number=1, + message="VulnerabilityReport.Vulnerability.Details", + ) + installed_inventory_item_ids = proto.RepeatedField(proto.STRING, number=2,) + available_inventory_item_ids = proto.RepeatedField(proto.STRING, number=3,) + create_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, + ) + + name = proto.Field(proto.STRING, number=1,) + vulnerabilities = proto.RepeatedField( + proto.MESSAGE, number=2, message=Vulnerability, + ) + update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) + + +class GetVulnerabilityReportRequest(proto.Message): + r"""A request message for getting the vulnerability report for + the specified VM. + + Attributes: + name (str): + Required. API resource name for vulnerability resource. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, either + Compute Engine ``instance-id`` or ``instance-name`` can be + provided. + """ + + name = proto.Field(proto.STRING, number=1,) + + +class ListVulnerabilityReportsRequest(proto.Message): + r"""A request message for listing vulnerability reports for all + VM instances in the specified location. + + Attributes: + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/-`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. + page_size (int): + The maximum number of results to return. + page_token (str): + A pagination token returned from a previous call to + ``ListVulnerabilityReports`` that indicates where this + listing should continue from. + filter (str): + If provided, this field specifies the criteria that must be + met by a ``vulnerabilityReport`` API resource to be included + in the response. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) + + +class ListVulnerabilityReportsResponse(proto.Message): + r"""A response message for listing vulnerability reports for all + VM instances in the specified location. + + Attributes: + vulnerability_reports (Sequence[google.cloud.osconfig_v1.types.VulnerabilityReport]): + List of vulnerabilityReport objects. + next_page_token (str): + The pagination token to retrieve the next + page of vulnerabilityReports object. + """ + + @property + def raw_page(self): + return self + + vulnerability_reports = proto.RepeatedField( + proto.MESSAGE, number=1, message="VulnerabilityReport", + ) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class CVSSv3(proto.Message): + r"""Common Vulnerability Scoring System version 3. + For details, see https://www.first.org/cvss/specification- + document + + Attributes: + base_score (float): + The base score is a function of the base + metric scores. + https://www.first.org/cvss/specification- + document#Base-Metrics + exploitability_score (float): + The Exploitability sub-score equation is + derived from the Base Exploitability metrics. + https://www.first.org/cvss/specification- + document#2-1-Exploitability-Metrics + impact_score (float): + The Impact sub-score equation is derived from + the Base Impact metrics. + attack_vector (google.cloud.osconfig_v1.types.CVSSv3.AttackVector): + This metric reflects the context by which + vulnerability exploitation is possible. + attack_complexity (google.cloud.osconfig_v1.types.CVSSv3.AttackComplexity): + This metric describes the conditions beyond + the attacker's control that must exist in order + to exploit the vulnerability. + privileges_required (google.cloud.osconfig_v1.types.CVSSv3.PrivilegesRequired): + This metric describes the level of privileges + an attacker must possess before successfully + exploiting the vulnerability. + user_interaction (google.cloud.osconfig_v1.types.CVSSv3.UserInteraction): + This metric captures the requirement for a + human user, other than the attacker, to + participate in the successful compromise of the + vulnerable component. + scope (google.cloud.osconfig_v1.types.CVSSv3.Scope): + The Scope metric captures whether a + vulnerability in one vulnerable component + impacts resources in components beyond its + security scope. + confidentiality_impact (google.cloud.osconfig_v1.types.CVSSv3.Impact): + This metric measures the impact to the + confidentiality of the information resources + managed by a software component due to a + successfully exploited vulnerability. + integrity_impact (google.cloud.osconfig_v1.types.CVSSv3.Impact): + This metric measures the impact to integrity + of a successfully exploited vulnerability. + availability_impact (google.cloud.osconfig_v1.types.CVSSv3.Impact): + This metric measures the impact to the + availability of the impacted component resulting + from a successfully exploited vulnerability. + """ + + class AttackVector(proto.Enum): + r"""This metric reflects the context by which vulnerability + exploitation is possible. + """ + ATTACK_VECTOR_UNSPECIFIED = 0 + ATTACK_VECTOR_NETWORK = 1 + ATTACK_VECTOR_ADJACENT = 2 + ATTACK_VECTOR_LOCAL = 3 + ATTACK_VECTOR_PHYSICAL = 4 + + class AttackComplexity(proto.Enum): + r"""This metric describes the conditions beyond the attacker's + control that must exist in order to exploit the vulnerability. + """ + ATTACK_COMPLEXITY_UNSPECIFIED = 0 + ATTACK_COMPLEXITY_LOW = 1 + ATTACK_COMPLEXITY_HIGH = 2 + + class PrivilegesRequired(proto.Enum): + r"""This metric describes the level of privileges an attacker + must possess before successfully exploiting the vulnerability. + """ + PRIVILEGES_REQUIRED_UNSPECIFIED = 0 + PRIVILEGES_REQUIRED_NONE = 1 + PRIVILEGES_REQUIRED_LOW = 2 + PRIVILEGES_REQUIRED_HIGH = 3 + + class UserInteraction(proto.Enum): + r"""This metric captures the requirement for a human user, other + than the attacker, to participate in the successful compromise + of the vulnerable component. + """ + USER_INTERACTION_UNSPECIFIED = 0 + USER_INTERACTION_NONE = 1 + USER_INTERACTION_REQUIRED = 2 + + class Scope(proto.Enum): + r"""The Scope metric captures whether a vulnerability in one + vulnerable component impacts resources in components beyond its + security scope. + """ + SCOPE_UNSPECIFIED = 0 + SCOPE_UNCHANGED = 1 + SCOPE_CHANGED = 2 + + class Impact(proto.Enum): + r"""The Impact metrics capture the effects of a successfully + exploited vulnerability on the component that suffers the worst + outcome that is most directly and predictably associated with + the attack. + """ + IMPACT_UNSPECIFIED = 0 + IMPACT_HIGH = 1 + IMPACT_LOW = 2 + IMPACT_NONE = 3 + + base_score = proto.Field(proto.FLOAT, number=1,) + exploitability_score = proto.Field(proto.FLOAT, number=2,) + impact_score = proto.Field(proto.FLOAT, number=3,) + attack_vector = proto.Field(proto.ENUM, number=5, enum=AttackVector,) + attack_complexity = proto.Field(proto.ENUM, number=6, enum=AttackComplexity,) + privileges_required = proto.Field(proto.ENUM, number=7, enum=PrivilegesRequired,) + user_interaction = proto.Field(proto.ENUM, number=8, enum=UserInteraction,) + scope = proto.Field(proto.ENUM, number=9, enum=Scope,) + confidentiality_impact = proto.Field(proto.ENUM, number=10, enum=Impact,) + integrity_impact = proto.Field(proto.ENUM, number=11, enum=Impact,) + availability_impact = proto.Field(proto.ENUM, number=12, enum=Impact,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/scripts/fixup_osconfig_v1_keywords.py b/scripts/fixup_osconfig_v1_keywords.py index b5accfb..9b58a4d 100644 --- a/scripts/fixup_osconfig_v1_keywords.py +++ b/scripts/fixup_osconfig_v1_keywords.py @@ -43,11 +43,15 @@ class osconfigCallTransformer(cst.CSTTransformer): 'create_patch_deployment': ('parent', 'patch_deployment_id', 'patch_deployment', ), 'delete_patch_deployment': ('name', ), 'execute_patch_job': ('parent', 'instance_filter', 'description', 'patch_config', 'duration', 'dry_run', 'display_name', 'rollout', ), + 'get_inventory': ('name', 'view', ), 'get_patch_deployment': ('name', ), 'get_patch_job': ('name', ), + 'get_vulnerability_report': ('name', ), + 'list_inventories': ('parent', 'view', 'page_size', 'page_token', 'filter', ), 'list_patch_deployments': ('parent', 'page_size', 'page_token', ), 'list_patch_job_instance_details': ('parent', 'page_size', 'page_token', 'filter', ), 'list_patch_jobs': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_vulnerability_reports': ('parent', 'page_size', 'page_token', 'filter', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/tests/unit/gapic/osconfig_v1/test_os_config_zonal_service.py b/tests/unit/gapic/osconfig_v1/test_os_config_zonal_service.py new file mode 100644 index 0000000..3da984b --- /dev/null +++ b/tests/unit/gapic/osconfig_v1/test_os_config_zonal_service.py @@ -0,0 +1,2357 @@ +# -*- 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 packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_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 as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.osconfig_v1.services.os_config_zonal_service import ( + OsConfigZonalServiceAsyncClient, +) +from google.cloud.osconfig_v1.services.os_config_zonal_service import ( + OsConfigZonalServiceClient, +) +from google.cloud.osconfig_v1.services.os_config_zonal_service import pagers +from google.cloud.osconfig_v1.services.os_config_zonal_service import transports +from google.cloud.osconfig_v1.services.os_config_zonal_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import vulnerability +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + + +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 OsConfigZonalServiceClient._get_default_mtls_endpoint(None) is None + assert ( + OsConfigZonalServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + OsConfigZonalServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + OsConfigZonalServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OsConfigZonalServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OsConfigZonalServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [OsConfigZonalServiceClient, OsConfigZonalServiceAsyncClient,] +) +def test_os_config_zonal_service_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "osconfig.googleapis.com:443" + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.OsConfigZonalServiceGrpcTransport, "grpc"), + (transports.OsConfigZonalServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_os_config_zonal_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class", [OsConfigZonalServiceClient, OsConfigZonalServiceAsyncClient,] +) +def test_os_config_zonal_service_client_from_service_account_file(client_class): + creds = ga_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 + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "osconfig.googleapis.com:443" + + +def test_os_config_zonal_service_client_get_transport_class(): + transport = OsConfigZonalServiceClient.get_transport_class() + available_transports = [ + transports.OsConfigZonalServiceGrpcTransport, + ] + assert transport in available_transports + + transport = OsConfigZonalServiceClient.get_transport_class("grpc") + assert transport == transports.OsConfigZonalServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OsConfigZonalServiceClient, + transports.OsConfigZonalServiceGrpcTransport, + "grpc", + ), + ( + OsConfigZonalServiceAsyncClient, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + OsConfigZonalServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OsConfigZonalServiceClient), +) +@mock.patch.object( + OsConfigZonalServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OsConfigZonalServiceAsyncClient), +) +def test_os_config_zonal_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(OsConfigZonalServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_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(OsConfigZonalServiceClient, "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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + 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, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + OsConfigZonalServiceClient, + transports.OsConfigZonalServiceGrpcTransport, + "grpc", + "true", + ), + ( + OsConfigZonalServiceAsyncClient, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + OsConfigZonalServiceClient, + transports.OsConfigZonalServiceGrpcTransport, + "grpc", + "false", + ), + ( + OsConfigZonalServiceAsyncClient, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + OsConfigZonalServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OsConfigZonalServiceClient), +) +@mock.patch.object( + OsConfigZonalServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OsConfigZonalServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_os_config_zonal_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + 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) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + 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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OsConfigZonalServiceClient, + transports.OsConfigZonalServiceGrpcTransport, + "grpc", + ), + ( + OsConfigZonalServiceAsyncClient, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_os_config_zonal_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"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OsConfigZonalServiceClient, + transports.OsConfigZonalServiceGrpcTransport, + "grpc", + ), + ( + OsConfigZonalServiceAsyncClient, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_os_config_zonal_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, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_os_config_zonal_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.osconfig_v1.services.os_config_zonal_service.transports.OsConfigZonalServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = OsConfigZonalServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + +def test_get_inventory( + transport: str = "grpc", request_type=inventory.GetInventoryRequest +): + client = OsConfigZonalServiceClient( + credentials=ga_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_inventory), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.Inventory(name="name_value",) + response = client.get_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.GetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, inventory.Inventory) + assert response.name == "name_value" + + +def test_get_inventory_from_dict(): + test_get_inventory(request_type=dict) + + +def test_get_inventory_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_inventory), "__call__") as call: + client.get_inventory() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.GetInventoryRequest() + + +@pytest.mark.asyncio +async def test_get_inventory_async( + transport: str = "grpc_asyncio", request_type=inventory.GetInventoryRequest +): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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_inventory), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + inventory.Inventory(name="name_value",) + ) + response = await client.get_inventory(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.GetInventoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, inventory.Inventory) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_inventory_async_from_dict(): + await test_get_inventory_async(request_type=dict) + + +def test_get_inventory_field_headers(): + client = OsConfigZonalServiceClient( + credentials=ga_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 = inventory.GetInventoryRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_inventory), "__call__") as call: + call.return_value = inventory.Inventory() + client.get_inventory(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_inventory_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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 = inventory.GetInventoryRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_inventory), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.Inventory()) + await client.get_inventory(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_inventory_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_inventory), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.Inventory() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_inventory(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_inventory_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_inventory( + inventory.GetInventoryRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_inventory_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_inventory), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.Inventory() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(inventory.Inventory()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_inventory(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_inventory_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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_inventory( + inventory.GetInventoryRequest(), name="name_value", + ) + + +def test_list_inventories( + transport: str = "grpc", request_type=inventory.ListInventoriesRequest +): + client = OsConfigZonalServiceClient( + credentials=ga_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_inventories), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.ListInventoriesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.ListInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInventoriesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_inventories_from_dict(): + test_list_inventories(request_type=dict) + + +def test_list_inventories_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_inventories), "__call__") as call: + client.list_inventories() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.ListInventoriesRequest() + + +@pytest.mark.asyncio +async def test_list_inventories_async( + transport: str = "grpc_asyncio", request_type=inventory.ListInventoriesRequest +): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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_inventories), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + inventory.ListInventoriesResponse(next_page_token="next_page_token_value",) + ) + response = await client.list_inventories(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == inventory.ListInventoriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInventoriesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_inventories_async_from_dict(): + await test_list_inventories_async(request_type=dict) + + +def test_list_inventories_field_headers(): + client = OsConfigZonalServiceClient( + credentials=ga_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 = inventory.ListInventoriesRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_inventories), "__call__") as call: + call.return_value = inventory.ListInventoriesResponse() + client.list_inventories(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_inventories_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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 = inventory.ListInventoriesRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_inventories), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + inventory.ListInventoriesResponse() + ) + await client.list_inventories(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_inventories_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_inventories), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.ListInventoriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_inventories(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_inventories_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_inventories( + inventory.ListInventoriesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_inventories_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_inventories), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = inventory.ListInventoriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + inventory.ListInventoriesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_inventories(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_inventories_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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_inventories( + inventory.ListInventoriesRequest(), parent="parent_value", + ) + + +def test_list_inventories_pager(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_inventories), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + inventory.Inventory(), + ], + next_page_token="abc", + ), + inventory.ListInventoriesResponse(inventories=[], next_page_token="def",), + inventory.ListInventoriesResponse( + inventories=[inventory.Inventory(),], next_page_token="ghi", + ), + inventory.ListInventoriesResponse( + inventories=[inventory.Inventory(), inventory.Inventory(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_inventories(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, inventory.Inventory) for i in results) + + +def test_list_inventories_pages(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_inventories), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + inventory.Inventory(), + ], + next_page_token="abc", + ), + inventory.ListInventoriesResponse(inventories=[], next_page_token="def",), + inventory.ListInventoriesResponse( + inventories=[inventory.Inventory(),], next_page_token="ghi", + ), + inventory.ListInventoriesResponse( + inventories=[inventory.Inventory(), inventory.Inventory(),], + ), + RuntimeError, + ) + pages = list(client.list_inventories(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_inventories_async_pager(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + inventory.Inventory(), + ], + next_page_token="abc", + ), + inventory.ListInventoriesResponse(inventories=[], next_page_token="def",), + inventory.ListInventoriesResponse( + inventories=[inventory.Inventory(),], next_page_token="ghi", + ), + inventory.ListInventoriesResponse( + inventories=[inventory.Inventory(), inventory.Inventory(),], + ), + RuntimeError, + ) + async_pager = await client.list_inventories(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, inventory.Inventory) for i in responses) + + +@pytest.mark.asyncio +async def test_list_inventories_async_pages(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_inventories), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + inventory.ListInventoriesResponse( + inventories=[ + inventory.Inventory(), + inventory.Inventory(), + inventory.Inventory(), + ], + next_page_token="abc", + ), + inventory.ListInventoriesResponse(inventories=[], next_page_token="def",), + inventory.ListInventoriesResponse( + inventories=[inventory.Inventory(),], next_page_token="ghi", + ), + inventory.ListInventoriesResponse( + inventories=[inventory.Inventory(), inventory.Inventory(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_inventories(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_vulnerability_report( + transport: str = "grpc", request_type=vulnerability.GetVulnerabilityReportRequest +): + client = OsConfigZonalServiceClient( + credentials=ga_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_vulnerability_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.VulnerabilityReport(name="name_value",) + response = client.get_vulnerability_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.GetVulnerabilityReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, vulnerability.VulnerabilityReport) + assert response.name == "name_value" + + +def test_get_vulnerability_report_from_dict(): + test_get_vulnerability_report(request_type=dict) + + +def test_get_vulnerability_report_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), "__call__" + ) as call: + client.get_vulnerability_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.GetVulnerabilityReportRequest() + + +@pytest.mark.asyncio +async def test_get_vulnerability_report_async( + transport: str = "grpc_asyncio", + request_type=vulnerability.GetVulnerabilityReportRequest, +): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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_vulnerability_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vulnerability.VulnerabilityReport(name="name_value",) + ) + response = await client.get_vulnerability_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.GetVulnerabilityReportRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, vulnerability.VulnerabilityReport) + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_vulnerability_report_async_from_dict(): + await test_get_vulnerability_report_async(request_type=dict) + + +def test_get_vulnerability_report_field_headers(): + client = OsConfigZonalServiceClient( + credentials=ga_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 = vulnerability.GetVulnerabilityReportRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), "__call__" + ) as call: + call.return_value = vulnerability.VulnerabilityReport() + client.get_vulnerability_report(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_vulnerability_report_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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 = vulnerability.GetVulnerabilityReportRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vulnerability.VulnerabilityReport() + ) + await client.get_vulnerability_report(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_vulnerability_report_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.VulnerabilityReport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_vulnerability_report(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_vulnerability_report_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_vulnerability_report( + vulnerability.GetVulnerabilityReportRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_vulnerability_report_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_vulnerability_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.VulnerabilityReport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vulnerability.VulnerabilityReport() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_vulnerability_report(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_vulnerability_report_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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_vulnerability_report( + vulnerability.GetVulnerabilityReportRequest(), name="name_value", + ) + + +def test_list_vulnerability_reports( + transport: str = "grpc", request_type=vulnerability.ListVulnerabilityReportsRequest +): + client = OsConfigZonalServiceClient( + credentials=ga_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_vulnerability_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.ListVulnerabilityReportsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_vulnerability_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.ListVulnerabilityReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVulnerabilityReportsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_vulnerability_reports_from_dict(): + test_list_vulnerability_reports(request_type=dict) + + +def test_list_vulnerability_reports_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), "__call__" + ) as call: + client.list_vulnerability_reports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.ListVulnerabilityReportsRequest() + + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_async( + transport: str = "grpc_asyncio", + request_type=vulnerability.ListVulnerabilityReportsRequest, +): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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_vulnerability_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vulnerability.ListVulnerabilityReportsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_vulnerability_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == vulnerability.ListVulnerabilityReportsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVulnerabilityReportsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_async_from_dict(): + await test_list_vulnerability_reports_async(request_type=dict) + + +def test_list_vulnerability_reports_field_headers(): + client = OsConfigZonalServiceClient( + credentials=ga_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 = vulnerability.ListVulnerabilityReportsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), "__call__" + ) as call: + call.return_value = vulnerability.ListVulnerabilityReportsResponse() + client.list_vulnerability_reports(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_vulnerability_reports_field_headers_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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 = vulnerability.ListVulnerabilityReportsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vulnerability.ListVulnerabilityReportsResponse() + ) + await client.list_vulnerability_reports(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_vulnerability_reports_flattened(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.ListVulnerabilityReportsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_vulnerability_reports(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_vulnerability_reports_flattened_error(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_vulnerability_reports( + vulnerability.ListVulnerabilityReportsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_flattened_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vulnerability.ListVulnerabilityReportsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vulnerability.ListVulnerabilityReportsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_vulnerability_reports(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_vulnerability_reports_flattened_error_async(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_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_vulnerability_reports( + vulnerability.ListVulnerabilityReportsRequest(), parent="parent_value", + ) + + +def test_list_vulnerability_reports_pager(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + next_page_token="abc", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[], next_page_token="def", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[vulnerability.VulnerabilityReport(),], + next_page_token="ghi", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_vulnerability_reports(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, vulnerability.VulnerabilityReport) for i in results) + + +def test_list_vulnerability_reports_pages(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + next_page_token="abc", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[], next_page_token="def", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[vulnerability.VulnerabilityReport(),], + next_page_token="ghi", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_vulnerability_reports(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_vulnerability_reports_async_pager(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + next_page_token="abc", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[], next_page_token="def", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[vulnerability.VulnerabilityReport(),], + next_page_token="ghi", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_vulnerability_reports(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, vulnerability.VulnerabilityReport) for i in responses) + + +@pytest.mark.asyncio +async def test_list_vulnerability_reports_async_pages(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_vulnerability_reports), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + next_page_token="abc", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[], next_page_token="def", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[vulnerability.VulnerabilityReport(),], + next_page_token="ghi", + ), + vulnerability.ListVulnerabilityReportsResponse( + vulnerability_reports=[ + vulnerability.VulnerabilityReport(), + vulnerability.VulnerabilityReport(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_vulnerability_reports(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.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigZonalServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OsConfigZonalServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OsConfigZonalServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OsConfigZonalServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OsConfigZonalServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance(client.transport, transports.OsConfigZonalServiceGrpcTransport,) + + +def test_os_config_zonal_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OsConfigZonalServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_os_config_zonal_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.osconfig_v1.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.OsConfigZonalServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_inventory", + "list_inventories", + "get_vulnerability_report", + "list_vulnerability_reports", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_os_config_zonal_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.osconfig_v1.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigZonalServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_os_config_zonal_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.osconfig_v1.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigZonalServiceTransport( + 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_os_config_zonal_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.osconfig_v1.services.os_config_zonal_service.transports.OsConfigZonalServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OsConfigZonalServiceTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_os_config_zonal_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + OsConfigZonalServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_os_config_zonal_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + OsConfigZonalServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_os_config_zonal_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_os_config_zonal_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.OsConfigZonalServiceGrpcTransport, grpc_helpers), + (transports.OsConfigZonalServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_os_config_zonal_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "osconfig.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="osconfig.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + ], +) +def test_os_config_zonal_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_os_config_zonal_service_host_no_port(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="osconfig.googleapis.com" + ), + ) + assert client.transport._host == "osconfig.googleapis.com:443" + + +def test_os_config_zonal_service_host_with_port(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="osconfig.googleapis.com:8000" + ), + ) + assert client.transport._host == "osconfig.googleapis.com:8000" + + +def test_os_config_zonal_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OsConfigZonalServiceGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_os_config_zonal_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OsConfigZonalServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + ], +) +def test_os_config_zonal_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + 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 + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + 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=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.OsConfigZonalServiceGrpcTransport, + transports.OsConfigZonalServiceGrpcAsyncIOTransport, + ], +) +def test_os_config_zonal_service_transport_channel_mtls_with_adc(transport_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), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_instance_path(): + project = "squid" + zone = "clam" + instance = "whelk" + expected = "projects/{project}/zones/{zone}/instances/{instance}".format( + project=project, zone=zone, instance=instance, + ) + actual = OsConfigZonalServiceClient.instance_path(project, zone, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "octopus", + "zone": "oyster", + "instance": "nudibranch", + } + path = OsConfigZonalServiceClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_instance_path(path) + assert expected == actual + + +def test_inventory_path(): + project = "cuttlefish" + location = "mussel" + instance = "winkle" + expected = "projects/{project}/locations/{location}/instances/{instance}/inventory".format( + project=project, location=location, instance=instance, + ) + actual = OsConfigZonalServiceClient.inventory_path(project, location, instance) + assert expected == actual + + +def test_parse_inventory_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "instance": "abalone", + } + path = OsConfigZonalServiceClient.inventory_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_inventory_path(path) + assert expected == actual + + +def test_vulnerability_report_path(): + project = "squid" + location = "clam" + instance = "whelk" + expected = "projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport".format( + project=project, location=location, instance=instance, + ) + actual = OsConfigZonalServiceClient.vulnerability_report_path( + project, location, instance + ) + assert expected == actual + + +def test_parse_vulnerability_report_path(): + expected = { + "project": "octopus", + "location": "oyster", + "instance": "nudibranch", + } + path = OsConfigZonalServiceClient.vulnerability_report_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_vulnerability_report_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = OsConfigZonalServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = OsConfigZonalServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder,) + actual = OsConfigZonalServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = OsConfigZonalServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization,) + actual = OsConfigZonalServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = OsConfigZonalServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project,) + actual = OsConfigZonalServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = OsConfigZonalServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = OsConfigZonalServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = OsConfigZonalServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.OsConfigZonalServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.OsConfigZonalServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = OsConfigZonalServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info)