From 44c158dd19c4329678e170733377494821ca955f Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 4 Nov 2021 09:18:12 +0000 Subject: [PATCH] feat: add OS policy assignment rpcs (#142) - [ ] Regenerate this pull request now. Committer: @adjackura PiperOrigin-RevId: 407422484 Source-Link: https://github.com/googleapis/googleapis/commit/c11bc3edab44a009dfafd13525d3a38548d823fa Source-Link: https://github.com/googleapis/googleapis-gen/commit/d2df80a5a61299ed2dff12bfaf2886619117e9ce Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiZDJkZjgwYTVhNjEyOTllZDJkZmYxMmJmYWYyODg2NjE5MTE3ZTljZSJ9 --- google/cloud/osconfig/__init__.py | 56 + google/cloud/osconfig_v1/__init__.py | 30 + google/cloud/osconfig_v1/gapic_metadata.json | 80 + .../os_config_zonal_service/async_client.py | 828 +++++ .../os_config_zonal_service/client.py | 902 ++++++ .../os_config_zonal_service/pagers.py | 424 +++ .../transports/base.py | 138 + .../transports/grpc.py | 301 ++ .../transports/grpc_asyncio.py | 303 ++ google/cloud/osconfig_v1/types/__init__.py | 34 + google/cloud/osconfig_v1/types/os_policy.py | 806 +++++ .../types/os_policy_assignment_reports.py | 328 ++ .../types/os_policy_assignments.py | 455 +++ .../os_config_zonal_service/async_client.py | 1 - .../os_config_zonal_service/client.py | 1 - scripts/fixup_osconfig_v1_keywords.py | 8 + .../test_os_config_zonal_service.py | 2688 ++++++++++++++++- 17 files changed, 7359 insertions(+), 24 deletions(-) create mode 100644 google/cloud/osconfig_v1/types/os_policy.py create mode 100644 google/cloud/osconfig_v1/types/os_policy_assignment_reports.py create mode 100644 google/cloud/osconfig_v1/types/os_policy_assignments.py diff --git a/google/cloud/osconfig/__init__.py b/google/cloud/osconfig/__init__.py index 26f2833..57a6115 100644 --- a/google/cloud/osconfig/__init__.py +++ b/google/cloud/osconfig/__init__.py @@ -32,6 +32,47 @@ 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.os_policy import OSPolicy +from google.cloud.osconfig_v1.types.os_policy_assignment_reports import ( + GetOSPolicyAssignmentReportRequest, +) +from google.cloud.osconfig_v1.types.os_policy_assignment_reports import ( + ListOSPolicyAssignmentReportsRequest, +) +from google.cloud.osconfig_v1.types.os_policy_assignment_reports import ( + ListOSPolicyAssignmentReportsResponse, +) +from google.cloud.osconfig_v1.types.os_policy_assignment_reports import ( + OSPolicyAssignmentReport, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + CreateOSPolicyAssignmentRequest, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + DeleteOSPolicyAssignmentRequest, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + GetOSPolicyAssignmentRequest, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + ListOSPolicyAssignmentRevisionsRequest, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + ListOSPolicyAssignmentRevisionsResponse, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + ListOSPolicyAssignmentsRequest, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + ListOSPolicyAssignmentsResponse, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import OSPolicyAssignment +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + OSPolicyAssignmentOperationMetadata, +) +from google.cloud.osconfig_v1.types.os_policy_assignments import ( + UpdateOSPolicyAssignmentRequest, +) from google.cloud.osconfig_v1.types.osconfig_common import FixedOrPercent from google.cloud.osconfig_v1.types.patch_deployments import ( CreatePatchDeploymentRequest, @@ -91,6 +132,21 @@ "ListInventoriesRequest", "ListInventoriesResponse", "InventoryView", + "OSPolicy", + "GetOSPolicyAssignmentReportRequest", + "ListOSPolicyAssignmentReportsRequest", + "ListOSPolicyAssignmentReportsResponse", + "OSPolicyAssignmentReport", + "CreateOSPolicyAssignmentRequest", + "DeleteOSPolicyAssignmentRequest", + "GetOSPolicyAssignmentRequest", + "ListOSPolicyAssignmentRevisionsRequest", + "ListOSPolicyAssignmentRevisionsResponse", + "ListOSPolicyAssignmentsRequest", + "ListOSPolicyAssignmentsResponse", + "OSPolicyAssignment", + "OSPolicyAssignmentOperationMetadata", + "UpdateOSPolicyAssignmentRequest", "FixedOrPercent", "CreatePatchDeploymentRequest", "DeletePatchDeploymentRequest", diff --git a/google/cloud/osconfig_v1/__init__.py b/google/cloud/osconfig_v1/__init__.py index 5e8a826..917e147 100644 --- a/google/cloud/osconfig_v1/__init__.py +++ b/google/cloud/osconfig_v1/__init__.py @@ -24,6 +24,21 @@ from .types.inventory import ListInventoriesRequest from .types.inventory import ListInventoriesResponse from .types.inventory import InventoryView +from .types.os_policy import OSPolicy +from .types.os_policy_assignment_reports import GetOSPolicyAssignmentReportRequest +from .types.os_policy_assignment_reports import ListOSPolicyAssignmentReportsRequest +from .types.os_policy_assignment_reports import ListOSPolicyAssignmentReportsResponse +from .types.os_policy_assignment_reports import OSPolicyAssignmentReport +from .types.os_policy_assignments import CreateOSPolicyAssignmentRequest +from .types.os_policy_assignments import DeleteOSPolicyAssignmentRequest +from .types.os_policy_assignments import GetOSPolicyAssignmentRequest +from .types.os_policy_assignments import ListOSPolicyAssignmentRevisionsRequest +from .types.os_policy_assignments import ListOSPolicyAssignmentRevisionsResponse +from .types.os_policy_assignments import ListOSPolicyAssignmentsRequest +from .types.os_policy_assignments import ListOSPolicyAssignmentsResponse +from .types.os_policy_assignments import OSPolicyAssignment +from .types.os_policy_assignments import OSPolicyAssignmentOperationMetadata +from .types.os_policy_assignments import UpdateOSPolicyAssignmentRequest from .types.osconfig_common import FixedOrPercent from .types.patch_deployments import CreatePatchDeploymentRequest from .types.patch_deployments import DeletePatchDeploymentRequest @@ -69,7 +84,9 @@ "AptSettings", "CVSSv3", "CancelPatchJobRequest", + "CreateOSPolicyAssignmentRequest", "CreatePatchDeploymentRequest", + "DeleteOSPolicyAssignmentRequest", "DeletePatchDeploymentRequest", "ExecStep", "ExecStepConfig", @@ -77,6 +94,8 @@ "FixedOrPercent", "GcsObject", "GetInventoryRequest", + "GetOSPolicyAssignmentReportRequest", + "GetOSPolicyAssignmentRequest", "GetPatchDeploymentRequest", "GetPatchJobRequest", "GetVulnerabilityReportRequest", @@ -86,6 +105,12 @@ "InventoryView", "ListInventoriesRequest", "ListInventoriesResponse", + "ListOSPolicyAssignmentReportsRequest", + "ListOSPolicyAssignmentReportsResponse", + "ListOSPolicyAssignmentRevisionsRequest", + "ListOSPolicyAssignmentRevisionsResponse", + "ListOSPolicyAssignmentsRequest", + "ListOSPolicyAssignmentsResponse", "ListPatchDeploymentsRequest", "ListPatchDeploymentsResponse", "ListPatchJobInstanceDetailsRequest", @@ -95,6 +120,10 @@ "ListVulnerabilityReportsRequest", "ListVulnerabilityReportsResponse", "MonthlySchedule", + "OSPolicy", + "OSPolicyAssignment", + "OSPolicyAssignmentOperationMetadata", + "OSPolicyAssignmentReport", "OneTimeSchedule", "OsConfigServiceClient", "OsConfigZonalServiceClient", @@ -105,6 +134,7 @@ "PatchJobInstanceDetails", "PatchRollout", "RecurringSchedule", + "UpdateOSPolicyAssignmentRequest", "VulnerabilityReport", "WeekDayOfMonth", "WeeklySchedule", diff --git a/google/cloud/osconfig_v1/gapic_metadata.json b/google/cloud/osconfig_v1/gapic_metadata.json index 1f20b04..e23cfcc 100644 --- a/google/cloud/osconfig_v1/gapic_metadata.json +++ b/google/cloud/osconfig_v1/gapic_metadata.json @@ -114,11 +114,31 @@ "grpc": { "libraryClient": "OsConfigZonalServiceClient", "rpcs": { + "CreateOSPolicyAssignment": { + "methods": [ + "create_os_policy_assignment" + ] + }, + "DeleteOSPolicyAssignment": { + "methods": [ + "delete_os_policy_assignment" + ] + }, "GetInventory": { "methods": [ "get_inventory" ] }, + "GetOSPolicyAssignment": { + "methods": [ + "get_os_policy_assignment" + ] + }, + "GetOSPolicyAssignmentReport": { + "methods": [ + "get_os_policy_assignment_report" + ] + }, "GetVulnerabilityReport": { "methods": [ "get_vulnerability_report" @@ -129,21 +149,61 @@ "list_inventories" ] }, + "ListOSPolicyAssignmentReports": { + "methods": [ + "list_os_policy_assignment_reports" + ] + }, + "ListOSPolicyAssignmentRevisions": { + "methods": [ + "list_os_policy_assignment_revisions" + ] + }, + "ListOSPolicyAssignments": { + "methods": [ + "list_os_policy_assignments" + ] + }, "ListVulnerabilityReports": { "methods": [ "list_vulnerability_reports" ] + }, + "UpdateOSPolicyAssignment": { + "methods": [ + "update_os_policy_assignment" + ] } } }, "grpc-async": { "libraryClient": "OsConfigZonalServiceAsyncClient", "rpcs": { + "CreateOSPolicyAssignment": { + "methods": [ + "create_os_policy_assignment" + ] + }, + "DeleteOSPolicyAssignment": { + "methods": [ + "delete_os_policy_assignment" + ] + }, "GetInventory": { "methods": [ "get_inventory" ] }, + "GetOSPolicyAssignment": { + "methods": [ + "get_os_policy_assignment" + ] + }, + "GetOSPolicyAssignmentReport": { + "methods": [ + "get_os_policy_assignment_report" + ] + }, "GetVulnerabilityReport": { "methods": [ "get_vulnerability_report" @@ -154,10 +214,30 @@ "list_inventories" ] }, + "ListOSPolicyAssignmentReports": { + "methods": [ + "list_os_policy_assignment_reports" + ] + }, + "ListOSPolicyAssignmentRevisions": { + "methods": [ + "list_os_policy_assignment_revisions" + ] + }, + "ListOSPolicyAssignments": { + "methods": [ + "list_os_policy_assignments" + ] + }, "ListVulnerabilityReports": { "methods": [ "list_vulnerability_reports" ] + }, + "UpdateOSPolicyAssignment": { + "methods": [ + "update_os_policy_assignment" + ] } } } 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 index 20ed650..771620c 100644 --- 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 @@ -28,9 +28,16 @@ OptionalRetry = Union[retries.Retry, object] +from google.api_core import operation # type: ignore +from google.api_core import operation_async # 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 os_policy +from google.cloud.osconfig_v1.types import os_policy_assignment_reports +from google.cloud.osconfig_v1.types import os_policy_assignments from google.cloud.osconfig_v1.types import vulnerability +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import OsConfigZonalServiceGrpcAsyncIOTransport @@ -51,8 +58,26 @@ class OsConfigZonalServiceAsyncClient: instance_path = staticmethod(OsConfigZonalServiceClient.instance_path) parse_instance_path = staticmethod(OsConfigZonalServiceClient.parse_instance_path) + instance_os_policy_assignment_path = staticmethod( + OsConfigZonalServiceClient.instance_os_policy_assignment_path + ) + parse_instance_os_policy_assignment_path = staticmethod( + OsConfigZonalServiceClient.parse_instance_os_policy_assignment_path + ) inventory_path = staticmethod(OsConfigZonalServiceClient.inventory_path) parse_inventory_path = staticmethod(OsConfigZonalServiceClient.parse_inventory_path) + os_policy_assignment_path = staticmethod( + OsConfigZonalServiceClient.os_policy_assignment_path + ) + parse_os_policy_assignment_path = staticmethod( + OsConfigZonalServiceClient.parse_os_policy_assignment_path + ) + os_policy_assignment_report_path = staticmethod( + OsConfigZonalServiceClient.os_policy_assignment_report_path + ) + parse_os_policy_assignment_report_path = staticmethod( + OsConfigZonalServiceClient.parse_os_policy_assignment_report_path + ) vulnerability_report_path = staticmethod( OsConfigZonalServiceClient.vulnerability_report_path ) @@ -178,6 +203,809 @@ def __init__( client_info=client_info, ) + async def create_os_policy_assignment( + self, + request: Union[ + os_policy_assignments.CreateOSPolicyAssignmentRequest, dict + ] = None, + *, + parent: str = None, + os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, + os_policy_assignment_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Create an OS policy assignment. + + This method also creates the first revision of the OS policy + assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (Union[google.cloud.osconfig_v1.types.CreateOSPolicyAssignmentRequest, dict]): + The request object. A request message to create an OS + policy assignment + parent (:class:`str`): + Required. The parent resource name in + the form: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + os_policy_assignment (:class:`google.cloud.osconfig_v1.types.OSPolicyAssignment`): + Required. The OS policy assignment to + be created. + + This corresponds to the ``os_policy_assignment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + os_policy_assignment_id (:class:`str`): + Required. The logical name of the OS policy assignment + in the project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + + This corresponds to the ``os_policy_assignment_id`` 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.osconfig_v1.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # 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, os_policy_assignment, os_policy_assignment_id] + ) + 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 = os_policy_assignments.CreateOSPolicyAssignmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if os_policy_assignment is not None: + request.os_policy_assignment = os_policy_assignment + if os_policy_assignment_id is not None: + request.os_policy_assignment_id = os_policy_assignment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_os_policy_assignment, + 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,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + os_policy_assignments.OSPolicyAssignment, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + async def update_os_policy_assignment( + self, + request: Union[ + os_policy_assignments.UpdateOSPolicyAssignmentRequest, dict + ] = None, + *, + os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Update an existing OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (Union[google.cloud.osconfig_v1.types.UpdateOSPolicyAssignmentRequest, dict]): + The request object. A request message to update an OS + policy assignment + os_policy_assignment (:class:`google.cloud.osconfig_v1.types.OSPolicyAssignment`): + Required. The updated OS policy + assignment. + + This corresponds to the ``os_policy_assignment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask that controls + which fields of the assignment should be + updated. + + This corresponds to the ``update_mask`` 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.osconfig_v1.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # 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([os_policy_assignment, update_mask]) + 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 = os_policy_assignments.UpdateOSPolicyAssignmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if os_policy_assignment is not None: + request.os_policy_assignment = os_policy_assignment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_os_policy_assignment, + 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( + (("os_policy_assignment.name", request.os_policy_assignment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + os_policy_assignments.OSPolicyAssignment, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_os_policy_assignment( + self, + request: Union[os_policy_assignments.GetOSPolicyAssignmentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> os_policy_assignments.OSPolicyAssignment: + r"""Retrieve an existing OS policy assignment. + + This method always returns the latest revision. In order to + retrieve a previous revision of the assignment, also provide the + revision ID in the ``name`` parameter. + + Args: + request (Union[google.cloud.osconfig_v1.types.GetOSPolicyAssignmentRequest, dict]): + The request object. A request message to get an OS + policy assignment + name (:class:`str`): + Required. The resource name of OS policy assignment. + + Format: + ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` + + 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.OSPolicyAssignment: + OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # 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 = os_policy_assignments.GetOSPolicyAssignmentRequest(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_os_policy_assignment, + 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_os_policy_assignments( + self, + request: Union[ + os_policy_assignments.ListOSPolicyAssignmentsRequest, dict + ] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentsAsyncPager: + r"""List the OS policy assignments under the parent + resource. + For each OS policy assignment, the latest revision is + returned. + + Args: + request (Union[google.cloud.osconfig_v1.types.ListOSPolicyAssignmentsRequest, dict]): + The request object. A request message to list OS policy + assignments for a parent resource + parent (:class:`str`): + Required. The parent resource name. + 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.ListOSPolicyAssignmentsAsyncPager: + A response message for listing all + assignments under given parent. + 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest(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_os_policy_assignments, + 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.ListOSPolicyAssignmentsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_os_policy_assignment_revisions( + self, + request: Union[ + os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, dict + ] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentRevisionsAsyncPager: + r"""List the OS policy assignment revisions for a given + OS policy assignment. + + Args: + request (Union[google.cloud.osconfig_v1.types.ListOSPolicyAssignmentRevisionsRequest, dict]): + The request object. A request message to list revisions + for a OS policy assignment + name (:class:`str`): + Required. The name of the OS policy + assignment to list revisions for. + + 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.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentRevisionsAsyncPager: + A response message for listing all + revisions for a OS policy assignment. + 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([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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(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.list_os_policy_assignment_revisions, + 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,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListOSPolicyAssignmentRevisionsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_os_policy_assignment( + self, + request: Union[ + os_policy_assignments.DeleteOSPolicyAssignmentRequest, dict + ] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Delete the OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + If the LRO completes and is not cancelled, all revisions + associated with the OS policy assignment are deleted. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (Union[google.cloud.osconfig_v1.types.DeleteOSPolicyAssignmentRequest, dict]): + The request object. A request message for deleting a OS + policy assignment. + name (:class:`str`): + Required. The name of the OS policy + assignment to be deleted + + 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 = os_policy_assignments.DeleteOSPolicyAssignmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_os_policy_assignment, + 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,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_os_policy_assignment_report( + self, + request: Union[ + os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest, dict + ] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> os_policy_assignment_reports.OSPolicyAssignmentReport: + r"""Get the OS policy asssignment report for the + specified Compute Engine VM instance. + + Args: + request (Union[google.cloud.osconfig_v1.types.GetOSPolicyAssignmentReportRequest, dict]): + The request object. Get a report of the OS policy + assignment for a VM instance. + name (:class:`str`): + Required. API resource name for OS policy assignment + report. + + Format: + ``/projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}/report`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance_id}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. For + ``{assignment_id}``, the OSPolicyAssignment id must 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.OSPolicyAssignmentReport: + A report of the OS policy assignment + status for a given instance. + + """ + # 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 = os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest( + 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_os_policy_assignment_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_os_policy_assignment_reports( + self, + request: Union[ + os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest, dict + ] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentReportsAsyncPager: + r"""List OS policy asssignment reports for all Compute + Engine VM instances in the specified zone. + + Args: + request (Union[google.cloud.osconfig_v1.types.ListOSPolicyAssignmentReportsRequest, dict]): + The request object. List the OS policy assignment + reports for VM instances. + parent (:class:`str`): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}/reports`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either ``instance-name``, ``instance-id``, or ``-`` can + be provided. If '-' is provided, the response will + include OSPolicyAssignmentReports for all instances in + the project/location. For ``{assignment}``, either + ``assignment-id`` or ``-`` can be provided. If '-' is + provided, the response will include + OSPolicyAssignmentReports for all OSPolicyAssignments in + the project/location. Either {instance} or {assignment} + must be ``-``. + + For example: + ``projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/-/reports`` + returns all reports for the instance + ``projects/{project}/locations/{location}/instances/-/osPolicyAssignments/{assignment-id}/reports`` + returns all the reports for the given assignment across + all instances. + ``projects/{project}/locations/{location}/instances/-/osPolicyAssignments/-/reports`` + returns all the reports for all assignments across all + instances. + + 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.ListOSPolicyAssignmentReportsAsyncPager: + A response message for listing OS + Policy assignment reports including the + page of results and page token. + 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 = os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest( + 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_os_policy_assignment_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.ListOSPolicyAssignmentReportsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + async def get_inventory( self, request: Union[inventory.GetInventoryRequest, dict] = None, 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 index 906f5c8..7aaee4d 100644 --- a/google/cloud/osconfig_v1/services/os_config_zonal_service/client.py +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/client.py @@ -32,9 +32,16 @@ OptionalRetry = Union[retries.Retry, object] +from google.api_core import operation # type: ignore +from google.api_core import operation_async # 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 os_policy +from google.cloud.osconfig_v1.types import os_policy_assignment_reports +from google.cloud.osconfig_v1.types import os_policy_assignments from google.cloud.osconfig_v1.types import vulnerability +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import OsConfigZonalServiceGrpcTransport @@ -181,6 +188,27 @@ def parse_instance_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def instance_os_policy_assignment_path( + project: str, location: str, instance: str, assignment: str, + ) -> str: + """Returns a fully-qualified instance_os_policy_assignment string.""" + return "projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}".format( + project=project, + location=location, + instance=instance, + assignment=assignment, + ) + + @staticmethod + def parse_instance_os_policy_assignment_path(path: str) -> Dict[str, str]: + """Parses a instance_os_policy_assignment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/osPolicyAssignments/(?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.""" @@ -197,6 +225,47 @@ def parse_inventory_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def os_policy_assignment_path( + project: str, location: str, os_policy_assignment: str, + ) -> str: + """Returns a fully-qualified os_policy_assignment string.""" + return "projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}".format( + project=project, + location=location, + os_policy_assignment=os_policy_assignment, + ) + + @staticmethod + def parse_os_policy_assignment_path(path: str) -> Dict[str, str]: + """Parses a os_policy_assignment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/osPolicyAssignments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def os_policy_assignment_report_path( + project: str, location: str, instance: str, assignment: str, + ) -> str: + """Returns a fully-qualified os_policy_assignment_report string.""" + return "projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}/report".format( + project=project, + location=location, + instance=instance, + assignment=assignment, + ) + + @staticmethod + def parse_os_policy_assignment_report_path(path: str) -> Dict[str, str]: + """Parses a os_policy_assignment_report path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/osPolicyAssignments/(?P.+?)/report$", + 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.""" @@ -389,6 +458,839 @@ def __init__( always_use_jwt_access=True, ) + def create_os_policy_assignment( + self, + request: Union[ + os_policy_assignments.CreateOSPolicyAssignmentRequest, dict + ] = None, + *, + parent: str = None, + os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, + os_policy_assignment_id: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Create an OS policy assignment. + + This method also creates the first revision of the OS policy + assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (Union[google.cloud.osconfig_v1.types.CreateOSPolicyAssignmentRequest, dict]): + The request object. A request message to create an OS + policy assignment + parent (str): + Required. The parent resource name in + the form: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + os_policy_assignment (google.cloud.osconfig_v1.types.OSPolicyAssignment): + Required. The OS policy assignment to + be created. + + This corresponds to the ``os_policy_assignment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + os_policy_assignment_id (str): + Required. The logical name of the OS policy assignment + in the project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + + This corresponds to the ``os_policy_assignment_id`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.osconfig_v1.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # 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, os_policy_assignment, os_policy_assignment_id] + ) + 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 os_policy_assignments.CreateOSPolicyAssignmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, os_policy_assignments.CreateOSPolicyAssignmentRequest + ): + request = os_policy_assignments.CreateOSPolicyAssignmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if os_policy_assignment is not None: + request.os_policy_assignment = os_policy_assignment + if os_policy_assignment_id is not None: + request.os_policy_assignment_id = os_policy_assignment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_os_policy_assignment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + os_policy_assignments.OSPolicyAssignment, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + def update_os_policy_assignment( + self, + request: Union[ + os_policy_assignments.UpdateOSPolicyAssignmentRequest, dict + ] = None, + *, + os_policy_assignment: os_policy_assignments.OSPolicyAssignment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Update an existing OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (Union[google.cloud.osconfig_v1.types.UpdateOSPolicyAssignmentRequest, dict]): + The request object. A request message to update an OS + policy assignment + os_policy_assignment (google.cloud.osconfig_v1.types.OSPolicyAssignment): + Required. The updated OS policy + assignment. + + This corresponds to the ``os_policy_assignment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask that controls + which fields of the assignment should be + updated. + + This corresponds to the ``update_mask`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.osconfig_v1.types.OSPolicyAssignment` OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # 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([os_policy_assignment, update_mask]) + 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 os_policy_assignments.UpdateOSPolicyAssignmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, os_policy_assignments.UpdateOSPolicyAssignmentRequest + ): + request = os_policy_assignments.UpdateOSPolicyAssignmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if os_policy_assignment is not None: + request.os_policy_assignment = os_policy_assignment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_os_policy_assignment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("os_policy_assignment.name", request.os_policy_assignment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + os_policy_assignments.OSPolicyAssignment, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + def get_os_policy_assignment( + self, + request: Union[os_policy_assignments.GetOSPolicyAssignmentRequest, dict] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> os_policy_assignments.OSPolicyAssignment: + r"""Retrieve an existing OS policy assignment. + + This method always returns the latest revision. In order to + retrieve a previous revision of the assignment, also provide the + revision ID in the ``name`` parameter. + + Args: + request (Union[google.cloud.osconfig_v1.types.GetOSPolicyAssignmentRequest, dict]): + The request object. A request message to get an OS + policy assignment + name (str): + Required. The resource name of OS policy assignment. + + Format: + ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` + + 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.OSPolicyAssignment: + OS policy assignment is an API resource that is used to + apply a set of OS policies to a dynamically targeted + group of Compute Engine VM instances. + + An OS policy is used to define the desired state + configuration for a Compute Engine VM instance + through a set of configuration resources that provide + capabilities such as installing or removing software + packages, or executing a script. + + For more information, see [OS policy and OS policy + assignment](\ https://cloud.google.com/compute/docs/os-configuration-management/working-with-os-policies). + + """ + # 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 os_policy_assignments.GetOSPolicyAssignmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, os_policy_assignments.GetOSPolicyAssignmentRequest): + request = os_policy_assignments.GetOSPolicyAssignmentRequest(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_os_policy_assignment] + + # 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_os_policy_assignments( + self, + request: Union[ + os_policy_assignments.ListOSPolicyAssignmentsRequest, dict + ] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentsPager: + r"""List the OS policy assignments under the parent + resource. + For each OS policy assignment, the latest revision is + returned. + + Args: + request (Union[google.cloud.osconfig_v1.types.ListOSPolicyAssignmentsRequest, dict]): + The request object. A request message to list OS policy + assignments for a parent resource + parent (str): + Required. The parent resource name. + 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.ListOSPolicyAssignmentsPager: + A response message for listing all + assignments under given parent. + 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 os_policy_assignments.ListOSPolicyAssignmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, os_policy_assignments.ListOSPolicyAssignmentsRequest + ): + request = os_policy_assignments.ListOSPolicyAssignmentsRequest(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_os_policy_assignments + ] + + # 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.ListOSPolicyAssignmentsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_os_policy_assignment_revisions( + self, + request: Union[ + os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, dict + ] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentRevisionsPager: + r"""List the OS policy assignment revisions for a given + OS policy assignment. + + Args: + request (Union[google.cloud.osconfig_v1.types.ListOSPolicyAssignmentRevisionsRequest, dict]): + The request object. A request message to list revisions + for a OS policy assignment + name (str): + Required. The name of the OS policy + assignment to list revisions for. + + 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.services.os_config_zonal_service.pagers.ListOSPolicyAssignmentRevisionsPager: + A response message for listing all + revisions for a OS policy assignment. + 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([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 os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest + ): + request = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest( + 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.list_os_policy_assignment_revisions + ] + + # 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,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListOSPolicyAssignmentRevisionsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_os_policy_assignment( + self, + request: Union[ + os_policy_assignments.DeleteOSPolicyAssignmentRequest, dict + ] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Delete the OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + If the LRO completes and is not cancelled, all revisions + associated with the OS policy assignment are deleted. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Args: + request (Union[google.cloud.osconfig_v1.types.DeleteOSPolicyAssignmentRequest, dict]): + The request object. A request message for deleting a OS + policy assignment. + name (str): + Required. The name of the OS policy + assignment to be deleted + + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + The JSON representation for Empty is empty JSON + object {}. + + """ + # 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 os_policy_assignments.DeleteOSPolicyAssignmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, os_policy_assignments.DeleteOSPolicyAssignmentRequest + ): + request = os_policy_assignments.DeleteOSPolicyAssignmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_os_policy_assignment + ] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=os_policy_assignments.OSPolicyAssignmentOperationMetadata, + ) + + # Done; return the response. + return response + + def get_os_policy_assignment_report( + self, + request: Union[ + os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest, dict + ] = None, + *, + name: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> os_policy_assignment_reports.OSPolicyAssignmentReport: + r"""Get the OS policy asssignment report for the + specified Compute Engine VM instance. + + Args: + request (Union[google.cloud.osconfig_v1.types.GetOSPolicyAssignmentReportRequest, dict]): + The request object. Get a report of the OS policy + assignment for a VM instance. + name (str): + Required. API resource name for OS policy assignment + report. + + Format: + ``/projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}/report`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance_id}``, + either Compute Engine ``instance-id`` or + ``instance-name`` can be provided. For + ``{assignment_id}``, the OSPolicyAssignment id must 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.OSPolicyAssignmentReport: + A report of the OS policy assignment + status for a given instance. + + """ + # 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 os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest + ): + request = os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest( + 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_os_policy_assignment_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_os_policy_assignment_reports( + self, + request: Union[ + os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest, dict + ] = None, + *, + parent: str = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListOSPolicyAssignmentReportsPager: + r"""List OS policy asssignment reports for all Compute + Engine VM instances in the specified zone. + + Args: + request (Union[google.cloud.osconfig_v1.types.ListOSPolicyAssignmentReportsRequest, dict]): + The request object. List the OS policy assignment + reports for VM instances. + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}/reports`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, + either ``instance-name``, ``instance-id``, or ``-`` can + be provided. If '-' is provided, the response will + include OSPolicyAssignmentReports for all instances in + the project/location. For ``{assignment}``, either + ``assignment-id`` or ``-`` can be provided. If '-' is + provided, the response will include + OSPolicyAssignmentReports for all OSPolicyAssignments in + the project/location. Either {instance} or {assignment} + must be ``-``. + + For example: + ``projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/-/reports`` + returns all reports for the instance + ``projects/{project}/locations/{location}/instances/-/osPolicyAssignments/{assignment-id}/reports`` + returns all the reports for the given assignment across + all instances. + ``projects/{project}/locations/{location}/instances/-/osPolicyAssignments/-/reports`` + returns all the reports for all assignments across all + instances. + + 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.ListOSPolicyAssignmentReportsPager: + A response message for listing OS + Policy assignment reports including the + page of results and page token. + 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 os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest + ): + request = os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest( + 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_os_policy_assignment_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.ListOSPolicyAssignmentReportsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + def get_inventory( self, request: Union[inventory.GetInventoryRequest, dict] = None, 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 index cbf40b9..1f136c7 100644 --- a/google/cloud/osconfig_v1/services/os_config_zonal_service/pagers.py +++ b/google/cloud/osconfig_v1/services/os_config_zonal_service/pagers.py @@ -25,9 +25,433 @@ ) from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import os_policy_assignment_reports +from google.cloud.osconfig_v1.types import os_policy_assignments from google.cloud.osconfig_v1.types import vulnerability +class ListOSPolicyAssignmentsPager: + """A pager for iterating through ``list_os_policy_assignments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``os_policy_assignments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOSPolicyAssignments`` requests and continue to iterate + through the ``os_policy_assignments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentsResponse` + 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[..., os_policy_assignments.ListOSPolicyAssignmentsResponse], + request: os_policy_assignments.ListOSPolicyAssignmentsRequest, + response: os_policy_assignments.ListOSPolicyAssignmentsResponse, + *, + 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.ListOSPolicyAssignmentsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListOSPolicyAssignmentsResponse): + 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[os_policy_assignments.ListOSPolicyAssignmentsResponse]: + 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) -> Iterator[os_policy_assignments.OSPolicyAssignment]: + for page in self.pages: + yield from page.os_policy_assignments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListOSPolicyAssignmentsAsyncPager: + """A pager for iterating through ``list_os_policy_assignments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``os_policy_assignments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOSPolicyAssignments`` requests and continue to iterate + through the ``os_policy_assignments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentsResponse` + 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[os_policy_assignments.ListOSPolicyAssignmentsResponse] + ], + request: os_policy_assignments.ListOSPolicyAssignmentsRequest, + response: os_policy_assignments.ListOSPolicyAssignmentsResponse, + *, + 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.ListOSPolicyAssignmentsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListOSPolicyAssignmentsResponse): + 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 = os_policy_assignments.ListOSPolicyAssignmentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[os_policy_assignments.ListOSPolicyAssignmentsResponse]: + 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) -> AsyncIterator[os_policy_assignments.OSPolicyAssignment]: + async def async_generator(): + async for page in self.pages: + for response in page.os_policy_assignments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListOSPolicyAssignmentRevisionsPager: + """A pager for iterating through ``list_os_policy_assignment_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``os_policy_assignments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOSPolicyAssignmentRevisions`` requests and continue to iterate + through the ``os_policy_assignments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentRevisionsResponse` + 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[ + ..., os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse + ], + request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, + response: os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, + *, + 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.ListOSPolicyAssignmentRevisionsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListOSPolicyAssignmentRevisionsResponse): + 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest( + request + ) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]: + 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) -> Iterator[os_policy_assignments.OSPolicyAssignment]: + for page in self.pages: + yield from page.os_policy_assignments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListOSPolicyAssignmentRevisionsAsyncPager: + """A pager for iterating through ``list_os_policy_assignment_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``os_policy_assignments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOSPolicyAssignmentRevisions`` requests and continue to iterate + through the ``os_policy_assignments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentRevisionsResponse` + 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[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse], + ], + request: os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, + response: os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, + *, + 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.ListOSPolicyAssignmentRevisionsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListOSPolicyAssignmentRevisionsResponse): + 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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest( + request + ) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse]: + 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) -> AsyncIterator[os_policy_assignments.OSPolicyAssignment]: + async def async_generator(): + async for page in self.pages: + for response in page.os_policy_assignments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListOSPolicyAssignmentReportsPager: + """A pager for iterating through ``list_os_policy_assignment_reports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentReportsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``os_policy_assignment_reports`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOSPolicyAssignmentReports`` requests and continue to iterate + through the ``os_policy_assignment_reports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentReportsResponse` + 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[ + ..., os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse + ], + request: os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest, + response: os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse, + *, + 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.ListOSPolicyAssignmentReportsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListOSPolicyAssignmentReportsResponse): + 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 = os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest( + request + ) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterator[os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse]: + 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, + ) -> Iterator[os_policy_assignment_reports.OSPolicyAssignmentReport]: + for page in self.pages: + yield from page.os_policy_assignment_reports + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListOSPolicyAssignmentReportsAsyncPager: + """A pager for iterating through ``list_os_policy_assignment_reports`` requests. + + This class thinly wraps an initial + :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentReportsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``os_policy_assignment_reports`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOSPolicyAssignmentReports`` requests and continue to iterate + through the ``os_policy_assignment_reports`` field on the + corresponding responses. + + All the usual :class:`google.cloud.osconfig_v1.types.ListOSPolicyAssignmentReportsResponse` + 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[ + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse + ], + ], + request: os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest, + response: os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse, + *, + 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.ListOSPolicyAssignmentReportsRequest): + The initial request object. + response (google.cloud.osconfig_v1.types.ListOSPolicyAssignmentReportsResponse): + 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 = os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest( + request + ) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[ + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse + ]: + 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, + ) -> AsyncIterator[os_policy_assignment_reports.OSPolicyAssignmentReport]: + async def async_generator(): + async for page in self.pages: + for response in page.os_policy_assignment_reports: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListInventoriesPager: """A pager for iterating through ``list_inventories`` requests. 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 index 9693d25..74c1a0c 100644 --- 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 @@ -22,11 +22,15 @@ 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.api_core import operations_v1 # 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 os_policy_assignment_reports +from google.cloud.osconfig_v1.types import os_policy_assignments from google.cloud.osconfig_v1.types import vulnerability +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -120,6 +124,46 @@ def __init__( def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { + self.create_os_policy_assignment: gapic_v1.method.wrap_method( + self.create_os_policy_assignment, + default_timeout=None, + client_info=client_info, + ), + self.update_os_policy_assignment: gapic_v1.method.wrap_method( + self.update_os_policy_assignment, + default_timeout=None, + client_info=client_info, + ), + self.get_os_policy_assignment: gapic_v1.method.wrap_method( + self.get_os_policy_assignment, + default_timeout=None, + client_info=client_info, + ), + self.list_os_policy_assignments: gapic_v1.method.wrap_method( + self.list_os_policy_assignments, + default_timeout=None, + client_info=client_info, + ), + self.list_os_policy_assignment_revisions: gapic_v1.method.wrap_method( + self.list_os_policy_assignment_revisions, + default_timeout=None, + client_info=client_info, + ), + self.delete_os_policy_assignment: gapic_v1.method.wrap_method( + self.delete_os_policy_assignment, + default_timeout=None, + client_info=client_info, + ), + self.get_os_policy_assignment_report: gapic_v1.method.wrap_method( + self.get_os_policy_assignment_report, + default_timeout=None, + client_info=client_info, + ), + self.list_os_policy_assignment_reports: gapic_v1.method.wrap_method( + self.list_os_policy_assignment_reports, + default_timeout=None, + client_info=client_info, + ), self.get_inventory: gapic_v1.method.wrap_method( self.get_inventory, default_timeout=None, client_info=client_info, ), @@ -147,6 +191,100 @@ def close(self): """ raise NotImplementedError() + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.CreateOSPolicyAssignmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.UpdateOSPolicyAssignmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.GetOSPolicyAssignmentRequest], + Union[ + os_policy_assignments.OSPolicyAssignment, + Awaitable[os_policy_assignments.OSPolicyAssignment], + ], + ]: + raise NotImplementedError() + + @property + def list_os_policy_assignments( + self, + ) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentsRequest], + Union[ + os_policy_assignments.ListOSPolicyAssignmentsResponse, + Awaitable[os_policy_assignments.ListOSPolicyAssignmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_os_policy_assignment_revisions( + self, + ) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], + Union[ + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, + Awaitable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.DeleteOSPolicyAssignmentRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_os_policy_assignment_report( + self, + ) -> Callable[ + [os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest], + Union[ + os_policy_assignment_reports.OSPolicyAssignmentReport, + Awaitable[os_policy_assignment_reports.OSPolicyAssignmentReport], + ], + ]: + raise NotImplementedError() + + @property + def list_os_policy_assignment_reports( + self, + ) -> Callable[ + [os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest], + Union[ + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse, + Awaitable[ + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse + ], + ], + ]: + raise NotImplementedError() + @property def get_inventory( self, 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 index b273bd3..4698651 100644 --- 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 @@ -17,6 +17,7 @@ from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # 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 @@ -25,7 +26,10 @@ import grpc # type: ignore from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import os_policy_assignment_reports +from google.cloud.osconfig_v1.types import os_policy_assignments from google.cloud.osconfig_v1.types import vulnerability +from google.longrunning import operations_pb2 # type: ignore from .base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO @@ -114,6 +118,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -229,6 +234,302 @@ def grpc_channel(self) -> grpc.Channel: """ return self._grpc_channel + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + + @property + def create_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.CreateOSPolicyAssignmentRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create os policy assignment method over gRPC. + + Create an OS policy assignment. + + This method also creates the first revision of the OS policy + assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.CreateOSPolicyAssignmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_os_policy_assignment" not in self._stubs: + self._stubs["create_os_policy_assignment"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/CreateOSPolicyAssignment", + request_serializer=os_policy_assignments.CreateOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_os_policy_assignment"] + + @property + def update_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.UpdateOSPolicyAssignmentRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the update os policy assignment method over gRPC. + + Update an existing OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.UpdateOSPolicyAssignmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_os_policy_assignment" not in self._stubs: + self._stubs["update_os_policy_assignment"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/UpdateOSPolicyAssignment", + request_serializer=os_policy_assignments.UpdateOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_os_policy_assignment"] + + @property + def get_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.GetOSPolicyAssignmentRequest], + os_policy_assignments.OSPolicyAssignment, + ]: + r"""Return a callable for the get os policy assignment method over gRPC. + + Retrieve an existing OS policy assignment. + + This method always returns the latest revision. In order to + retrieve a previous revision of the assignment, also provide the + revision ID in the ``name`` parameter. + + Returns: + Callable[[~.GetOSPolicyAssignmentRequest], + ~.OSPolicyAssignment]: + 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_os_policy_assignment" not in self._stubs: + self._stubs["get_os_policy_assignment"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/GetOSPolicyAssignment", + request_serializer=os_policy_assignments.GetOSPolicyAssignmentRequest.serialize, + response_deserializer=os_policy_assignments.OSPolicyAssignment.deserialize, + ) + return self._stubs["get_os_policy_assignment"] + + @property + def list_os_policy_assignments( + self, + ) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentsRequest], + os_policy_assignments.ListOSPolicyAssignmentsResponse, + ]: + r"""Return a callable for the list os policy assignments method over gRPC. + + List the OS policy assignments under the parent + resource. + For each OS policy assignment, the latest revision is + returned. + + Returns: + Callable[[~.ListOSPolicyAssignmentsRequest], + ~.ListOSPolicyAssignmentsResponse]: + 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_os_policy_assignments" not in self._stubs: + self._stubs["list_os_policy_assignments"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListOSPolicyAssignments", + request_serializer=os_policy_assignments.ListOSPolicyAssignmentsRequest.serialize, + response_deserializer=os_policy_assignments.ListOSPolicyAssignmentsResponse.deserialize, + ) + return self._stubs["list_os_policy_assignments"] + + @property + def list_os_policy_assignment_revisions( + self, + ) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse, + ]: + r"""Return a callable for the list os policy assignment + revisions method over gRPC. + + List the OS policy assignment revisions for a given + OS policy assignment. + + Returns: + Callable[[~.ListOSPolicyAssignmentRevisionsRequest], + ~.ListOSPolicyAssignmentRevisionsResponse]: + 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_os_policy_assignment_revisions" not in self._stubs: + self._stubs[ + "list_os_policy_assignment_revisions" + ] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListOSPolicyAssignmentRevisions", + request_serializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest.serialize, + response_deserializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse.deserialize, + ) + return self._stubs["list_os_policy_assignment_revisions"] + + @property + def delete_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.DeleteOSPolicyAssignmentRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete os policy assignment method over gRPC. + + Delete the OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + If the LRO completes and is not cancelled, all revisions + associated with the OS policy assignment are deleted. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.DeleteOSPolicyAssignmentRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_os_policy_assignment" not in self._stubs: + self._stubs["delete_os_policy_assignment"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/DeleteOSPolicyAssignment", + request_serializer=os_policy_assignments.DeleteOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_os_policy_assignment"] + + @property + def get_os_policy_assignment_report( + self, + ) -> Callable[ + [os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest], + os_policy_assignment_reports.OSPolicyAssignmentReport, + ]: + r"""Return a callable for the get os policy assignment + report method over gRPC. + + Get the OS policy asssignment report for the + specified Compute Engine VM instance. + + Returns: + Callable[[~.GetOSPolicyAssignmentReportRequest], + ~.OSPolicyAssignmentReport]: + 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_os_policy_assignment_report" not in self._stubs: + self._stubs[ + "get_os_policy_assignment_report" + ] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/GetOSPolicyAssignmentReport", + request_serializer=os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest.serialize, + response_deserializer=os_policy_assignment_reports.OSPolicyAssignmentReport.deserialize, + ) + return self._stubs["get_os_policy_assignment_report"] + + @property + def list_os_policy_assignment_reports( + self, + ) -> Callable[ + [os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest], + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse, + ]: + r"""Return a callable for the list os policy assignment + reports method over gRPC. + + List OS policy asssignment reports for all Compute + Engine VM instances in the specified zone. + + Returns: + Callable[[~.ListOSPolicyAssignmentReportsRequest], + ~.ListOSPolicyAssignmentReportsResponse]: + 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_os_policy_assignment_reports" not in self._stubs: + self._stubs[ + "list_os_policy_assignment_reports" + ] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListOSPolicyAssignmentReports", + request_serializer=os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest.serialize, + response_deserializer=os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse.deserialize, + ) + return self._stubs["list_os_policy_assignment_reports"] + @property def get_inventory( self, 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 index 03519a9..f24baab 100644 --- 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 @@ -18,6 +18,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -25,7 +26,10 @@ from grpc.experimental import aio # type: ignore from google.cloud.osconfig_v1.types import inventory +from google.cloud.osconfig_v1.types import os_policy_assignment_reports +from google.cloud.osconfig_v1.types import os_policy_assignments from google.cloud.osconfig_v1.types import vulnerability +from google.longrunning import operations_pb2 # type: ignore from .base import OsConfigZonalServiceTransport, DEFAULT_CLIENT_INFO from .grpc import OsConfigZonalServiceGrpcTransport @@ -160,6 +164,7 @@ def __init__( self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -231,6 +236,304 @@ def grpc_channel(self) -> aio.Channel: # Return the channel from cache. return self._grpc_channel + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.CreateOSPolicyAssignmentRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create os policy assignment method over gRPC. + + Create an OS policy assignment. + + This method also creates the first revision of the OS policy + assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.CreateOSPolicyAssignmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_os_policy_assignment" not in self._stubs: + self._stubs["create_os_policy_assignment"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/CreateOSPolicyAssignment", + request_serializer=os_policy_assignments.CreateOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_os_policy_assignment"] + + @property + def update_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.UpdateOSPolicyAssignmentRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update os policy assignment method over gRPC. + + Update an existing OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.UpdateOSPolicyAssignmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_os_policy_assignment" not in self._stubs: + self._stubs["update_os_policy_assignment"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/UpdateOSPolicyAssignment", + request_serializer=os_policy_assignments.UpdateOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_os_policy_assignment"] + + @property + def get_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.GetOSPolicyAssignmentRequest], + Awaitable[os_policy_assignments.OSPolicyAssignment], + ]: + r"""Return a callable for the get os policy assignment method over gRPC. + + Retrieve an existing OS policy assignment. + + This method always returns the latest revision. In order to + retrieve a previous revision of the assignment, also provide the + revision ID in the ``name`` parameter. + + Returns: + Callable[[~.GetOSPolicyAssignmentRequest], + Awaitable[~.OSPolicyAssignment]]: + 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_os_policy_assignment" not in self._stubs: + self._stubs["get_os_policy_assignment"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/GetOSPolicyAssignment", + request_serializer=os_policy_assignments.GetOSPolicyAssignmentRequest.serialize, + response_deserializer=os_policy_assignments.OSPolicyAssignment.deserialize, + ) + return self._stubs["get_os_policy_assignment"] + + @property + def list_os_policy_assignments( + self, + ) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentsRequest], + Awaitable[os_policy_assignments.ListOSPolicyAssignmentsResponse], + ]: + r"""Return a callable for the list os policy assignments method over gRPC. + + List the OS policy assignments under the parent + resource. + For each OS policy assignment, the latest revision is + returned. + + Returns: + Callable[[~.ListOSPolicyAssignmentsRequest], + Awaitable[~.ListOSPolicyAssignmentsResponse]]: + 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_os_policy_assignments" not in self._stubs: + self._stubs["list_os_policy_assignments"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListOSPolicyAssignments", + request_serializer=os_policy_assignments.ListOSPolicyAssignmentsRequest.serialize, + response_deserializer=os_policy_assignments.ListOSPolicyAssignmentsResponse.deserialize, + ) + return self._stubs["list_os_policy_assignments"] + + @property + def list_os_policy_assignment_revisions( + self, + ) -> Callable[ + [os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest], + Awaitable[os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse], + ]: + r"""Return a callable for the list os policy assignment + revisions method over gRPC. + + List the OS policy assignment revisions for a given + OS policy assignment. + + Returns: + Callable[[~.ListOSPolicyAssignmentRevisionsRequest], + Awaitable[~.ListOSPolicyAssignmentRevisionsResponse]]: + 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_os_policy_assignment_revisions" not in self._stubs: + self._stubs[ + "list_os_policy_assignment_revisions" + ] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListOSPolicyAssignmentRevisions", + request_serializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest.serialize, + response_deserializer=os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse.deserialize, + ) + return self._stubs["list_os_policy_assignment_revisions"] + + @property + def delete_os_policy_assignment( + self, + ) -> Callable[ + [os_policy_assignments.DeleteOSPolicyAssignmentRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete os policy assignment method over gRPC. + + Delete the OS policy assignment. + + This method creates a new revision of the OS policy assignment. + + This method returns a long running operation (LRO) that contains + the rollout details. The rollout can be cancelled by cancelling + the LRO. + + If the LRO completes and is not cancelled, all revisions + associated with the OS policy assignment are deleted. + + For more information, see `Method: + projects.locations.osPolicyAssignments.operations.cancel `__. + + Returns: + Callable[[~.DeleteOSPolicyAssignmentRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_os_policy_assignment" not in self._stubs: + self._stubs["delete_os_policy_assignment"] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/DeleteOSPolicyAssignment", + request_serializer=os_policy_assignments.DeleteOSPolicyAssignmentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_os_policy_assignment"] + + @property + def get_os_policy_assignment_report( + self, + ) -> Callable[ + [os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest], + Awaitable[os_policy_assignment_reports.OSPolicyAssignmentReport], + ]: + r"""Return a callable for the get os policy assignment + report method over gRPC. + + Get the OS policy asssignment report for the + specified Compute Engine VM instance. + + Returns: + Callable[[~.GetOSPolicyAssignmentReportRequest], + Awaitable[~.OSPolicyAssignmentReport]]: + 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_os_policy_assignment_report" not in self._stubs: + self._stubs[ + "get_os_policy_assignment_report" + ] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/GetOSPolicyAssignmentReport", + request_serializer=os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest.serialize, + response_deserializer=os_policy_assignment_reports.OSPolicyAssignmentReport.deserialize, + ) + return self._stubs["get_os_policy_assignment_report"] + + @property + def list_os_policy_assignment_reports( + self, + ) -> Callable[ + [os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest], + Awaitable[os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse], + ]: + r"""Return a callable for the list os policy assignment + reports method over gRPC. + + List OS policy asssignment reports for all Compute + Engine VM instances in the specified zone. + + Returns: + Callable[[~.ListOSPolicyAssignmentReportsRequest], + Awaitable[~.ListOSPolicyAssignmentReportsResponse]]: + 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_os_policy_assignment_reports" not in self._stubs: + self._stubs[ + "list_os_policy_assignment_reports" + ] = self.grpc_channel.unary_unary( + "/google.cloud.osconfig.v1.OsConfigZonalService/ListOSPolicyAssignmentReports", + request_serializer=os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest.serialize, + response_deserializer=os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse.deserialize, + ) + return self._stubs["list_os_policy_assignment_reports"] + @property def get_inventory( self, diff --git a/google/cloud/osconfig_v1/types/__init__.py b/google/cloud/osconfig_v1/types/__init__.py index 6ea7245..0b1e15b 100644 --- a/google/cloud/osconfig_v1/types/__init__.py +++ b/google/cloud/osconfig_v1/types/__init__.py @@ -20,6 +20,25 @@ ListInventoriesResponse, InventoryView, ) +from .os_policy import OSPolicy +from .os_policy_assignment_reports import ( + GetOSPolicyAssignmentReportRequest, + ListOSPolicyAssignmentReportsRequest, + ListOSPolicyAssignmentReportsResponse, + OSPolicyAssignmentReport, +) +from .os_policy_assignments import ( + CreateOSPolicyAssignmentRequest, + DeleteOSPolicyAssignmentRequest, + GetOSPolicyAssignmentRequest, + ListOSPolicyAssignmentRevisionsRequest, + ListOSPolicyAssignmentRevisionsResponse, + ListOSPolicyAssignmentsRequest, + ListOSPolicyAssignmentsResponse, + OSPolicyAssignment, + OSPolicyAssignmentOperationMetadata, + UpdateOSPolicyAssignmentRequest, +) from .osconfig_common import FixedOrPercent from .patch_deployments import ( CreatePatchDeploymentRequest, @@ -71,6 +90,21 @@ "ListInventoriesRequest", "ListInventoriesResponse", "InventoryView", + "OSPolicy", + "GetOSPolicyAssignmentReportRequest", + "ListOSPolicyAssignmentReportsRequest", + "ListOSPolicyAssignmentReportsResponse", + "OSPolicyAssignmentReport", + "CreateOSPolicyAssignmentRequest", + "DeleteOSPolicyAssignmentRequest", + "GetOSPolicyAssignmentRequest", + "ListOSPolicyAssignmentRevisionsRequest", + "ListOSPolicyAssignmentRevisionsResponse", + "ListOSPolicyAssignmentsRequest", + "ListOSPolicyAssignmentsResponse", + "OSPolicyAssignment", + "OSPolicyAssignmentOperationMetadata", + "UpdateOSPolicyAssignmentRequest", "FixedOrPercent", "CreatePatchDeploymentRequest", "DeletePatchDeploymentRequest", diff --git a/google/cloud/osconfig_v1/types/os_policy.py b/google/cloud/osconfig_v1/types/os_policy.py new file mode 100644 index 0000000..4c243ce --- /dev/null +++ b/google/cloud/osconfig_v1/types/os_policy.py @@ -0,0 +1,806 @@ +# -*- 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 + + +__protobuf__ = proto.module(package="google.cloud.osconfig.v1", manifest={"OSPolicy",},) + + +class OSPolicy(proto.Message): + r"""An OS policy defines the desired state configuration for a + VM. + + Attributes: + id (str): + Required. The id of the OS policy with the following + restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the assignment. + description (str): + Policy description. + Length of the description is limited to 1024 + characters. + mode (google.cloud.osconfig_v1.types.OSPolicy.Mode): + Required. Policy mode + resource_groups (Sequence[google.cloud.osconfig_v1.types.OSPolicy.ResourceGroup]): + Required. List of resource groups for the policy. For a + particular VM, resource groups are evaluated in the order + specified and the first resource group that is applicable is + selected and the rest are ignored. + + If none of the resource groups are applicable for a VM, the + VM is considered to be non-compliant w.r.t this policy. This + behavior can be toggled by the flag + ``allow_no_resource_group_match`` + allow_no_resource_group_match (bool): + This flag determines the OS policy compliance status when + none of the resource groups within the policy are applicable + for a VM. Set this value to ``true`` if the policy needs to + be reported as compliant even if the policy has nothing to + validate or enforce. + """ + + class Mode(proto.Enum): + r"""Policy mode""" + MODE_UNSPECIFIED = 0 + VALIDATION = 1 + ENFORCEMENT = 2 + + class InventoryFilter(proto.Message): + r"""Filtering criteria to select VMs based on inventory details. + + Attributes: + os_short_name (str): + Required. The OS short name + os_version (str): + The OS version + + Prefix matches are supported if asterisk(*) is provided as + the last character. For example, to match all versions with + a major version of ``7``, specify the following value for + this field ``7.*`` + + An empty string matches all OS versions. + """ + + os_short_name = proto.Field(proto.STRING, number=1,) + os_version = proto.Field(proto.STRING, number=2,) + + class Resource(proto.Message): + r"""An OS policy resource is used to define the desired state + configuration and provides a specific functionality like + installing/removing packages, executing a script etc. + + The system ensures that resources are always in their desired + state by taking necessary actions if they have drifted from + their desired state. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + Required. The id of the resource with the following + restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the OS policy. + pkg (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource): + Package resource + This field is a member of `oneof`_ ``resource_type``. + repository (google.cloud.osconfig_v1.types.OSPolicy.Resource.RepositoryResource): + Package repository resource + This field is a member of `oneof`_ ``resource_type``. + exec_ (google.cloud.osconfig_v1.types.OSPolicy.Resource.ExecResource): + Exec resource + This field is a member of `oneof`_ ``resource_type``. + file (google.cloud.osconfig_v1.types.OSPolicy.Resource.FileResource): + File resource + This field is a member of `oneof`_ ``resource_type``. + """ + + class File(proto.Message): + r"""A remote or local file. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + remote (google.cloud.osconfig_v1.types.OSPolicy.Resource.File.Remote): + A generic remote file. + This field is a member of `oneof`_ ``type``. + gcs (google.cloud.osconfig_v1.types.OSPolicy.Resource.File.Gcs): + A Cloud Storage object. + This field is a member of `oneof`_ ``type``. + local_path (str): + A local path within the VM to use. + This field is a member of `oneof`_ ``type``. + allow_insecure (bool): + Defaults to false. When false, files are + subject to validations based on the file type: + Remote: A checksum must be specified. + Cloud Storage: An object generation number must + be specified. + """ + + class Remote(proto.Message): + r"""Specifies a file available via some URI. + + Attributes: + uri (str): + Required. URI from which to fetch the object. It should + contain both the protocol and path following the format + ``{protocol}://{location}``. + sha256_checksum (str): + SHA256 checksum of the remote file. + """ + + uri = proto.Field(proto.STRING, number=1,) + sha256_checksum = proto.Field(proto.STRING, number=2,) + + class Gcs(proto.Message): + r"""Specifies a file available as a Cloud Storage Object. + + Attributes: + bucket (str): + Required. Bucket of the Cloud Storage object. + object_ (str): + Required. Name of the Cloud Storage object. + generation (int): + Generation number of the Cloud Storage + object. + """ + + bucket = proto.Field(proto.STRING, number=1,) + object_ = proto.Field(proto.STRING, number=2,) + generation = proto.Field(proto.INT64, number=3,) + + remote = proto.Field( + proto.MESSAGE, + number=1, + oneof="type", + message="OSPolicy.Resource.File.Remote", + ) + gcs = proto.Field( + proto.MESSAGE, + number=2, + oneof="type", + message="OSPolicy.Resource.File.Gcs", + ) + local_path = proto.Field(proto.STRING, number=3, oneof="type",) + allow_insecure = proto.Field(proto.BOOL, number=4,) + + class PackageResource(proto.Message): + r"""A resource that manages a system package. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + desired_state (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource.DesiredState): + Required. The desired state the agent should + maintain for this package. + apt (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource.APT): + A package managed by Apt. + This field is a member of `oneof`_ ``system_package``. + deb (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource.Deb): + A deb package file. + This field is a member of `oneof`_ ``system_package``. + yum (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource.YUM): + A package managed by YUM. + This field is a member of `oneof`_ ``system_package``. + zypper (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource.Zypper): + A package managed by Zypper. + This field is a member of `oneof`_ ``system_package``. + rpm (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource.RPM): + An rpm package file. + This field is a member of `oneof`_ ``system_package``. + googet (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource.GooGet): + A package managed by GooGet. + This field is a member of `oneof`_ ``system_package``. + msi (google.cloud.osconfig_v1.types.OSPolicy.Resource.PackageResource.MSI): + An MSI package. + This field is a member of `oneof`_ ``system_package``. + """ + + class DesiredState(proto.Enum): + r"""The desired state that the OS Config agent maintains on the + VM. + """ + DESIRED_STATE_UNSPECIFIED = 0 + INSTALLED = 1 + REMOVED = 2 + + class Deb(proto.Message): + r"""A deb package file. dpkg packages only support INSTALLED + state. + + Attributes: + source (google.cloud.osconfig_v1.types.OSPolicy.Resource.File): + Required. A deb package. + pull_deps (bool): + Whether dependencies should also be installed. + + - install when false: ``dpkg -i package`` + - install when true: + ``apt-get update && apt-get -y install package.deb`` + """ + + source = proto.Field( + proto.MESSAGE, number=1, message="OSPolicy.Resource.File", + ) + pull_deps = proto.Field(proto.BOOL, number=2,) + + class APT(proto.Message): + r"""A package managed by APT. + + - install: ``apt-get update && apt-get -y install [name]`` + - remove: ``apt-get -y remove [name]`` + + Attributes: + name (str): + Required. Package name. + """ + + name = proto.Field(proto.STRING, number=1,) + + class RPM(proto.Message): + r"""An RPM package file. RPM packages only support INSTALLED + state. + + Attributes: + source (google.cloud.osconfig_v1.types.OSPolicy.Resource.File): + Required. An rpm package. + pull_deps (bool): + Whether dependencies should also be installed. + + - install when false: + ``rpm --upgrade --replacepkgs package.rpm`` + - install when true: ``yum -y install package.rpm`` or + ``zypper -y install package.rpm`` + """ + + source = proto.Field( + proto.MESSAGE, number=1, message="OSPolicy.Resource.File", + ) + pull_deps = proto.Field(proto.BOOL, number=2,) + + class YUM(proto.Message): + r"""A package managed by YUM. + + - install: ``yum -y install package`` + - remove: ``yum -y remove package`` + + Attributes: + name (str): + Required. Package name. + """ + + name = proto.Field(proto.STRING, number=1,) + + class Zypper(proto.Message): + r"""A package managed by Zypper. + + - install: ``zypper -y install package`` + - remove: ``zypper -y rm package`` + + Attributes: + name (str): + Required. Package name. + """ + + name = proto.Field(proto.STRING, number=1,) + + class GooGet(proto.Message): + r"""A package managed by GooGet. + + - install: ``googet -noconfirm install package`` + - remove: ``googet -noconfirm remove package`` + + Attributes: + name (str): + Required. Package name. + """ + + name = proto.Field(proto.STRING, number=1,) + + class MSI(proto.Message): + r"""An MSI package. MSI packages only support INSTALLED state. + + Attributes: + source (google.cloud.osconfig_v1.types.OSPolicy.Resource.File): + Required. The MSI package. + properties (Sequence[str]): + Additional properties to use during installation. This + should be in the format of Property=Setting. Appended to the + defaults of ``ACTION=INSTALL REBOOT=ReallySuppress``. + """ + + source = proto.Field( + proto.MESSAGE, number=1, message="OSPolicy.Resource.File", + ) + properties = proto.RepeatedField(proto.STRING, number=2,) + + desired_state = proto.Field( + proto.ENUM, + number=1, + enum="OSPolicy.Resource.PackageResource.DesiredState", + ) + apt = proto.Field( + proto.MESSAGE, + number=2, + oneof="system_package", + message="OSPolicy.Resource.PackageResource.APT", + ) + deb = proto.Field( + proto.MESSAGE, + number=3, + oneof="system_package", + message="OSPolicy.Resource.PackageResource.Deb", + ) + yum = proto.Field( + proto.MESSAGE, + number=4, + oneof="system_package", + message="OSPolicy.Resource.PackageResource.YUM", + ) + zypper = proto.Field( + proto.MESSAGE, + number=5, + oneof="system_package", + message="OSPolicy.Resource.PackageResource.Zypper", + ) + rpm = proto.Field( + proto.MESSAGE, + number=6, + oneof="system_package", + message="OSPolicy.Resource.PackageResource.RPM", + ) + googet = proto.Field( + proto.MESSAGE, + number=7, + oneof="system_package", + message="OSPolicy.Resource.PackageResource.GooGet", + ) + msi = proto.Field( + proto.MESSAGE, + number=8, + oneof="system_package", + message="OSPolicy.Resource.PackageResource.MSI", + ) + + class RepositoryResource(proto.Message): + r"""A resource that manages a package repository. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + apt (google.cloud.osconfig_v1.types.OSPolicy.Resource.RepositoryResource.AptRepository): + An Apt Repository. + This field is a member of `oneof`_ ``repository``. + yum (google.cloud.osconfig_v1.types.OSPolicy.Resource.RepositoryResource.YumRepository): + A Yum Repository. + This field is a member of `oneof`_ ``repository``. + zypper (google.cloud.osconfig_v1.types.OSPolicy.Resource.RepositoryResource.ZypperRepository): + A Zypper Repository. + This field is a member of `oneof`_ ``repository``. + goo (google.cloud.osconfig_v1.types.OSPolicy.Resource.RepositoryResource.GooRepository): + A Goo Repository. + This field is a member of `oneof`_ ``repository``. + """ + + class AptRepository(proto.Message): + r"""Represents a single apt package repository. These will be added to a + repo file that will be managed at + ``/etc/apt/sources.list.d/google_osconfig.list``. + + Attributes: + archive_type (google.cloud.osconfig_v1.types.OSPolicy.Resource.RepositoryResource.AptRepository.ArchiveType): + Required. Type of archive files in this + repository. + uri (str): + Required. URI for this repository. + distribution (str): + Required. Distribution of this repository. + components (Sequence[str]): + Required. List of components for this + repository. Must contain at least one item. + gpg_key (str): + URI of the key file for this repository. The agent maintains + a keyring at + ``/etc/apt/trusted.gpg.d/osconfig_agent_managed.gpg``. + """ + + class ArchiveType(proto.Enum): + r"""Type of archive.""" + ARCHIVE_TYPE_UNSPECIFIED = 0 + DEB = 1 + DEB_SRC = 2 + + archive_type = proto.Field( + proto.ENUM, + number=1, + enum="OSPolicy.Resource.RepositoryResource.AptRepository.ArchiveType", + ) + uri = proto.Field(proto.STRING, number=2,) + distribution = proto.Field(proto.STRING, number=3,) + components = proto.RepeatedField(proto.STRING, number=4,) + gpg_key = proto.Field(proto.STRING, number=5,) + + class YumRepository(proto.Message): + r"""Represents a single yum package repository. These are added to a + repo file that is managed at + ``/etc/yum.repos.d/google_osconfig.repo``. + + Attributes: + id (str): + Required. A one word, unique name for this repository. This + is the ``repo id`` in the yum config file and also the + ``display_name`` if ``display_name`` is omitted. This id is + also used as the unique identifier when checking for + resource conflicts. + display_name (str): + The display name of the repository. + base_url (str): + Required. The location of the repository + directory. + gpg_keys (Sequence[str]): + URIs of GPG keys. + """ + + id = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + base_url = proto.Field(proto.STRING, number=3,) + gpg_keys = proto.RepeatedField(proto.STRING, number=4,) + + class ZypperRepository(proto.Message): + r"""Represents a single zypper package repository. These are added to a + repo file that is managed at + ``/etc/zypp/repos.d/google_osconfig.repo``. + + Attributes: + id (str): + Required. A one word, unique name for this repository. This + is the ``repo id`` in the zypper config file and also the + ``display_name`` if ``display_name`` is omitted. This id is + also used as the unique identifier when checking for + GuestPolicy conflicts. + display_name (str): + The display name of the repository. + base_url (str): + Required. The location of the repository + directory. + gpg_keys (Sequence[str]): + URIs of GPG keys. + """ + + id = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + base_url = proto.Field(proto.STRING, number=3,) + gpg_keys = proto.RepeatedField(proto.STRING, number=4,) + + class GooRepository(proto.Message): + r"""Represents a Goo package repository. These are added to a repo file + that is managed at + ``C:/ProgramData/GooGet/repos/google_osconfig.repo``. + + Attributes: + name (str): + Required. The name of the repository. + url (str): + Required. The url of the repository. + """ + + name = proto.Field(proto.STRING, number=1,) + url = proto.Field(proto.STRING, number=2,) + + apt = proto.Field( + proto.MESSAGE, + number=1, + oneof="repository", + message="OSPolicy.Resource.RepositoryResource.AptRepository", + ) + yum = proto.Field( + proto.MESSAGE, + number=2, + oneof="repository", + message="OSPolicy.Resource.RepositoryResource.YumRepository", + ) + zypper = proto.Field( + proto.MESSAGE, + number=3, + oneof="repository", + message="OSPolicy.Resource.RepositoryResource.ZypperRepository", + ) + goo = proto.Field( + proto.MESSAGE, + number=4, + oneof="repository", + message="OSPolicy.Resource.RepositoryResource.GooRepository", + ) + + class ExecResource(proto.Message): + r"""A resource that allows executing scripts on the VM. + + The ``ExecResource`` has 2 stages: ``validate`` and ``enforce`` and + both stages accept a script as an argument to execute. + + When the ``ExecResource`` is applied by the agent, it first executes + the script in the ``validate`` stage. The ``validate`` stage can + signal that the ``ExecResource`` is already in the desired state by + returning an exit code of ``100``. If the ``ExecResource`` is not in + the desired state, it should return an exit code of ``101``. Any + other exit code returned by this stage is considered an error. + + If the ``ExecResource`` is not in the desired state based on the + exit code from the ``validate`` stage, the agent proceeds to execute + the script from the ``enforce`` stage. If the ``ExecResource`` is + already in the desired state, the ``enforce`` stage will not be run. + Similar to ``validate`` stage, the ``enforce`` stage should return + an exit code of ``100`` to indicate that the resource in now in its + desired state. Any other exit code is considered an error. + + NOTE: An exit code of ``100`` was chosen over ``0`` (and ``101`` vs + ``1``) to have an explicit indicator of ``in desired state``, + ``not in desired state`` and errors. Because, for example, + Powershell will always return an exit code of ``0`` unless an + ``exit`` statement is provided in the script. So, for reasons of + consistency and being explicit, exit codes ``100`` and ``101`` were + chosen. + + Attributes: + validate (google.cloud.osconfig_v1.types.OSPolicy.Resource.ExecResource.Exec): + Required. What to run to validate this + resource is in the desired state. An exit code + of 100 indicates "in desired state", and exit + code of 101 indicates "not in desired state". + Any other exit code indicates a failure running + validate. + enforce (google.cloud.osconfig_v1.types.OSPolicy.Resource.ExecResource.Exec): + What to run to bring this resource into the + desired state. An exit code of 100 indicates + "success", any other exit code indicates a + failure running enforce. + """ + + class Exec(proto.Message): + r"""A file or script to execute. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + file (google.cloud.osconfig_v1.types.OSPolicy.Resource.File): + A remote or local file. + This field is a member of `oneof`_ ``source``. + script (str): + An inline script. + The size of the script is limited to 1024 + characters. + This field is a member of `oneof`_ ``source``. + args (Sequence[str]): + Optional arguments to pass to the source + during execution. + interpreter (google.cloud.osconfig_v1.types.OSPolicy.Resource.ExecResource.Exec.Interpreter): + Required. The script interpreter to use. + output_file_path (str): + Only recorded for enforce Exec. + Path to an output file (that is created by this + Exec) whose content will be recorded in + OSPolicyResourceCompliance after a successful + run. Absence or failure to read this file will + result in this ExecResource being non-compliant. + Output file size is limited to 100K bytes. + """ + + class Interpreter(proto.Enum): + r"""The interpreter to use.""" + INTERPRETER_UNSPECIFIED = 0 + NONE = 1 + SHELL = 2 + POWERSHELL = 3 + + file = proto.Field( + proto.MESSAGE, + number=1, + oneof="source", + message="OSPolicy.Resource.File", + ) + script = proto.Field(proto.STRING, number=2, oneof="source",) + args = proto.RepeatedField(proto.STRING, number=3,) + interpreter = proto.Field( + proto.ENUM, + number=4, + enum="OSPolicy.Resource.ExecResource.Exec.Interpreter", + ) + output_file_path = proto.Field(proto.STRING, number=5,) + + validate = proto.Field( + proto.MESSAGE, number=1, message="OSPolicy.Resource.ExecResource.Exec", + ) + enforce = proto.Field( + proto.MESSAGE, number=2, message="OSPolicy.Resource.ExecResource.Exec", + ) + + class FileResource(proto.Message): + r"""A resource that manages the state of a file. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + file (google.cloud.osconfig_v1.types.OSPolicy.Resource.File): + A remote or local source. + This field is a member of `oneof`_ ``source``. + content (str): + A a file with this content. + The size of the content is limited to 1024 + characters. + This field is a member of `oneof`_ ``source``. + path (str): + Required. The absolute path of the file + within the VM. + state (google.cloud.osconfig_v1.types.OSPolicy.Resource.FileResource.DesiredState): + Required. Desired state of the file. + permissions (str): + Consists of three octal digits which + represent, in order, the permissions of the + owner, group, and other users for the file + (similarly to the numeric mode used in the linux + chmod utility). Each digit represents a three + bit number with the 4 bit corresponding to the + read permissions, the 2 bit corresponds to the + write bit, and the one bit corresponds to the + execute permission. Default behavior is 755. + + Below are some examples of permissions and their + associated values: read, write, and execute: 7 + read and execute: 5 + read and write: 6 + read only: 4 + """ + + class DesiredState(proto.Enum): + r"""Desired state of the file.""" + DESIRED_STATE_UNSPECIFIED = 0 + PRESENT = 1 + ABSENT = 2 + CONTENTS_MATCH = 3 + + file = proto.Field( + proto.MESSAGE, + number=1, + oneof="source", + message="OSPolicy.Resource.File", + ) + content = proto.Field(proto.STRING, number=2, oneof="source",) + path = proto.Field(proto.STRING, number=3,) + state = proto.Field( + proto.ENUM, + number=4, + enum="OSPolicy.Resource.FileResource.DesiredState", + ) + permissions = proto.Field(proto.STRING, number=5,) + + id = proto.Field(proto.STRING, number=1,) + pkg = proto.Field( + proto.MESSAGE, + number=2, + oneof="resource_type", + message="OSPolicy.Resource.PackageResource", + ) + repository = proto.Field( + proto.MESSAGE, + number=3, + oneof="resource_type", + message="OSPolicy.Resource.RepositoryResource", + ) + exec_ = proto.Field( + proto.MESSAGE, + number=4, + oneof="resource_type", + message="OSPolicy.Resource.ExecResource", + ) + file = proto.Field( + proto.MESSAGE, + number=5, + oneof="resource_type", + message="OSPolicy.Resource.FileResource", + ) + + class ResourceGroup(proto.Message): + r"""Resource groups provide a mechanism to group OS policy resources. + + Resource groups enable OS policy authors to create a single OS + policy to be applied to VMs running different operating Systems. + + When the OS policy is applied to a target VM, the appropriate + resource group within the OS policy is selected based on the + ``OSFilter`` specified within the resource group. + + Attributes: + inventory_filters (Sequence[google.cloud.osconfig_v1.types.OSPolicy.InventoryFilter]): + List of inventory filters for the resource group. + + The resources in this resource group are applied to the + target VM if it satisfies at least one of the following + inventory filters. + + For example, to apply this resource group to VMs running + either ``RHEL`` or ``CentOS`` operating systems, specify 2 + items for the list with following values: + inventory_filters[0].os_short_name='rhel' and + inventory_filters[1].os_short_name='centos' + + If the list is empty, this resource group will be applied to + the target VM unconditionally. + resources (Sequence[google.cloud.osconfig_v1.types.OSPolicy.Resource]): + Required. List of resources configured for + this resource group. The resources are executed + in the exact order specified here. + """ + + inventory_filters = proto.RepeatedField( + proto.MESSAGE, number=1, message="OSPolicy.InventoryFilter", + ) + resources = proto.RepeatedField( + proto.MESSAGE, number=2, message="OSPolicy.Resource", + ) + + id = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + mode = proto.Field(proto.ENUM, number=3, enum=Mode,) + resource_groups = proto.RepeatedField( + proto.MESSAGE, number=4, message=ResourceGroup, + ) + allow_no_resource_group_match = proto.Field(proto.BOOL, number=5,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/osconfig_v1/types/os_policy_assignment_reports.py b/google/cloud/osconfig_v1/types/os_policy_assignment_reports.py new file mode 100644 index 0000000..83e4575 --- /dev/null +++ b/google/cloud/osconfig_v1/types/os_policy_assignment_reports.py @@ -0,0 +1,328 @@ +# -*- 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={ + "GetOSPolicyAssignmentReportRequest", + "ListOSPolicyAssignmentReportsRequest", + "ListOSPolicyAssignmentReportsResponse", + "OSPolicyAssignmentReport", + }, +) + + +class GetOSPolicyAssignmentReportRequest(proto.Message): + r"""Get a report of the OS policy assignment for a VM instance. + + Attributes: + name (str): + Required. API resource name for OS policy assignment report. + + Format: + ``/projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}/report`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance_id}``, + either Compute Engine ``instance-id`` or ``instance-name`` + can be provided. For ``{assignment_id}``, the + OSPolicyAssignment id must be provided. + """ + + name = proto.Field(proto.STRING, number=1,) + + +class ListOSPolicyAssignmentReportsRequest(proto.Message): + r"""List the OS policy assignment reports for VM instances. + + Attributes: + parent (str): + Required. The parent resource name. + + Format: + ``projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}/reports`` + + For ``{project}``, either ``project-number`` or + ``project-id`` can be provided. For ``{instance}``, either + ``instance-name``, ``instance-id``, or ``-`` can be + provided. If '-' is provided, the response will include + OSPolicyAssignmentReports for all instances in the + project/location. For ``{assignment}``, either + ``assignment-id`` or ``-`` can be provided. If '-' is + provided, the response will include + OSPolicyAssignmentReports for all OSPolicyAssignments in the + project/location. Either {instance} or {assignment} must be + ``-``. + + For example: + ``projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/-/reports`` + returns all reports for the instance + ``projects/{project}/locations/{location}/instances/-/osPolicyAssignments/{assignment-id}/reports`` + returns all the reports for the given assignment across all + instances. + ``projects/{project}/locations/{location}/instances/-/osPolicyAssignments/-/reports`` + returns all the reports for all assignments across all + instances. + page_size (int): + The maximum number of results to return. + filter (str): + If provided, this field specifies the criteria that must be + met by the ``OSPolicyAssignmentReport`` API resource that is + included in the response. + page_token (str): + A pagination token returned from a previous call to the + ``ListOSPolicyAssignmentReports`` method that indicates + where this listing should continue from. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + filter = proto.Field(proto.STRING, number=3,) + page_token = proto.Field(proto.STRING, number=4,) + + +class ListOSPolicyAssignmentReportsResponse(proto.Message): + r"""A response message for listing OS Policy assignment reports + including the page of results and page token. + + Attributes: + os_policy_assignment_reports (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignmentReport]): + List of OS policy assignment reports. + next_page_token (str): + The pagination token to retrieve the next + page of OS policy assignment report objects. + """ + + @property + def raw_page(self): + return self + + os_policy_assignment_reports = proto.RepeatedField( + proto.MESSAGE, number=1, message="OSPolicyAssignmentReport", + ) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class OSPolicyAssignmentReport(proto.Message): + r"""A report of the OS policy assignment status for a given + instance. + + Attributes: + name (str): + The ``OSPolicyAssignmentReport`` API resource name. + + Format: + ``projects/{project_number}/locations/{location}/instances/{instance_id}/osPolicyAssignments/{os_policy_assignment_id}/report`` + instance (str): + The Compute Engine VM instance name. + os_policy_assignment (str): + Reference to the ``OSPolicyAssignment`` API resource that + the ``OSPolicy`` belongs to. + + Format: + ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id@revision_id}`` + os_policy_compliances (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignmentReport.OSPolicyCompliance]): + Compliance data for each ``OSPolicy`` that is applied to the + VM. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp for when the report was last + generated. + last_run_id (str): + Unique identifier of the last attempted run + to apply the OS policies associated with this + assignment on the VM. + This ID is logged by the OS Config agent while + applying the OS policies associated with this + assignment on the VM. NOTE: If the service is + unable to successfully connect to the agent for + this run, then this id will not be available in + the agent logs. + """ + + class OSPolicyCompliance(proto.Message): + r"""Compliance data for an OS policy + + Attributes: + os_policy_id (str): + The OS policy id + compliance_state (google.cloud.osconfig_v1.types.OSPolicyAssignmentReport.OSPolicyCompliance.ComplianceState): + The compliance state of the OS policy. + compliance_state_reason (str): + The reason for the OS policy to be in an unknown compliance + state. This field is always populated when + ``compliance_state`` is ``UNKNOWN``. + + If populated, the field can contain one of the following + values: + + - ``vm-not-running``: The VM was not running. + - ``os-policies-not-supported-by-agent``: The version of + the OS Config agent running on the VM does not support + running OS policies. + - ``no-agent-detected``: The OS Config agent is not + detected for the VM. + - ``resource-execution-errors``: The OS Config agent + encountered errors while executing one or more resources + in the policy. See ``os_policy_resource_compliances`` for + details. + - ``task-timeout``: The task sent to the agent to apply the + policy timed out. + - ``unexpected-agent-state``: The OS Config agent did not + report the final status of the task that attempted to + apply the policy. Instead, the agent unexpectedly started + working on a different task. This mostly happens when the + agent or VM unexpectedly restarts while applying OS + policies. + - ``internal-service-errors``: Internal service errors were + encountered while attempting to apply the policy. + os_policy_resource_compliances (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance]): + Compliance data for each resource within the + policy that is applied to the VM. + """ + + class ComplianceState(proto.Enum): + r"""Possible compliance states for an os policy.""" + UNKNOWN = 0 + COMPLIANT = 1 + NON_COMPLIANT = 2 + + class OSPolicyResourceCompliance(proto.Message): + r"""Compliance data for an OS policy resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + os_policy_resource_id (str): + The ID of the OS policy resource. + config_steps (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance.OSPolicyResourceConfigStep]): + Ordered list of configuration completed by + the agent for the OS policy resource. + compliance_state (google.cloud.osconfig_v1.types.OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance.ComplianceState): + The compliance state of the resource. + compliance_state_reason (str): + A reason for the resource to be in the given compliance + state. This field is always populated when + ``compliance_state`` is ``UNKNOWN``. + + The following values are supported when + ``compliance_state == UNKNOWN`` + + - ``execution-errors``: Errors were encountered by the + agent while executing the resource and the compliance + state couldn't be determined. + - ``execution-skipped-by-agent``: Resource execution was + skipped by the agent because errors were encountered + while executing prior resources in the OS policy. + - ``os-policy-execution-attempt-failed``: The execution of + the OS policy containing this resource failed and the + compliance state couldn't be determined. + exec_resource_output (google.cloud.osconfig_v1.types.OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance.ExecResourceOutput): + ExecResource specific output. + This field is a member of `oneof`_ ``output``. + """ + + class ComplianceState(proto.Enum): + r"""Possible compliance states for a resource.""" + UNKNOWN = 0 + COMPLIANT = 1 + NON_COMPLIANT = 2 + + class OSPolicyResourceConfigStep(proto.Message): + r"""Step performed by the OS Config agent for configuring an + ``OSPolicy`` resource to its desired state. + + Attributes: + type_ (google.cloud.osconfig_v1.types.OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance.OSPolicyResourceConfigStep.Type): + Configuration step type. + error_message (str): + An error message recorded during the + execution of this step. Only populated if errors + were encountered during this step execution. + """ + + class Type(proto.Enum): + r"""Supported configuration step types""" + TYPE_UNSPECIFIED = 0 + VALIDATION = 1 + DESIRED_STATE_CHECK = 2 + DESIRED_STATE_ENFORCEMENT = 3 + DESIRED_STATE_CHECK_POST_ENFORCEMENT = 4 + + type_ = proto.Field( + proto.ENUM, + number=1, + enum="OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance.OSPolicyResourceConfigStep.Type", + ) + error_message = proto.Field(proto.STRING, number=2,) + + class ExecResourceOutput(proto.Message): + r"""ExecResource specific output. + + Attributes: + enforcement_output (bytes): + Output from enforcement phase output file (if + run). Output size is limited to 100K bytes. + """ + + enforcement_output = proto.Field(proto.BYTES, number=2,) + + os_policy_resource_id = proto.Field(proto.STRING, number=1,) + config_steps = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance.OSPolicyResourceConfigStep", + ) + compliance_state = proto.Field( + proto.ENUM, + number=3, + enum="OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance.ComplianceState", + ) + compliance_state_reason = proto.Field(proto.STRING, number=4,) + exec_resource_output = proto.Field( + proto.MESSAGE, + number=5, + oneof="output", + message="OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance.ExecResourceOutput", + ) + + os_policy_id = proto.Field(proto.STRING, number=1,) + compliance_state = proto.Field( + proto.ENUM, + number=2, + enum="OSPolicyAssignmentReport.OSPolicyCompliance.ComplianceState", + ) + compliance_state_reason = proto.Field(proto.STRING, number=3,) + os_policy_resource_compliances = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="OSPolicyAssignmentReport.OSPolicyCompliance.OSPolicyResourceCompliance", + ) + + name = proto.Field(proto.STRING, number=1,) + instance = proto.Field(proto.STRING, number=2,) + os_policy_assignment = proto.Field(proto.STRING, number=3,) + os_policy_compliances = proto.RepeatedField( + proto.MESSAGE, number=4, message=OSPolicyCompliance, + ) + update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + last_run_id = proto.Field(proto.STRING, number=6,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/osconfig_v1/types/os_policy_assignments.py b/google/cloud/osconfig_v1/types/os_policy_assignments.py new file mode 100644 index 0000000..e19c445 --- /dev/null +++ b/google/cloud/osconfig_v1/types/os_policy_assignments.py @@ -0,0 +1,455 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.cloud.osconfig_v1.types import os_policy +from google.cloud.osconfig_v1.types import osconfig_common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.osconfig.v1", + manifest={ + "OSPolicyAssignment", + "OSPolicyAssignmentOperationMetadata", + "CreateOSPolicyAssignmentRequest", + "UpdateOSPolicyAssignmentRequest", + "GetOSPolicyAssignmentRequest", + "ListOSPolicyAssignmentsRequest", + "ListOSPolicyAssignmentsResponse", + "ListOSPolicyAssignmentRevisionsRequest", + "ListOSPolicyAssignmentRevisionsResponse", + "DeleteOSPolicyAssignmentRequest", + }, +) + + +class OSPolicyAssignment(proto.Message): + r"""OS policy assignment is an API resource that is used to apply a set + of OS policies to a dynamically targeted group of Compute Engine VM + instances. + + An OS policy is used to define the desired state configuration for a + Compute Engine VM instance through a set of configuration resources + that provide capabilities such as installing or removing software + packages, or executing a script. + + For more information, see `OS policy and OS policy + assignment `__. + + Attributes: + name (str): + Resource name. + + Format: + ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id}`` + + This field is ignored when you create an OS policy + assignment. + description (str): + OS policy assignment description. + Length of the description is limited to 1024 + characters. + os_policies (Sequence[google.cloud.osconfig_v1.types.OSPolicy]): + Required. List of OS policies to be applied + to the VMs. + instance_filter (google.cloud.osconfig_v1.types.OSPolicyAssignment.InstanceFilter): + Required. Filter to select VMs. + rollout (google.cloud.osconfig_v1.types.OSPolicyAssignment.Rollout): + Required. Rollout to deploy the OS policy assignment. A + rollout is triggered in the following situations: + + 1) OSPolicyAssignment is created. + 2) OSPolicyAssignment is updated and the update contains + changes to one of the following fields: + + - instance_filter + - os_policies + + 3) OSPolicyAssignment is deleted. + revision_id (str): + Output only. The assignment revision ID + A new revision is committed whenever a rollout + is triggered for a OS policy assignment + revision_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp that the revision + was created. + etag (str): + The etag for this OS policy assignment. + If this is provided on update, it must match the + server's etag. + rollout_state (google.cloud.osconfig_v1.types.OSPolicyAssignment.RolloutState): + Output only. OS policy assignment rollout + state + baseline (bool): + Output only. Indicates that this revision has been + successfully rolled out in this zone and new VMs will be + assigned OS policies from this revision. + + For a given OS policy assignment, there is only one revision + with a value of ``true`` for this field. + deleted (bool): + Output only. Indicates that this revision + deletes the OS policy assignment. + reconciling (bool): + Output only. Indicates that reconciliation is in progress + for the revision. This value is ``true`` when the + ``rollout_state`` is one of: + + - IN_PROGRESS + - CANCELLING + uid (str): + Output only. Server generated unique id for + the OS policy assignment resource. + """ + + class RolloutState(proto.Enum): + r"""OS policy assignment rollout state""" + ROLLOUT_STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + CANCELLING = 2 + CANCELLED = 3 + SUCCEEDED = 4 + + class LabelSet(proto.Message): + r"""Message representing label set. + + - A label is a key value pair set for a VM. + - A LabelSet is a set of labels. + - Labels within a LabelSet are ANDed. In other words, a LabelSet is + applicable for a VM only if it matches all the labels in the + LabelSet. + - Example: A LabelSet with 2 labels: ``env=prod`` and + ``type=webserver`` will only be applicable for those VMs with + both labels present. + + Attributes: + labels (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignment.LabelSet.LabelsEntry]): + Labels are identified by key/value pairs in + this map. A VM should contain all the key/value + pairs specified in this map to be selected. + """ + + labels = proto.MapField(proto.STRING, proto.STRING, number=1,) + + class InstanceFilter(proto.Message): + r"""Filters to select target VMs for an assignment. + If more than one filter criteria is specified below, a VM will + be selected if and only if it satisfies all of them. + + Attributes: + all_ (bool): + Target all VMs in the project. If true, no + other criteria is permitted. + inclusion_labels (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignment.LabelSet]): + List of label sets used for VM inclusion. + + If the list has more than one ``LabelSet``, the VM is + included if any of the label sets are applicable for the VM. + exclusion_labels (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignment.LabelSet]): + List of label sets used for VM exclusion. + If the list has more than one label set, the VM + is excluded if any of the label sets are + applicable for the VM. + inventories (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignment.InstanceFilter.Inventory]): + List of inventories to select VMs. + A VM is selected if its inventory data matches + at least one of the following inventories. + """ + + class Inventory(proto.Message): + r"""VM inventory details. + + Attributes: + os_short_name (str): + Required. The OS short name + os_version (str): + The OS version + + Prefix matches are supported if asterisk(*) is provided as + the last character. For example, to match all versions with + a major version of ``7``, specify the following value for + this field ``7.*`` + + An empty string matches all OS versions. + """ + + os_short_name = proto.Field(proto.STRING, number=1,) + os_version = proto.Field(proto.STRING, number=2,) + + all_ = proto.Field(proto.BOOL, number=1,) + inclusion_labels = proto.RepeatedField( + proto.MESSAGE, number=2, message="OSPolicyAssignment.LabelSet", + ) + exclusion_labels = proto.RepeatedField( + proto.MESSAGE, number=3, message="OSPolicyAssignment.LabelSet", + ) + inventories = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="OSPolicyAssignment.InstanceFilter.Inventory", + ) + + class Rollout(proto.Message): + r"""Message to configure the rollout at the zonal level for the + OS policy assignment. + + Attributes: + disruption_budget (google.cloud.osconfig_v1.types.FixedOrPercent): + Required. The maximum number (or percentage) + of VMs per zone to disrupt at any given moment. + min_wait_duration (google.protobuf.duration_pb2.Duration): + Required. This determines the minimum duration of time to + wait after the configuration changes are applied through the + current rollout. A VM continues to count towards the + ``disruption_budget`` at least until this duration of time + has passed after configuration changes are applied. + """ + + disruption_budget = proto.Field( + proto.MESSAGE, number=1, message=osconfig_common.FixedOrPercent, + ) + min_wait_duration = proto.Field( + proto.MESSAGE, number=2, message=duration_pb2.Duration, + ) + + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + os_policies = proto.RepeatedField( + proto.MESSAGE, number=3, message=os_policy.OSPolicy, + ) + instance_filter = proto.Field(proto.MESSAGE, number=4, message=InstanceFilter,) + rollout = proto.Field(proto.MESSAGE, number=5, message=Rollout,) + revision_id = proto.Field(proto.STRING, number=6,) + revision_create_time = proto.Field( + proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp, + ) + etag = proto.Field(proto.STRING, number=8,) + rollout_state = proto.Field(proto.ENUM, number=9, enum=RolloutState,) + baseline = proto.Field(proto.BOOL, number=10,) + deleted = proto.Field(proto.BOOL, number=11,) + reconciling = proto.Field(proto.BOOL, number=12,) + uid = proto.Field(proto.STRING, number=13,) + + +class OSPolicyAssignmentOperationMetadata(proto.Message): + r"""OS policy assignment operation metadata provided by OS policy + assignment API methods that return long running operations. + + Attributes: + os_policy_assignment (str): + Reference to the ``OSPolicyAssignment`` API resource. + + Format: + ``projects/{project_number}/locations/{location}/osPolicyAssignments/{os_policy_assignment_id@revision_id}`` + api_method (google.cloud.osconfig_v1.types.OSPolicyAssignmentOperationMetadata.APIMethod): + The OS policy assignment API method. + rollout_state (google.cloud.osconfig_v1.types.OSPolicyAssignmentOperationMetadata.RolloutState): + State of the rollout + rollout_start_time (google.protobuf.timestamp_pb2.Timestamp): + Rollout start time + rollout_update_time (google.protobuf.timestamp_pb2.Timestamp): + Rollout update time + """ + + class APIMethod(proto.Enum): + r"""The OS policy assignment API method.""" + API_METHOD_UNSPECIFIED = 0 + CREATE = 1 + UPDATE = 2 + DELETE = 3 + + class RolloutState(proto.Enum): + r"""State of the rollout""" + ROLLOUT_STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + CANCELLING = 2 + CANCELLED = 3 + SUCCEEDED = 4 + + os_policy_assignment = proto.Field(proto.STRING, number=1,) + api_method = proto.Field(proto.ENUM, number=2, enum=APIMethod,) + rollout_state = proto.Field(proto.ENUM, number=3, enum=RolloutState,) + rollout_start_time = proto.Field( + proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp, + ) + rollout_update_time = proto.Field( + proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, + ) + + +class CreateOSPolicyAssignmentRequest(proto.Message): + r"""A request message to create an OS policy assignment + + Attributes: + parent (str): + Required. The parent resource name in the + form: projects/{project}/locations/{location} + os_policy_assignment (google.cloud.osconfig_v1.types.OSPolicyAssignment): + Required. The OS policy assignment to be + created. + os_policy_assignment_id (str): + Required. The logical name of the OS policy assignment in + the project with the following restrictions: + + - Must contain only lowercase letters, numbers, and + hyphens. + - Must start with a letter. + - Must be between 1-63 characters. + - Must end with a number or a letter. + - Must be unique within the project. + """ + + parent = proto.Field(proto.STRING, number=1,) + os_policy_assignment = proto.Field( + proto.MESSAGE, number=2, message="OSPolicyAssignment", + ) + os_policy_assignment_id = proto.Field(proto.STRING, number=3,) + + +class UpdateOSPolicyAssignmentRequest(proto.Message): + r"""A request message to update an OS policy assignment + + Attributes: + os_policy_assignment (google.cloud.osconfig_v1.types.OSPolicyAssignment): + Required. The updated OS policy assignment. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask that controls which + fields of the assignment should be updated. + """ + + os_policy_assignment = proto.Field( + proto.MESSAGE, number=1, message="OSPolicyAssignment", + ) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + + +class GetOSPolicyAssignmentRequest(proto.Message): + r"""A request message to get an OS policy assignment + + Attributes: + name (str): + Required. The resource name of OS policy assignment. + + Format: + ``projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}@{revisionId}`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class ListOSPolicyAssignmentsRequest(proto.Message): + r"""A request message to list OS policy assignments for a parent + resource + + Attributes: + parent (str): + Required. The parent resource name. + page_size (int): + The maximum number of assignments to return. + page_token (str): + A pagination token returned from a previous call to + ``ListOSPolicyAssignments`` that indicates where this + listing should continue from. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + + +class ListOSPolicyAssignmentsResponse(proto.Message): + r"""A response message for listing all assignments under given + parent. + + Attributes: + os_policy_assignments (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignment]): + The list of assignments + next_page_token (str): + The pagination token to retrieve the next + page of OS policy assignments. + """ + + @property + def raw_page(self): + return self + + os_policy_assignments = proto.RepeatedField( + proto.MESSAGE, number=1, message="OSPolicyAssignment", + ) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class ListOSPolicyAssignmentRevisionsRequest(proto.Message): + r"""A request message to list revisions for a OS policy + assignment + + Attributes: + name (str): + Required. The name of the OS policy + assignment to list revisions for. + page_size (int): + The maximum number of revisions to return. + page_token (str): + A pagination token returned from a previous call to + ``ListOSPolicyAssignmentRevisions`` that indicates where + this listing should continue from. + """ + + name = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + + +class ListOSPolicyAssignmentRevisionsResponse(proto.Message): + r"""A response message for listing all revisions for a OS policy + assignment. + + Attributes: + os_policy_assignments (Sequence[google.cloud.osconfig_v1.types.OSPolicyAssignment]): + The OS policy assignment revisions + next_page_token (str): + The pagination token to retrieve the next + page of OS policy assignment revisions. + """ + + @property + def raw_page(self): + return self + + os_policy_assignments = proto.RepeatedField( + proto.MESSAGE, number=1, message="OSPolicyAssignment", + ) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class DeleteOSPolicyAssignmentRequest(proto.Message): + r"""A request message for deleting a OS policy assignment. + + Attributes: + name (str): + Required. The name of the OS policy + assignment to be deleted + """ + + name = proto.Field(proto.STRING, number=1,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py b/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py index a099930..fe1f807 100644 --- a/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py +++ b/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/async_client.py @@ -253,7 +253,6 @@ async def create_os_policy_assignment( - Must end with a number or a letter. - Must be unique within the project. - This corresponds to the ``os_policy_assignment_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. diff --git a/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py b/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py index 5e510a6..1ed9c62 100644 --- a/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py +++ b/google/cloud/osconfig_v1alpha/services/os_config_zonal_service/client.py @@ -490,7 +490,6 @@ def create_os_policy_assignment( - Must end with a number or a letter. - Must be unique within the project. - This corresponds to the ``os_policy_assignment_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. diff --git a/scripts/fixup_osconfig_v1_keywords.py b/scripts/fixup_osconfig_v1_keywords.py index d186953..57cd075 100644 --- a/scripts/fixup_osconfig_v1_keywords.py +++ b/scripts/fixup_osconfig_v1_keywords.py @@ -40,18 +40,26 @@ class osconfigCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'cancel_patch_job': ('name', ), + 'create_os_policy_assignment': ('parent', 'os_policy_assignment', 'os_policy_assignment_id', ), 'create_patch_deployment': ('parent', 'patch_deployment_id', 'patch_deployment', ), + 'delete_os_policy_assignment': ('name', ), 'delete_patch_deployment': ('name', ), 'execute_patch_job': ('parent', 'instance_filter', 'description', 'patch_config', 'duration', 'dry_run', 'display_name', 'rollout', ), 'get_inventory': ('name', 'view', ), + 'get_os_policy_assignment': ('name', ), + 'get_os_policy_assignment_report': ('name', ), 'get_patch_deployment': ('name', ), 'get_patch_job': ('name', ), 'get_vulnerability_report': ('name', ), 'list_inventories': ('parent', 'view', 'page_size', 'page_token', 'filter', ), + 'list_os_policy_assignment_reports': ('parent', 'page_size', 'filter', 'page_token', ), + 'list_os_policy_assignment_revisions': ('name', 'page_size', 'page_token', ), + 'list_os_policy_assignments': ('parent', 'page_size', 'page_token', ), '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', ), + 'update_os_policy_assignment': ('os_policy_assignment', 'update_mask', ), } 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 index a7c2157..a67e3f4 100644 --- a/tests/unit/gapic/osconfig_v1/test_os_config_zonal_service.py +++ b/tests/unit/gapic/osconfig_v1/test_os_config_zonal_service.py @@ -25,9 +25,12 @@ from google.api_core import client_options from google.api_core import exceptions as core_exceptions +from google.api_core import future from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError @@ -40,8 +43,15 @@ 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.types import inventory +from google.cloud.osconfig_v1.types import os_policy +from google.cloud.osconfig_v1.types import os_policy_assignment_reports +from google.cloud.osconfig_v1.types import os_policy_assignments +from google.cloud.osconfig_v1.types import osconfig_common from google.cloud.osconfig_v1.types import vulnerability +from google.longrunning import operations_pb2 from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import google.auth @@ -506,6 +516,2519 @@ def test_os_config_zonal_service_client_client_options_from_dict(): ) +def test_create_os_policy_assignment( + transport: str = "grpc", + request_type=os_policy_assignments.CreateOSPolicyAssignmentRequest, +): + 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.create_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_os_policy_assignment_from_dict(): + test_create_os_policy_assignment(request_type=dict) + + +def test_create_os_policy_assignment_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.create_os_policy_assignment), "__call__" + ) as call: + client.create_os_policy_assignment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_async( + transport: str = "grpc_asyncio", + request_type=os_policy_assignments.CreateOSPolicyAssignmentRequest, +): + 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.create_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.CreateOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_async_from_dict(): + await test_create_os_policy_assignment_async(request_type=dict) + + +def test_create_os_policy_assignment_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 = os_policy_assignments.CreateOSPolicyAssignmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_os_policy_assignment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_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 = os_policy_assignments.CreateOSPolicyAssignmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_os_policy_assignment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_os_policy_assignment_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.create_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_os_policy_assignment( + parent="parent_value", + os_policy_assignment=os_policy_assignments.OSPolicyAssignment( + name="name_value" + ), + os_policy_assignment_id="os_policy_assignment_id_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" + assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment( + name="name_value" + ) + assert args[0].os_policy_assignment_id == "os_policy_assignment_id_value" + + +def test_create_os_policy_assignment_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.create_os_policy_assignment( + os_policy_assignments.CreateOSPolicyAssignmentRequest(), + parent="parent_value", + os_policy_assignment=os_policy_assignments.OSPolicyAssignment( + name="name_value" + ), + os_policy_assignment_id="os_policy_assignment_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_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.create_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_os_policy_assignment( + parent="parent_value", + os_policy_assignment=os_policy_assignments.OSPolicyAssignment( + name="name_value" + ), + os_policy_assignment_id="os_policy_assignment_id_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" + assert args[0].os_policy_assignment == os_policy_assignments.OSPolicyAssignment( + name="name_value" + ) + assert args[0].os_policy_assignment_id == "os_policy_assignment_id_value" + + +@pytest.mark.asyncio +async def test_create_os_policy_assignment_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.create_os_policy_assignment( + os_policy_assignments.CreateOSPolicyAssignmentRequest(), + parent="parent_value", + os_policy_assignment=os_policy_assignments.OSPolicyAssignment( + name="name_value" + ), + os_policy_assignment_id="os_policy_assignment_id_value", + ) + + +def test_update_os_policy_assignment( + transport: str = "grpc", + request_type=os_policy_assignments.UpdateOSPolicyAssignmentRequest, +): + 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.update_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_os_policy_assignment_from_dict(): + test_update_os_policy_assignment(request_type=dict) + + +def test_update_os_policy_assignment_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.update_os_policy_assignment), "__call__" + ) as call: + client.update_os_policy_assignment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_async( + transport: str = "grpc_asyncio", + request_type=os_policy_assignments.UpdateOSPolicyAssignmentRequest, +): + 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.update_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.update_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_async_from_dict(): + await test_update_os_policy_assignment_async(request_type=dict) + + +def test_update_os_policy_assignment_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 = os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + request.os_policy_assignment.name = "os_policy_assignment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_os_policy_assignment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_os_policy_assignment(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", + "os_policy_assignment.name=os_policy_assignment.name/value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_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 = os_policy_assignments.UpdateOSPolicyAssignmentRequest() + + request.os_policy_assignment.name = "os_policy_assignment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_os_policy_assignment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_os_policy_assignment(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", + "os_policy_assignment.name=os_policy_assignment.name/value", + ) in kw["metadata"] + + +def test_update_os_policy_assignment_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.update_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_os_policy_assignment( + os_policy_assignment=os_policy_assignments.OSPolicyAssignment( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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].os_policy_assignment == os_policy_assignments.OSPolicyAssignment( + name="name_value" + ) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + + +def test_update_os_policy_assignment_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.update_os_policy_assignment( + os_policy_assignments.UpdateOSPolicyAssignmentRequest(), + os_policy_assignment=os_policy_assignments.OSPolicyAssignment( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_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.update_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_os_policy_assignment( + os_policy_assignment=os_policy_assignments.OSPolicyAssignment( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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].os_policy_assignment == os_policy_assignments.OSPolicyAssignment( + name="name_value" + ) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_os_policy_assignment_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.update_os_policy_assignment( + os_policy_assignments.UpdateOSPolicyAssignmentRequest(), + os_policy_assignment=os_policy_assignments.OSPolicyAssignment( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_os_policy_assignment( + transport: str = "grpc", + request_type=os_policy_assignments.GetOSPolicyAssignmentRequest, +): + 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_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.OSPolicyAssignment( + name="name_value", + description="description_value", + revision_id="revision_id_value", + etag="etag_value", + rollout_state=os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS, + baseline=True, + deleted=True, + reconciling=True, + uid="uid_value", + ) + response = client.get_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, os_policy_assignments.OSPolicyAssignment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.revision_id == "revision_id_value" + assert response.etag == "etag_value" + assert ( + response.rollout_state + == os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS + ) + assert response.baseline is True + assert response.deleted is True + assert response.reconciling is True + assert response.uid == "uid_value" + + +def test_get_os_policy_assignment_from_dict(): + test_get_os_policy_assignment(request_type=dict) + + +def test_get_os_policy_assignment_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_os_policy_assignment), "__call__" + ) as call: + client.get_os_policy_assignment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_async( + transport: str = "grpc_asyncio", + request_type=os_policy_assignments.GetOSPolicyAssignmentRequest, +): + 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_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.OSPolicyAssignment( + name="name_value", + description="description_value", + revision_id="revision_id_value", + etag="etag_value", + rollout_state=os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS, + baseline=True, + deleted=True, + reconciling=True, + uid="uid_value", + ) + ) + response = await client.get_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.GetOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, os_policy_assignments.OSPolicyAssignment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.revision_id == "revision_id_value" + assert response.etag == "etag_value" + assert ( + response.rollout_state + == os_policy_assignments.OSPolicyAssignment.RolloutState.IN_PROGRESS + ) + assert response.baseline is True + assert response.deleted is True + assert response.reconciling is True + assert response.uid == "uid_value" + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_async_from_dict(): + await test_get_os_policy_assignment_async(request_type=dict) + + +def test_get_os_policy_assignment_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 = os_policy_assignments.GetOSPolicyAssignmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_os_policy_assignment), "__call__" + ) as call: + call.return_value = os_policy_assignments.OSPolicyAssignment() + client.get_os_policy_assignment(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_os_policy_assignment_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 = os_policy_assignments.GetOSPolicyAssignmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_os_policy_assignment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.OSPolicyAssignment() + ) + await client.get_os_policy_assignment(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_os_policy_assignment_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_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.OSPolicyAssignment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_os_policy_assignment(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_os_policy_assignment_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_os_policy_assignment( + os_policy_assignments.GetOSPolicyAssignmentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_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_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.OSPolicyAssignment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.OSPolicyAssignment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_os_policy_assignment(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_os_policy_assignment_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_os_policy_assignment( + os_policy_assignments.GetOSPolicyAssignmentRequest(), name="name_value", + ) + + +def test_list_os_policy_assignments( + transport: str = "grpc", + request_type=os_policy_assignments.ListOSPolicyAssignmentsRequest, +): + 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_os_policy_assignments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_os_policy_assignments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_os_policy_assignments_from_dict(): + test_list_os_policy_assignments(request_type=dict) + + +def test_list_os_policy_assignments_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_os_policy_assignments), "__call__" + ) as call: + client.list_os_policy_assignments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() + + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_async( + transport: str = "grpc_asyncio", + request_type=os_policy_assignments.ListOSPolicyAssignmentsRequest, +): + 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_os_policy_assignments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_os_policy_assignments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_async_from_dict(): + await test_list_os_policy_assignments_async(request_type=dict) + + +def test_list_os_policy_assignments_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 = os_policy_assignments.ListOSPolicyAssignmentsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), "__call__" + ) as call: + call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() + client.list_os_policy_assignments(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_os_policy_assignments_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 = os_policy_assignments.ListOSPolicyAssignmentsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignments), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.ListOSPolicyAssignmentsResponse() + ) + await client.list_os_policy_assignments(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_os_policy_assignments_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_os_policy_assignments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_os_policy_assignments(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_os_policy_assignments_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_os_policy_assignments( + os_policy_assignments.ListOSPolicyAssignmentsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_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_os_policy_assignments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.ListOSPolicyAssignmentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_os_policy_assignments(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_os_policy_assignments_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_os_policy_assignments( + os_policy_assignments.ListOSPolicyAssignmentsRequest(), + parent="parent_value", + ) + + +def test_list_os_policy_assignments_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_os_policy_assignments), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token="abc", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[], next_page_token="def", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[os_policy_assignments.OSPolicyAssignment(),], + next_page_token="ghi", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_os_policy_assignments(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all( + isinstance(i, os_policy_assignments.OSPolicyAssignment) for i in results + ) + + +def test_list_os_policy_assignments_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_os_policy_assignments), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token="abc", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[], next_page_token="def", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[os_policy_assignments.OSPolicyAssignment(),], + next_page_token="ghi", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_os_policy_assignments(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_os_policy_assignments_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_os_policy_assignments), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token="abc", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[], next_page_token="def", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[os_policy_assignments.OSPolicyAssignment(),], + next_page_token="ghi", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_os_policy_assignments(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, os_policy_assignments.OSPolicyAssignment) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignments_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_os_policy_assignments), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token="abc", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[], next_page_token="def", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[os_policy_assignments.OSPolicyAssignment(),], + next_page_token="ghi", + ), + os_policy_assignments.ListOSPolicyAssignmentsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_os_policy_assignments(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_os_policy_assignment_revisions( + transport: str = "grpc", + request_type=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, +): + 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_os_policy_assignment_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_os_policy_assignment_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentRevisionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_os_policy_assignment_revisions_from_dict(): + test_list_os_policy_assignment_revisions(request_type=dict) + + +def test_list_os_policy_assignment_revisions_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_os_policy_assignment_revisions), "__call__" + ) as call: + client.list_os_policy_assignment_revisions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_async( + transport: str = "grpc_asyncio", + request_type=os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest, +): + 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_os_policy_assignment_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_os_policy_assignment_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentRevisionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_async_from_dict(): + await test_list_os_policy_assignment_revisions_async(request_type=dict) + + +def test_list_os_policy_assignment_revisions_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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), "__call__" + ) as call: + call.return_value = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() + ) + client.list_os_policy_assignment_revisions(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_list_os_policy_assignment_revisions_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 = os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_revisions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() + ) + await client.list_os_policy_assignment_revisions(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_list_os_policy_assignment_revisions_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_os_policy_assignment_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_os_policy_assignment_revisions(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_list_os_policy_assignment_revisions_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_os_policy_assignment_revisions( + os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_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_os_policy_assignment_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_os_policy_assignment_revisions(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_list_os_policy_assignment_revisions_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_os_policy_assignment_revisions( + os_policy_assignments.ListOSPolicyAssignmentRevisionsRequest(), + name="name_value", + ) + + +def test_list_os_policy_assignment_revisions_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_os_policy_assignment_revisions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token="abc", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[], next_page_token="def", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[os_policy_assignments.OSPolicyAssignment(),], + next_page_token="ghi", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_os_policy_assignment_revisions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all( + isinstance(i, os_policy_assignments.OSPolicyAssignment) for i in results + ) + + +def test_list_os_policy_assignment_revisions_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_os_policy_assignment_revisions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token="abc", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[], next_page_token="def", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[os_policy_assignments.OSPolicyAssignment(),], + next_page_token="ghi", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_os_policy_assignment_revisions(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_os_policy_assignment_revisions_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_os_policy_assignment_revisions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token="abc", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[], next_page_token="def", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[os_policy_assignments.OSPolicyAssignment(),], + next_page_token="ghi", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_os_policy_assignment_revisions(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, os_policy_assignments.OSPolicyAssignment) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_revisions_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_os_policy_assignment_revisions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + next_page_token="abc", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[], next_page_token="def", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[os_policy_assignments.OSPolicyAssignment(),], + next_page_token="ghi", + ), + os_policy_assignments.ListOSPolicyAssignmentRevisionsResponse( + os_policy_assignments=[ + os_policy_assignments.OSPolicyAssignment(), + os_policy_assignments.OSPolicyAssignment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_os_policy_assignment_revisions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_os_policy_assignment( + transport: str = "grpc", + request_type=os_policy_assignments.DeleteOSPolicyAssignmentRequest, +): + 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.delete_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_os_policy_assignment_from_dict(): + test_delete_os_policy_assignment(request_type=dict) + + +def test_delete_os_policy_assignment_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.delete_os_policy_assignment), "__call__" + ) as call: + client.delete_os_policy_assignment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_async( + transport: str = "grpc_asyncio", + request_type=os_policy_assignments.DeleteOSPolicyAssignmentRequest, +): + 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.delete_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_async_from_dict(): + await test_delete_os_policy_assignment_async(request_type=dict) + + +def test_delete_os_policy_assignment_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 = os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_os_policy_assignment), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_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 = os_policy_assignments.DeleteOSPolicyAssignmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_os_policy_assignment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_os_policy_assignment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_os_policy_assignment_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.delete_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_os_policy_assignment(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + + +def test_delete_os_policy_assignment_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.delete_os_policy_assignment( + os_policy_assignments.DeleteOSPolicyAssignmentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_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.delete_os_policy_assignment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_os_policy_assignment(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_os_policy_assignment_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.delete_os_policy_assignment( + os_policy_assignments.DeleteOSPolicyAssignmentRequest(), name="name_value", + ) + + +def test_get_os_policy_assignment_report( + transport: str = "grpc", + request_type=os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest, +): + 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_os_policy_assignment_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignment_reports.OSPolicyAssignmentReport( + name="name_value", + instance="instance_value", + os_policy_assignment="os_policy_assignment_value", + last_run_id="last_run_id_value", + ) + response = client.get_os_policy_assignment_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] == os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest() + ) + + # Establish that the response is the type that we expect. + assert isinstance(response, os_policy_assignment_reports.OSPolicyAssignmentReport) + assert response.name == "name_value" + assert response.instance == "instance_value" + assert response.os_policy_assignment == "os_policy_assignment_value" + assert response.last_run_id == "last_run_id_value" + + +def test_get_os_policy_assignment_report_from_dict(): + test_get_os_policy_assignment_report(request_type=dict) + + +def test_get_os_policy_assignment_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_os_policy_assignment_report), "__call__" + ) as call: + client.get_os_policy_assignment_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert ( + args[0] == os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest() + ) + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_report_async( + transport: str = "grpc_asyncio", + request_type=os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest, +): + 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_os_policy_assignment_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignment_reports.OSPolicyAssignmentReport( + name="name_value", + instance="instance_value", + os_policy_assignment="os_policy_assignment_value", + last_run_id="last_run_id_value", + ) + ) + response = await client.get_os_policy_assignment_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert ( + args[0] == os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest() + ) + + # Establish that the response is the type that we expect. + assert isinstance(response, os_policy_assignment_reports.OSPolicyAssignmentReport) + assert response.name == "name_value" + assert response.instance == "instance_value" + assert response.os_policy_assignment == "os_policy_assignment_value" + assert response.last_run_id == "last_run_id_value" + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_report_async_from_dict(): + await test_get_os_policy_assignment_report_async(request_type=dict) + + +def test_get_os_policy_assignment_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 = os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_os_policy_assignment_report), "__call__" + ) as call: + call.return_value = os_policy_assignment_reports.OSPolicyAssignmentReport() + client.get_os_policy_assignment_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_os_policy_assignment_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 = os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_os_policy_assignment_report), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignment_reports.OSPolicyAssignmentReport() + ) + await client.get_os_policy_assignment_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_os_policy_assignment_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_os_policy_assignment_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignment_reports.OSPolicyAssignmentReport() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_os_policy_assignment_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_os_policy_assignment_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_os_policy_assignment_report( + os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_os_policy_assignment_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_os_policy_assignment_report), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignment_reports.OSPolicyAssignmentReport() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignment_reports.OSPolicyAssignmentReport() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_os_policy_assignment_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_os_policy_assignment_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_os_policy_assignment_report( + os_policy_assignment_reports.GetOSPolicyAssignmentReportRequest(), + name="name_value", + ) + + +def test_list_os_policy_assignment_reports( + transport: str = "grpc", + request_type=os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest, +): + 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_os_policy_assignment_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_os_policy_assignment_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] + == os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest() + ) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentReportsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_os_policy_assignment_reports_from_dict(): + test_list_os_policy_assignment_reports(request_type=dict) + + +def test_list_os_policy_assignment_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_os_policy_assignment_reports), "__call__" + ) as call: + client.list_os_policy_assignment_reports() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert ( + args[0] + == os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest() + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_reports_async( + transport: str = "grpc_asyncio", + request_type=os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest, +): + 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_os_policy_assignment_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_os_policy_assignment_reports(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert ( + args[0] + == os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest() + ) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOSPolicyAssignmentReportsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_reports_async_from_dict(): + await test_list_os_policy_assignment_reports_async(request_type=dict) + + +def test_list_os_policy_assignment_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 = os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_reports), "__call__" + ) as call: + call.return_value = ( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse() + ) + client.list_os_policy_assignment_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_os_policy_assignment_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 = os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_os_policy_assignment_reports), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse() + ) + await client.list_os_policy_assignment_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_os_policy_assignment_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_os_policy_assignment_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_os_policy_assignment_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_os_policy_assignment_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_os_policy_assignment_reports( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_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_os_policy_assignment_reports), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_os_policy_assignment_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_os_policy_assignment_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_os_policy_assignment_reports( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsRequest(), + parent="parent_value", + ) + + +def test_list_os_policy_assignment_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_os_policy_assignment_reports), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + next_page_token="abc", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[], next_page_token="def", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + next_page_token="ghi", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_os_policy_assignment_reports(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all( + isinstance(i, os_policy_assignment_reports.OSPolicyAssignmentReport) + for i in results + ) + + +def test_list_os_policy_assignment_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_os_policy_assignment_reports), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + next_page_token="abc", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[], next_page_token="def", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + next_page_token="ghi", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + ), + RuntimeError, + ) + pages = list(client.list_os_policy_assignment_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_os_policy_assignment_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_os_policy_assignment_reports), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + next_page_token="abc", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[], next_page_token="def", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + next_page_token="ghi", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_os_policy_assignment_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, os_policy_assignment_reports.OSPolicyAssignmentReport) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_os_policy_assignment_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_os_policy_assignment_reports), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + next_page_token="abc", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[], next_page_token="def", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + next_page_token="ghi", + ), + os_policy_assignment_reports.ListOSPolicyAssignmentReportsResponse( + os_policy_assignment_reports=[ + os_policy_assignment_reports.OSPolicyAssignmentReport(), + os_policy_assignment_reports.OSPolicyAssignmentReport(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_os_policy_assignment_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_get_inventory( transport: str = "grpc", request_type=inventory.GetInventoryRequest ): @@ -1793,6 +4316,14 @@ def test_os_config_zonal_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( + "create_os_policy_assignment", + "update_os_policy_assignment", + "get_os_policy_assignment", + "list_os_policy_assignments", + "list_os_policy_assignment_revisions", + "delete_os_policy_assignment", + "get_os_policy_assignment_report", + "list_os_policy_assignment_reports", "get_inventory", "list_inventories", "get_vulnerability_report", @@ -1805,6 +4336,11 @@ def test_os_config_zonal_service_base_transport(): with pytest.raises(NotImplementedError): transport.close() + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + def test_os_config_zonal_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file @@ -2097,6 +4633,32 @@ def test_os_config_zonal_service_transport_channel_mtls_with_adc(transport_class assert transport.grpc_channel == mock_grpc_channel +def test_os_config_zonal_service_grpc_lro_client(): + client = OsConfigZonalServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_os_config_zonal_service_grpc_lro_async_client(): + client = OsConfigZonalServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + def test_instance_path(): project = "squid" zone = "clam" @@ -2121,10 +4683,38 @@ def test_parse_instance_path(): assert expected == actual -def test_inventory_path(): +def test_instance_os_policy_assignment_path(): project = "cuttlefish" location = "mussel" instance = "winkle" + assignment = "nautilus" + expected = "projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}".format( + project=project, location=location, instance=instance, assignment=assignment, + ) + actual = OsConfigZonalServiceClient.instance_os_policy_assignment_path( + project, location, instance, assignment + ) + assert expected == actual + + +def test_parse_instance_os_policy_assignment_path(): + expected = { + "project": "scallop", + "location": "abalone", + "instance": "squid", + "assignment": "clam", + } + path = OsConfigZonalServiceClient.instance_os_policy_assignment_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_instance_os_policy_assignment_path(path) + assert expected == actual + + +def test_inventory_path(): + project = "whelk" + location = "octopus" + instance = "oyster" expected = "projects/{project}/locations/{location}/instances/{instance}/inventory".format( project=project, location=location, instance=instance, ) @@ -2134,9 +4724,9 @@ def test_inventory_path(): def test_parse_inventory_path(): expected = { - "project": "nautilus", - "location": "scallop", - "instance": "abalone", + "project": "nudibranch", + "location": "cuttlefish", + "instance": "mussel", } path = OsConfigZonalServiceClient.inventory_path(**expected) @@ -2145,10 +4735,64 @@ def test_parse_inventory_path(): assert expected == actual +def test_os_policy_assignment_path(): + project = "winkle" + location = "nautilus" + os_policy_assignment = "scallop" + expected = "projects/{project}/locations/{location}/osPolicyAssignments/{os_policy_assignment}".format( + project=project, location=location, os_policy_assignment=os_policy_assignment, + ) + actual = OsConfigZonalServiceClient.os_policy_assignment_path( + project, location, os_policy_assignment + ) + assert expected == actual + + +def test_parse_os_policy_assignment_path(): + expected = { + "project": "abalone", + "location": "squid", + "os_policy_assignment": "clam", + } + path = OsConfigZonalServiceClient.os_policy_assignment_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_os_policy_assignment_path(path) + assert expected == actual + + +def test_os_policy_assignment_report_path(): + project = "whelk" + location = "octopus" + instance = "oyster" + assignment = "nudibranch" + expected = "projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/{assignment}/report".format( + project=project, location=location, instance=instance, assignment=assignment, + ) + actual = OsConfigZonalServiceClient.os_policy_assignment_report_path( + project, location, instance, assignment + ) + assert expected == actual + + +def test_parse_os_policy_assignment_report_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "instance": "winkle", + "assignment": "nautilus", + } + path = OsConfigZonalServiceClient.os_policy_assignment_report_path(**expected) + + # Check that the path construction is reversible. + actual = OsConfigZonalServiceClient.parse_os_policy_assignment_report_path(path) + assert expected == actual + + def test_vulnerability_report_path(): - project = "squid" - location = "clam" - instance = "whelk" + project = "scallop" + location = "abalone" + instance = "squid" expected = "projects/{project}/locations/{location}/instances/{instance}/vulnerabilityReport".format( project=project, location=location, instance=instance, ) @@ -2160,9 +4804,9 @@ def test_vulnerability_report_path(): def test_parse_vulnerability_report_path(): expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", + "project": "clam", + "location": "whelk", + "instance": "octopus", } path = OsConfigZonalServiceClient.vulnerability_report_path(**expected) @@ -2172,7 +4816,7 @@ def test_parse_vulnerability_report_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2182,7 +4826,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "nudibranch", } path = OsConfigZonalServiceClient.common_billing_account_path(**expected) @@ -2192,7 +4836,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "cuttlefish" expected = "folders/{folder}".format(folder=folder,) actual = OsConfigZonalServiceClient.common_folder_path(folder) assert expected == actual @@ -2200,7 +4844,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "mussel", } path = OsConfigZonalServiceClient.common_folder_path(**expected) @@ -2210,7 +4854,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "winkle" expected = "organizations/{organization}".format(organization=organization,) actual = OsConfigZonalServiceClient.common_organization_path(organization) assert expected == actual @@ -2218,7 +4862,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "nautilus", } path = OsConfigZonalServiceClient.common_organization_path(**expected) @@ -2228,7 +4872,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "scallop" expected = "projects/{project}".format(project=project,) actual = OsConfigZonalServiceClient.common_project_path(project) assert expected == actual @@ -2236,7 +4880,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "abalone", } path = OsConfigZonalServiceClient.common_project_path(**expected) @@ -2246,8 +4890,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2257,8 +4901,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "whelk", + "location": "octopus", } path = OsConfigZonalServiceClient.common_location_path(**expected)