diff --git a/packages/google-cloud-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index d23fd25bb1f0..4af29ebae727 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -325,6 +325,7 @@ AllocationAggregateReservation, AllocationAggregateReservationReservedResourceInfo, AllocationAggregateReservationReservedResourceInfoAccelerator, + AllocationReservationSharingPolicy, AllocationResourceStatus, AllocationResourceStatusSpecificSKUAllocation, AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk, @@ -363,12 +364,14 @@ BackendBucketCdnPolicyNegativeCachingPolicy, BackendBucketList, BackendBucketUsedBy, + BackendCustomMetric, BackendService, BackendServiceAggregatedList, BackendServiceCdnPolicy, BackendServiceCdnPolicyBypassCacheOnRequestHeader, BackendServiceCdnPolicyNegativeCachingPolicy, BackendServiceConnectionTrackingPolicy, + BackendServiceCustomMetric, BackendServiceFailoverPolicy, BackendServiceGroupHealth, BackendServiceHttpCookie, @@ -871,6 +874,7 @@ InstanceGroupManagerResizeRequestsListResponse, InstanceGroupManagerResizeRequestStatus, InstanceGroupManagerResizeRequestStatusLastAttempt, + InstanceGroupManagerResourcePolicies, InstanceGroupManagersAbandonInstancesRequest, InstanceGroupManagersApplyUpdatesRequest, InstanceGroupManagersCreateInstancesRequest, @@ -920,6 +924,8 @@ InstancesGetEffectiveFirewallsResponse, InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy, InstancesRemoveResourcePoliciesRequest, + InstancesReportHostAsFaultyRequest, + InstancesReportHostAsFaultyRequestFaultReason, InstancesScopedList, InstancesSetLabelsRequest, InstancesSetMachineResourcesRequest, @@ -1345,6 +1351,7 @@ RemoveRuleRegionNetworkFirewallPolicyRequest, RemoveRuleRegionSecurityPolicyRequest, RemoveRuleSecurityPolicyRequest, + ReportHostAsFaultyInstanceRequest, RequestMirrorPolicy, Reservation, ReservationAffinity, @@ -1379,6 +1386,7 @@ ResourcePolicyWeeklyCycle, ResourcePolicyWeeklyCycleDayOfWeek, ResourceStatus, + ResourceStatusPhysicalHostTopology, ResourceStatusScheduling, ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, @@ -1971,6 +1979,7 @@ "AllocationAggregateReservation", "AllocationAggregateReservationReservedResourceInfo", "AllocationAggregateReservationReservedResourceInfoAccelerator", + "AllocationReservationSharingPolicy", "AllocationResourceStatus", "AllocationResourceStatusSpecificSKUAllocation", "AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", @@ -2009,12 +2018,14 @@ "BackendBucketCdnPolicyNegativeCachingPolicy", "BackendBucketList", "BackendBucketUsedBy", + "BackendCustomMetric", "BackendService", "BackendServiceAggregatedList", "BackendServiceCdnPolicy", "BackendServiceCdnPolicyBypassCacheOnRequestHeader", "BackendServiceCdnPolicyNegativeCachingPolicy", "BackendServiceConnectionTrackingPolicy", + "BackendServiceCustomMetric", "BackendServiceFailoverPolicy", "BackendServiceGroupHealth", "BackendServiceHttpCookie", @@ -2517,6 +2528,7 @@ "InstanceGroupManagerResizeRequestsListResponse", "InstanceGroupManagerResizeRequestStatus", "InstanceGroupManagerResizeRequestStatusLastAttempt", + "InstanceGroupManagerResourcePolicies", "InstanceGroupManagersAbandonInstancesRequest", "InstanceGroupManagersApplyUpdatesRequest", "InstanceGroupManagersCreateInstancesRequest", @@ -2566,6 +2578,8 @@ "InstancesGetEffectiveFirewallsResponse", "InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "InstancesRemoveResourcePoliciesRequest", + "InstancesReportHostAsFaultyRequest", + "InstancesReportHostAsFaultyRequestFaultReason", "InstancesScopedList", "InstancesSetLabelsRequest", "InstancesSetMachineResourcesRequest", @@ -2991,6 +3005,7 @@ "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "Reservation", "ReservationAffinity", @@ -3025,6 +3040,7 @@ "ResourcePolicyWeeklyCycle", "ResourcePolicyWeeklyCycleDayOfWeek", "ResourceStatus", + "ResourceStatusPhysicalHostTopology", "ResourceStatusScheduling", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 0810b52e6900..2e21a5d5cb12 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -207,6 +207,7 @@ AllocationAggregateReservation, AllocationAggregateReservationReservedResourceInfo, AllocationAggregateReservationReservedResourceInfoAccelerator, + AllocationReservationSharingPolicy, AllocationResourceStatus, AllocationResourceStatusSpecificSKUAllocation, AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk, @@ -245,12 +246,14 @@ BackendBucketCdnPolicyNegativeCachingPolicy, BackendBucketList, BackendBucketUsedBy, + BackendCustomMetric, BackendService, BackendServiceAggregatedList, BackendServiceCdnPolicy, BackendServiceCdnPolicyBypassCacheOnRequestHeader, BackendServiceCdnPolicyNegativeCachingPolicy, BackendServiceConnectionTrackingPolicy, + BackendServiceCustomMetric, BackendServiceFailoverPolicy, BackendServiceGroupHealth, BackendServiceHttpCookie, @@ -753,6 +756,7 @@ InstanceGroupManagerResizeRequestsListResponse, InstanceGroupManagerResizeRequestStatus, InstanceGroupManagerResizeRequestStatusLastAttempt, + InstanceGroupManagerResourcePolicies, InstanceGroupManagersAbandonInstancesRequest, InstanceGroupManagersApplyUpdatesRequest, InstanceGroupManagersCreateInstancesRequest, @@ -802,6 +806,8 @@ InstancesGetEffectiveFirewallsResponse, InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy, InstancesRemoveResourcePoliciesRequest, + InstancesReportHostAsFaultyRequest, + InstancesReportHostAsFaultyRequestFaultReason, InstancesScopedList, InstancesSetLabelsRequest, InstancesSetMachineResourcesRequest, @@ -1227,6 +1233,7 @@ RemoveRuleRegionNetworkFirewallPolicyRequest, RemoveRuleRegionSecurityPolicyRequest, RemoveRuleSecurityPolicyRequest, + ReportHostAsFaultyInstanceRequest, RequestMirrorPolicy, Reservation, ReservationAffinity, @@ -1261,6 +1268,7 @@ ResourcePolicyWeeklyCycle, ResourcePolicyWeeklyCycleDayOfWeek, ResourceStatus, + ResourceStatusPhysicalHostTopology, ResourceStatusScheduling, ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, @@ -1757,6 +1765,7 @@ "AllocationAggregateReservation", "AllocationAggregateReservationReservedResourceInfo", "AllocationAggregateReservationReservedResourceInfoAccelerator", + "AllocationReservationSharingPolicy", "AllocationResourceStatus", "AllocationResourceStatusSpecificSKUAllocation", "AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", @@ -1796,12 +1805,14 @@ "BackendBucketList", "BackendBucketUsedBy", "BackendBucketsClient", + "BackendCustomMetric", "BackendService", "BackendServiceAggregatedList", "BackendServiceCdnPolicy", "BackendServiceCdnPolicyBypassCacheOnRequestHeader", "BackendServiceCdnPolicyNegativeCachingPolicy", "BackendServiceConnectionTrackingPolicy", + "BackendServiceCustomMetric", "BackendServiceFailoverPolicy", "BackendServiceGroupHealth", "BackendServiceHttpCookie", @@ -2321,6 +2332,7 @@ "InstanceGroupManagerResizeRequestStatusLastAttempt", "InstanceGroupManagerResizeRequestsClient", "InstanceGroupManagerResizeRequestsListResponse", + "InstanceGroupManagerResourcePolicies", "InstanceGroupManagerStandbyPolicy", "InstanceGroupManagerStatus", "InstanceGroupManagerStatusAllInstancesConfig", @@ -2380,6 +2392,8 @@ "InstancesGetEffectiveFirewallsResponse", "InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "InstancesRemoveResourcePoliciesRequest", + "InstancesReportHostAsFaultyRequest", + "InstancesReportHostAsFaultyRequestFaultReason", "InstancesScopedList", "InstancesSetLabelsRequest", "InstancesSetMachineResourcesRequest", @@ -2847,6 +2861,7 @@ "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "Reservation", "ReservationAffinity", @@ -2883,6 +2898,7 @@ "ResourcePolicyWeeklyCycle", "ResourcePolicyWeeklyCycleDayOfWeek", "ResourceStatus", + "ResourceStatusPhysicalHostTopology", "ResourceStatusScheduling", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json index 8a29ebae6f52..62a1a2aa584d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json +++ b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json @@ -1355,6 +1355,11 @@ "remove_resource_policies" ] }, + "ReportHostAsFaulty": { + "methods": [ + "report_host_as_faulty" + ] + }, "Reset": { "methods": [ "reset" diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py index 636d324a0482..abb5c0532639 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/client.py @@ -5243,6 +5243,341 @@ def error_code(self): # Done; return the response. return response + def report_host_as_faulty_unary( + self, + request: Optional[ + Union[compute.ReportHostAsFaultyInstanceRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instance: Optional[str] = None, + instances_report_host_as_faulty_request_resource: Optional[ + compute.InstancesReportHostAsFaultyRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Mark the host as faulty and try to restart the + instance on a new host. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_report_host_as_faulty(): + # Create a client + client = compute_v1.InstancesClient() + + # Initialize request argument(s) + request = compute_v1.ReportHostAsFaultyInstanceRequest( + instance="instance_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.report_host_as_faulty(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ReportHostAsFaultyInstanceRequest, dict]): + The request object. A request message for + Instances.ReportHostAsFaulty. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (str): + Name of the instance scoping this + request. + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instances_report_host_as_faulty_request_resource (google.cloud.compute_v1.types.InstancesReportHostAsFaultyRequest): + The body resource for this request + This corresponds to the ``instances_report_host_as_faulty_request_resource`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + zone, + instance, + instances_report_host_as_faulty_request_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.ReportHostAsFaultyInstanceRequest): + request = compute.ReportHostAsFaultyInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instance is not None: + request.instance = instance + if instances_report_host_as_faulty_request_resource is not None: + request.instances_report_host_as_faulty_request_resource = ( + instances_report_host_as_faulty_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report_host_as_faulty] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("instance", request.instance), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def report_host_as_faulty( + self, + request: Optional[ + Union[compute.ReportHostAsFaultyInstanceRequest, dict] + ] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + instance: Optional[str] = None, + instances_report_host_as_faulty_request_resource: Optional[ + compute.InstancesReportHostAsFaultyRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Mark the host as faulty and try to restart the + instance on a new host. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1 + + def sample_report_host_as_faulty(): + # Create a client + client = compute_v1.InstancesClient() + + # Initialize request argument(s) + request = compute_v1.ReportHostAsFaultyInstanceRequest( + instance="instance_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.report_host_as_faulty(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ReportHostAsFaultyInstanceRequest, dict]): + The request object. A request message for + Instances.ReportHostAsFaulty. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (str): + Name of the instance scoping this + request. + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instances_report_host_as_faulty_request_resource (google.cloud.compute_v1.types.InstancesReportHostAsFaultyRequest): + The body resource for this request + This corresponds to the ``instances_report_host_as_faulty_request_resource`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + zone, + instance, + instances_report_host_as_faulty_request_resource, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.ReportHostAsFaultyInstanceRequest): + request = compute.ReportHostAsFaultyInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if instance is not None: + request.instance = instance + if instances_report_host_as_faulty_request_resource is not None: + request.instances_report_host_as_faulty_request_resource = ( + instances_report_host_as_faulty_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.report_host_as_faulty] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("instance", request.instance), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def reset_unary( self, request: Optional[Union[compute.ResetInstanceRequest, dict]] = None, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py index 9b764b1e9d41..6d4e3cf3738c 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/base.py @@ -233,6 +233,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.report_host_as_faulty: gapic_v1.method.wrap_method( + self.report_host_as_faulty, + default_timeout=None, + client_info=client_info, + ), self.reset: gapic_v1.method.wrap_method( self.reset, default_timeout=None, @@ -572,6 +577,15 @@ def remove_resource_policies( ]: raise NotImplementedError() + @property + def report_host_as_faulty( + self, + ) -> Callable[ + [compute.ReportHostAsFaultyInstanceRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def reset( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py index 112f97691957..6f4bd164e88d 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest.py @@ -228,6 +228,14 @@ def post_remove_resource_policies(self, response): logging.log(f"Received response: {response}") return response + def pre_report_host_as_faulty(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_report_host_as_faulty(self, response): + logging.log(f"Received response: {response}") + return response + def pre_reset(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -1403,6 +1411,55 @@ def post_remove_resource_policies_with_metadata( """ return response, metadata + def pre_report_host_as_faulty( + self, + request: compute.ReportHostAsFaultyInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ReportHostAsFaultyInstanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for report_host_as_faulty + + Override in a subclass to manipulate the request or metadata + before they are sent to the Instances server. + """ + return request, metadata + + def post_report_host_as_faulty( + self, response: compute.Operation + ) -> compute.Operation: + """Post-rpc interceptor for report_host_as_faulty + + DEPRECATED. Please use the `post_report_host_as_faulty_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Instances server but before + it is returned to user code. This `post_report_host_as_faulty` interceptor runs + before the `post_report_host_as_faulty_with_metadata` interceptor. + """ + return response + + def post_report_host_as_faulty_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for report_host_as_faulty + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Instances server but before it is returned to user code. + + We recommend only using this `post_report_host_as_faulty_with_metadata` + interceptor in new development instead of the `post_report_host_as_faulty` interceptor. + When both interceptors are used, this `post_report_host_as_faulty_with_metadata` interceptor runs after the + `post_report_host_as_faulty` interceptor. The (possibly modified) response returned by + `post_report_host_as_faulty` will be passed to + `post_report_host_as_faulty_with_metadata`. + """ + return response, metadata + def pre_reset( self, request: compute.ResetInstanceRequest, @@ -6016,6 +6073,177 @@ def __call__( ) return resp + class _ReportHostAsFaulty( + _BaseInstancesRestTransport._BaseReportHostAsFaulty, InstancesRestStub + ): + def __hash__(self): + return hash("InstancesRestTransport.ReportHostAsFaulty") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: compute.ReportHostAsFaultyInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the report host as faulty method over HTTP. + + Args: + request (~.compute.ReportHostAsFaultyInstanceRequest): + The request object. A request message for + Instances.ReportHostAsFaulty. See the + method description for details. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.Operation: + Represents an Operation resource. Google Compute Engine + has three Operation resources: \* + `Global `__ + \* + `Regional `__ + \* + `Zonal `__ + You can use an operation resource to manage asynchronous + API requests. For more information, read Handling API + responses. Operations can be global, regional or zonal. + - For global operations, use the ``globalOperations`` + resource. - For regional operations, use the + ``regionOperations`` resource. - For zonal operations, + use the ``zoneOperations`` resource. For more + information, read Global, Regional, and Zonal Resources. + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseInstancesRestTransport._BaseReportHostAsFaulty._get_http_options() + ) + + request, metadata = self._interceptor.pre_report_host_as_faulty( + request, metadata + ) + transcoded_request = _BaseInstancesRestTransport._BaseReportHostAsFaulty._get_transcoded_request( + http_options, request + ) + + body = _BaseInstancesRestTransport._BaseReportHostAsFaulty._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseInstancesRestTransport._BaseReportHostAsFaulty._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1.InstancesClient.ReportHostAsFaulty", + extra={ + "serviceName": "google.cloud.compute.v1.Instances", + "rpcName": "ReportHostAsFaulty", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = InstancesRestTransport._ReportHostAsFaulty._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_report_host_as_faulty(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_report_host_as_faulty_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1.InstancesClient.report_host_as_faulty", + extra={ + "serviceName": "google.cloud.compute.v1.Instances", + "rpcName": "ReportHostAsFaulty", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _Reset(_BaseInstancesRestTransport._BaseReset, InstancesRestStub): def __hash__(self): return hash("InstancesRestTransport.Reset") @@ -10899,6 +11127,14 @@ def remove_resource_policies( # In C++ this would require a dynamic_cast return self._RemoveResourcePolicies(self._session, self._host, self._interceptor) # type: ignore + @property + def report_host_as_faulty( + self, + ) -> Callable[[compute.ReportHostAsFaultyInstanceRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReportHostAsFaulty(self._session, self._host, self._interceptor) # type: ignore + @property def reset(self) -> Callable[[compute.ResetInstanceRequest], compute.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest_base.py index 2955d44c9181..61eb5dab121f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest_base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/instances/transports/rest_base.py @@ -1076,6 +1076,62 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseReportHostAsFaulty: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/reportHostAsFaulty", + "body": "instances_report_host_as_faulty_request_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ReportHostAsFaultyInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseInstancesRestTransport._BaseReportHostAsFaulty._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseReset: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py index 0521b2afc042..aad3cd401493 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py @@ -97,6 +97,7 @@ AllocationAggregateReservation, AllocationAggregateReservationReservedResourceInfo, AllocationAggregateReservationReservedResourceInfoAccelerator, + AllocationReservationSharingPolicy, AllocationResourceStatus, AllocationResourceStatusSpecificSKUAllocation, AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk, @@ -135,12 +136,14 @@ BackendBucketCdnPolicyNegativeCachingPolicy, BackendBucketList, BackendBucketUsedBy, + BackendCustomMetric, BackendService, BackendServiceAggregatedList, BackendServiceCdnPolicy, BackendServiceCdnPolicyBypassCacheOnRequestHeader, BackendServiceCdnPolicyNegativeCachingPolicy, BackendServiceConnectionTrackingPolicy, + BackendServiceCustomMetric, BackendServiceFailoverPolicy, BackendServiceGroupHealth, BackendServiceHttpCookie, @@ -643,6 +646,7 @@ InstanceGroupManagerResizeRequestsListResponse, InstanceGroupManagerResizeRequestStatus, InstanceGroupManagerResizeRequestStatusLastAttempt, + InstanceGroupManagerResourcePolicies, InstanceGroupManagersAbandonInstancesRequest, InstanceGroupManagersApplyUpdatesRequest, InstanceGroupManagersCreateInstancesRequest, @@ -692,6 +696,8 @@ InstancesGetEffectiveFirewallsResponse, InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy, InstancesRemoveResourcePoliciesRequest, + InstancesReportHostAsFaultyRequest, + InstancesReportHostAsFaultyRequestFaultReason, InstancesScopedList, InstancesSetLabelsRequest, InstancesSetMachineResourcesRequest, @@ -1117,6 +1123,7 @@ RemoveRuleRegionNetworkFirewallPolicyRequest, RemoveRuleRegionSecurityPolicyRequest, RemoveRuleSecurityPolicyRequest, + ReportHostAsFaultyInstanceRequest, RequestMirrorPolicy, Reservation, ReservationAffinity, @@ -1151,6 +1158,7 @@ ResourcePolicyWeeklyCycle, ResourcePolicyWeeklyCycleDayOfWeek, ResourceStatus, + ResourceStatusPhysicalHostTopology, ResourceStatusScheduling, ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, @@ -1644,6 +1652,7 @@ "AllocationAggregateReservation", "AllocationAggregateReservationReservedResourceInfo", "AllocationAggregateReservationReservedResourceInfoAccelerator", + "AllocationReservationSharingPolicy", "AllocationResourceStatus", "AllocationResourceStatusSpecificSKUAllocation", "AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", @@ -1682,12 +1691,14 @@ "BackendBucketCdnPolicyNegativeCachingPolicy", "BackendBucketList", "BackendBucketUsedBy", + "BackendCustomMetric", "BackendService", "BackendServiceAggregatedList", "BackendServiceCdnPolicy", "BackendServiceCdnPolicyBypassCacheOnRequestHeader", "BackendServiceCdnPolicyNegativeCachingPolicy", "BackendServiceConnectionTrackingPolicy", + "BackendServiceCustomMetric", "BackendServiceFailoverPolicy", "BackendServiceGroupHealth", "BackendServiceHttpCookie", @@ -2190,6 +2201,7 @@ "InstanceGroupManagerResizeRequestsListResponse", "InstanceGroupManagerResizeRequestStatus", "InstanceGroupManagerResizeRequestStatusLastAttempt", + "InstanceGroupManagerResourcePolicies", "InstanceGroupManagersAbandonInstancesRequest", "InstanceGroupManagersApplyUpdatesRequest", "InstanceGroupManagersCreateInstancesRequest", @@ -2239,6 +2251,8 @@ "InstancesGetEffectiveFirewallsResponse", "InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "InstancesRemoveResourcePoliciesRequest", + "InstancesReportHostAsFaultyRequest", + "InstancesReportHostAsFaultyRequestFaultReason", "InstancesScopedList", "InstancesSetLabelsRequest", "InstancesSetMachineResourcesRequest", @@ -2664,6 +2678,7 @@ "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "Reservation", "ReservationAffinity", @@ -2698,6 +2713,7 @@ "ResourcePolicyWeeklyCycle", "ResourcePolicyWeeklyCycleDayOfWeek", "ResourceStatus", + "ResourceStatusPhysicalHostTopology", "ResourceStatusScheduling", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py index 77bc3be1e383..9ab56364b89f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py @@ -107,6 +107,7 @@ "AllocationAggregateReservation", "AllocationAggregateReservationReservedResourceInfo", "AllocationAggregateReservationReservedResourceInfoAccelerator", + "AllocationReservationSharingPolicy", "AllocationResourceStatus", "AllocationResourceStatusSpecificSKUAllocation", "AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk", @@ -144,12 +145,14 @@ "BackendBucketCdnPolicyNegativeCachingPolicy", "BackendBucketList", "BackendBucketUsedBy", + "BackendCustomMetric", "BackendService", "BackendServiceAggregatedList", "BackendServiceCdnPolicy", "BackendServiceCdnPolicyBypassCacheOnRequestHeader", "BackendServiceCdnPolicyNegativeCachingPolicy", "BackendServiceConnectionTrackingPolicy", + "BackendServiceCustomMetric", "BackendServiceFailoverPolicy", "BackendServiceGroupHealth", "BackendServiceHttpCookie", @@ -652,6 +655,7 @@ "InstanceGroupManagerResizeRequestStatus", "InstanceGroupManagerResizeRequestStatusLastAttempt", "InstanceGroupManagerResizeRequestsListResponse", + "InstanceGroupManagerResourcePolicies", "InstanceGroupManagerStandbyPolicy", "InstanceGroupManagerStatus", "InstanceGroupManagerStatusAllInstancesConfig", @@ -706,6 +710,8 @@ "InstancesGetEffectiveFirewallsResponse", "InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy", "InstancesRemoveResourcePoliciesRequest", + "InstancesReportHostAsFaultyRequest", + "InstancesReportHostAsFaultyRequestFaultReason", "InstancesScopedList", "InstancesSetLabelsRequest", "InstancesSetMachineResourcesRequest", @@ -1126,6 +1132,7 @@ "RemoveRuleRegionNetworkFirewallPolicyRequest", "RemoveRuleRegionSecurityPolicyRequest", "RemoveRuleSecurityPolicyRequest", + "ReportHostAsFaultyInstanceRequest", "RequestMirrorPolicy", "Reservation", "ReservationAffinity", @@ -1160,6 +1167,7 @@ "ResourcePolicyWeeklyCycle", "ResourcePolicyWeeklyCycleDayOfWeek", "ResourceStatus", + "ResourceStatusPhysicalHostTopology", "ResourceStatusScheduling", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", @@ -11433,6 +11441,47 @@ class AllocationAggregateReservationReservedResourceInfoAccelerator(proto.Messag ) +class AllocationReservationSharingPolicy(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + service_share_type (str): + Sharing config for all Google Cloud services. + Check the ServiceShareType enum for the list of + possible values. + + This field is a member of `oneof`_ ``_service_share_type``. + """ + + class ServiceShareType(proto.Enum): + r"""Sharing config for all Google Cloud services. + + Values: + UNDEFINED_SERVICE_SHARE_TYPE (0): + A value indicating that the enum field is not + set. + ALLOW_ALL (475536235): + Allow all Google Cloud managed services to + share reservations. + DISALLOW_ALL (277786301): + [Default] Disallow sharing with all Google Cloud services. + SERVICE_SHARE_TYPE_UNSPECIFIED (279057148): + No description available. + """ + UNDEFINED_SERVICE_SHARE_TYPE = 0 + ALLOW_ALL = 475536235 + DISALLOW_ALL = 277786301 + SERVICE_SHARE_TYPE_UNSPECIFIED = 279057148 + + service_share_type: str = proto.Field( + proto.STRING, + number=514508644, + optional=True, + ) + + class AllocationResourceStatus(proto.Message): r"""[Output Only] Contains output only fields. @@ -11466,6 +11515,9 @@ class AllocationResourceStatusSpecificSKUAllocation(proto.Message): reservation properties. This field is a member of `oneof`_ ``_source_instance_template_id``. + utilizations (MutableMapping[str, int]): + Per service utilization breakdown. The Key is + the Google Cloud managed service name. """ source_instance_template_id: str = proto.Field( @@ -11473,6 +11525,11 @@ class AllocationResourceStatusSpecificSKUAllocation(proto.Message): number=111196154, optional=True, ) + utilizations: MutableMapping[str, int] = proto.MapField( + proto.STRING, + proto.INT64, + number=402495121, + ) class AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk( @@ -14096,6 +14153,9 @@ class Backend(proto.Message): serverless NEGs, and PSC NEGs. This field is a member of `oneof`_ ``_capacity_scaler``. + custom_metrics (MutableSequence[google.cloud.compute_v1.types.BackendCustomMetric]): + List of custom metrics that are used for CUSTOM_METRICS + BalancingMode. description (str): An optional description of this resource. Provide this property when you create the @@ -14209,6 +14269,8 @@ class BalancingMode(proto.Enum): CONNECTION (246311646): Balance based on the number of simultaneous connections. + CUSTOM_METRICS (331575765): + Based on custom defined and reported metrics. RATE (2508000): Balance based on requests per second (RPS). UTILIZATION (157008386): @@ -14216,6 +14278,7 @@ class BalancingMode(proto.Enum): """ UNDEFINED_BALANCING_MODE = 0 CONNECTION = 246311646 + CUSTOM_METRICS = 331575765 RATE = 2508000 UTILIZATION = 157008386 @@ -14256,6 +14319,11 @@ class Preference(proto.Enum): number=315958157, optional=True, ) + custom_metrics: MutableSequence["BackendCustomMetric"] = proto.RepeatedField( + proto.MESSAGE, + number=429453813, + message="BackendCustomMetric", + ) description: str = proto.Field( proto.STRING, number=422937596, @@ -14924,6 +14992,57 @@ class BackendBucketUsedBy(proto.Message): ) +class BackendCustomMetric(proto.Message): + r"""Custom Metrics are used for CUSTOM_METRICS balancing_mode. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + dry_run (bool): + If true, the metric data is collected and + reported to Cloud Monitoring, but is not used + for load balancing. + + This field is a member of `oneof`_ ``_dry_run``. + max_utilization (float): + Optional parameter to define a target utilization for the + Custom Metrics balancing mode. The valid range is [0.0, + 1.0]. + + This field is a member of `oneof`_ ``_max_utilization``. + name (str): + Name of a custom utilization signal. The name must be 1-64 + characters long and match the regular expression + `a-z <[-_.a-z0-9]*[a-z0-9]>`__? which means the first + character must be a lowercase letter, and all following + characters must be a dash, period, underscore, lowercase + letter, or digit, except the last character, which cannot be + a dash, period, or underscore. For usage guidelines, see + Custom Metrics balancing mode. This field can only be used + for a global or regional backend service with the + loadBalancingScheme set to EXTERNAL_MANAGED, + INTERNAL_MANAGED INTERNAL_SELF_MANAGED. + + This field is a member of `oneof`_ ``_name``. + """ + + dry_run: bool = proto.Field( + proto.BOOL, + number=323854839, + optional=True, + ) + max_utilization: float = proto.Field( + proto.FLOAT, + number=148192199, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + + class BackendService(proto.Message): r"""Represents a Backend Service resource. A backend service defines how Google Cloud load balancers distribute traffic. The backend service @@ -15006,6 +15125,9 @@ class BackendService(proto.Message): [Output Only] Creation timestamp in RFC3339 text format. This field is a member of `oneof`_ ``_creation_timestamp``. + custom_metrics (MutableSequence[google.cloud.compute_v1.types.BackendServiceCustomMetric]): + List of custom metrics that are used for the + WEIGHTED_ROUND_ROBIN locality_lb_policy. custom_request_headers (MutableSequence[str]): Headers that the load balancer adds to proxied requests. See `Creating custom @@ -15547,6 +15669,14 @@ class LocalityLbPolicy(proto.Enum): either reported a valid weight or had UNAVAILABLE_WEIGHT. Otherwise, Load Balancing remains equal-weight. This option is only supported in Network Load Balancing. + WEIGHTED_ROUND_ROBIN (5584977): + Per-endpoint weighted round-robin Load Balancing using + weights computed from Backend reported Custom Metrics. If + set, the Backend Service responses are expected to contain + non-standard HTTP response header field + X-Endpoint-Load-Metrics. The reported metrics to use for + computing the weights are specified via the + backends[].customMetrics fields. """ UNDEFINED_LOCALITY_LB_POLICY = 0 INVALID_LB_POLICY = 323318707 @@ -15557,6 +15687,7 @@ class LocalityLbPolicy(proto.Enum): RING_HASH = 432795069 ROUND_ROBIN = 153895801 WEIGHTED_MAGLEV = 254930962 + WEIGHTED_ROUND_ROBIN = 5584977 class Protocol(proto.Enum): r"""The protocol this BackendService uses to communicate with @@ -15723,6 +15854,11 @@ class SessionAffinity(proto.Enum): number=30525366, optional=True, ) + custom_metrics: MutableSequence["BackendServiceCustomMetric"] = proto.RepeatedField( + proto.MESSAGE, + number=429453813, + message="BackendServiceCustomMetric", + ) custom_request_headers: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=27977992, @@ -16465,6 +16601,45 @@ class TrackingMode(proto.Enum): ) +class BackendServiceCustomMetric(proto.Message): + r"""Custom Metrics are used for WEIGHTED_ROUND_ROBIN locality_lb_policy. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + dry_run (bool): + If true, the metric data is not used for load + balancing. + + This field is a member of `oneof`_ ``_dry_run``. + name (str): + Name of a custom utilization signal. The name must be 1-64 + characters long and match the regular expression + `a-z <[-_.a-z0-9]*[a-z0-9]>`__? which means the first + character must be a lowercase letter, and all following + characters must be a dash, period, underscore, lowercase + letter, or digit, except the last character, which cannot be + a dash, period, or underscore. For usage guidelines, see + Custom Metrics balancing mode. This field can only be used + for a global or regional backend service with the + loadBalancingScheme set to EXTERNAL_MANAGED, + INTERNAL_MANAGED INTERNAL_SELF_MANAGED. + + This field is a member of `oneof`_ ``_name``. + """ + + dry_run: bool = proto.Field( + proto.BOOL, + number=323854839, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + + class BackendServiceFailoverPolicy(proto.Message): r"""For load balancers that have configurable failover: `Internal passthrough Network Load @@ -16962,6 +17137,14 @@ class Name(proto.Enum): either reported a valid weight or had UNAVAILABLE_WEIGHT. Otherwise, Load Balancing remains equal-weight. This option is only supported in Network Load Balancing. + WEIGHTED_ROUND_ROBIN (5584977): + Per-endpoint weighted round-robin Load Balancing using + weights computed from Backend reported Custom Metrics. If + set, the Backend Service responses are expected to contain + non-standard HTTP response header field + X-Endpoint-Load-Metrics. The reported metrics to use for + computing the weights are specified via the + backends[].customMetrics fields. """ UNDEFINED_NAME = 0 INVALID_LB_POLICY = 323318707 @@ -16972,6 +17155,7 @@ class Name(proto.Enum): RING_HASH = 432795069 ROUND_ROBIN = 153895801 WEIGHTED_MAGLEV = 254930962 + WEIGHTED_ROUND_ROBIN = 5584977 name: str = proto.Field( proto.STRING, @@ -19145,6 +19329,8 @@ class Type(proto.Enum): No description available. MEMORY_OPTIMIZED_M3 (276301372): No description available. + MEMORY_OPTIMIZED_M4 (276301373): + No description available. MEMORY_OPTIMIZED_X4_16TB (183089120): No description available. MEMORY_OPTIMIZED_X4_24TB (183116989): @@ -19180,6 +19366,7 @@ class Type(proto.Enum): GRAPHICS_OPTIMIZED = 68500563 MEMORY_OPTIMIZED = 281753417 MEMORY_OPTIMIZED_M3 = 276301372 + MEMORY_OPTIMIZED_M4 = 276301373 MEMORY_OPTIMIZED_X4_16TB = 183089120 MEMORY_OPTIMIZED_X4_24TB = 183116989 MEMORY_OPTIMIZED_X4_32TB = 183144858 @@ -44018,6 +44205,11 @@ class InstanceGroupManager(proto.Message): instance group resides (for regional resources). This field is a member of `oneof`_ ``_region``. + resource_policies (google.cloud.compute_v1.types.InstanceGroupManagerResourcePolicies): + Resource policies for this managed instance + group. + + This field is a member of `oneof`_ ``_resource_policies``. satisfies_pzi (bool): [Output Only] Reserved for future use. @@ -44226,6 +44418,12 @@ class ListManagedInstancesResults(proto.Enum): number=138946292, optional=True, ) + resource_policies: "InstanceGroupManagerResourcePolicies" = proto.Field( + proto.MESSAGE, + number=22220385, + optional=True, + message="InstanceGroupManagerResourcePolicies", + ) satisfies_pzi: bool = proto.Field( proto.BOOL, number=480964257, @@ -45145,6 +45343,33 @@ def raw_page(self): ) +class InstanceGroupManagerResourcePolicies(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + workload_policy (str): + The URL of the workload policy that is + specified for this managed instance group. It + can be a full or partial URL. For example, the + following are all valid URLs to a workload + policy: - + https://www.googleapis.com/compute/v1/projects/project/regions/region + /resourcePolicies/resourcePolicy - + projects/project/regions/region/resourcePolicies/resourcePolicy + - regions/region/resourcePolicies/resourcePolicy + + This field is a member of `oneof`_ ``_workload_policy``. + """ + + workload_policy: str = proto.Field( + proto.STRING, + number=114721530, + optional=True, + ) + + class InstanceGroupManagerStandbyPolicy(proto.Message): r""" @@ -47905,6 +48130,106 @@ class InstancesRemoveResourcePoliciesRequest(proto.Message): ) +class InstancesReportHostAsFaultyRequest(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disruption_schedule (str): + The disruption schedule for the VM. Default + to IMMEDIATE. Check the DisruptionSchedule enum + for the list of possible values. + + This field is a member of `oneof`_ ``_disruption_schedule``. + fault_reasons (MutableSequence[google.cloud.compute_v1.types.InstancesReportHostAsFaultyRequestFaultReason]): + + """ + + class DisruptionSchedule(proto.Enum): + r"""The disruption schedule for the VM. Default to IMMEDIATE. + + Values: + UNDEFINED_DISRUPTION_SCHEDULE (0): + A value indicating that the enum field is not + set. + DISRUPTION_SCHEDULE_UNSPECIFIED (332543835): + Not used. Required as per aip/126. + FUTURE (474513859): + Delay disruption for caller control. Will be + default soon. + IMMEDIATE (152881041): + Default value. Disrupt the VM immediately. + """ + UNDEFINED_DISRUPTION_SCHEDULE = 0 + DISRUPTION_SCHEDULE_UNSPECIFIED = 332543835 + FUTURE = 474513859 + IMMEDIATE = 152881041 + + disruption_schedule: str = proto.Field( + proto.STRING, + number=95871619, + optional=True, + ) + fault_reasons: MutableSequence[ + "InstancesReportHostAsFaultyRequestFaultReason" + ] = proto.RepeatedField( + proto.MESSAGE, + number=168056210, + message="InstancesReportHostAsFaultyRequestFaultReason", + ) + + +class InstancesReportHostAsFaultyRequestFaultReason(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + behavior (str): + Check the Behavior enum for the list of + possible values. + + This field is a member of `oneof`_ ``_behavior``. + description (str): + + This field is a member of `oneof`_ ``_description``. + """ + + class Behavior(proto.Enum): + r""" + + Values: + UNDEFINED_BEHAVIOR (0): + A value indicating that the enum field is not + set. + BEHAVIOR_UNSPECIFIED (85734570): + Public reportable behaviors + PERFORMANCE (135701520): + No description available. + SILENT_DATA_CORRUPTION (111360678): + No description available. + UNRECOVERABLE_GPU_ERROR (363710747): + No description available. + """ + UNDEFINED_BEHAVIOR = 0 + BEHAVIOR_UNSPECIFIED = 85734570 + PERFORMANCE = 135701520 + SILENT_DATA_CORRUPTION = 111360678 + UNRECOVERABLE_GPU_ERROR = 363710747 + + behavior: str = proto.Field( + proto.STRING, + number=437170770, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + + class InstancesScopedList(proto.Message): r""" @@ -82310,10 +82635,15 @@ class Mode(proto.Enum): The public delegated prefix is used for creating forwarding rules only. Such prefixes cannot set publicDelegatedSubPrefixes. + EXTERNAL_IPV6_SUBNETWORK_CREATION (61198284): + The public delegated prefix is used for + creating dual-mode subnetworks only. Such + prefixes cannot set publicDelegatedSubPrefixes. """ UNDEFINED_MODE = 0 DELEGATION = 264149288 EXTERNAL_IPV6_FORWARDING_RULE_CREATION = 398684356 + EXTERNAL_IPV6_SUBNETWORK_CREATION = 61198284 class Status(proto.Enum): r"""[Output Only] The status of the public delegated prefix, which can @@ -82665,10 +82995,15 @@ class Mode(proto.Enum): The public delegated prefix is used for creating forwarding rules only. Such prefixes cannot set publicDelegatedSubPrefixes. + EXTERNAL_IPV6_SUBNETWORK_CREATION (61198284): + The public delegated prefix is used for + creating dual-mode subnetworks only. Such + prefixes cannot set publicDelegatedSubPrefixes. """ UNDEFINED_MODE = 0 DELEGATION = 264149288 EXTERNAL_IPV6_FORWARDING_RULE_CREATION = 398684356 + EXTERNAL_IPV6_SUBNETWORK_CREATION = 61198284 class Status(proto.Enum): r"""[Output Only] The status of the sub public delegated prefix. @@ -86276,6 +86611,66 @@ class RemoveRuleSecurityPolicyRequest(proto.Message): ) +class ReportHostAsFaultyInstanceRequest(proto.Message): + r"""A request message for Instances.ReportHostAsFaulty. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance (str): + Name of the instance scoping this request. + instances_report_host_as_faulty_request_resource (google.cloud.compute_v1.types.InstancesReportHostAsFaultyRequest): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. For example, consider a situation + where you make an initial request and the + request times out. If you make the request again + with the same request ID, the server can check + if original operation with the same request ID + was received, and if so, will ignore the second + request. This prevents clients from accidentally + creating duplicate commitments. The request ID + must be a valid UUID with the exception that + zero UUID is not supported ( + 00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + zone (str): + The name of the zone for this request. + """ + + instance: str = proto.Field( + proto.STRING, + number=18257045, + ) + instances_report_host_as_faulty_request_resource: "InstancesReportHostAsFaultyRequest" = proto.Field( + proto.MESSAGE, + number=494094886, + message="InstancesReportHostAsFaultyRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class RequestMirrorPolicy(proto.Message): r"""A policy that specifies how requests intended for the route's backends are shadowed to a separate mirrored backend service. @@ -86358,6 +86753,12 @@ class Reservation(proto.Message): digit, except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + reservation_sharing_policy (google.cloud.compute_v1.types.AllocationReservationSharingPolicy): + Specify the reservation sharing policy. If + unspecified, the reservation will not be shared + with Google Cloud managed services. + + This field is a member of `oneof`_ ``_reservation_sharing_policy``. resource_policies (MutableMapping[str, str]): Resource policies to be added to this reservation. The key is defined by user, and the @@ -86481,6 +86882,12 @@ class Status(proto.Enum): number=3373707, optional=True, ) + reservation_sharing_policy: "AllocationReservationSharingPolicy" = proto.Field( + proto.MESSAGE, + number=205970120, + optional=True, + message="AllocationReservationSharingPolicy", + ) resource_policies: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -88245,6 +88652,13 @@ class ResourceStatus(proto.Message): blockId/subBlockId/hostId. This field is a member of `oneof`_ ``_physical_host``. + physical_host_topology (google.cloud.compute_v1.types.ResourceStatusPhysicalHostTopology): + [Output Only] A series of fields containing the global name + of the Compute Engine cluster, as well as the ID of the + block, sub-block, and host on which the running instance is + located. + + This field is a member of `oneof`_ ``_physical_host_topology``. scheduling (google.cloud.compute_v1.types.ResourceStatusScheduling): This field is a member of `oneof`_ ``_scheduling``. @@ -88258,6 +88672,12 @@ class ResourceStatus(proto.Message): number=464370704, optional=True, ) + physical_host_topology: "ResourceStatusPhysicalHostTopology" = proto.Field( + proto.MESSAGE, + number=390842814, + optional=True, + message="ResourceStatusPhysicalHostTopology", + ) scheduling: "ResourceStatusScheduling" = proto.Field( proto.MESSAGE, number=386688404, @@ -88272,6 +88692,62 @@ class ResourceStatus(proto.Message): ) +class ResourceStatusPhysicalHostTopology(proto.Message): + r"""Represents the physical host topology of the host on which + the VM is running. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + block (str): + [Output Only] The ID of the block in which the running + instance is located. Instances within the same block + experience low network latency. + + This field is a member of `oneof`_ ``_block``. + cluster (str): + [Output Only] The global name of the Compute Engine cluster + where the running instance is located. + + This field is a member of `oneof`_ ``_cluster``. + host (str): + [Output Only] The ID of the host on which the running + instance is located. Instances on the same host experience + the lowest possible network latency. + + This field is a member of `oneof`_ ``_host``. + subblock (str): + [Output Only] The ID of the sub-block in which the running + instance is located. Instances in the same sub-block + experience lower network latency than instances in the same + block. + + This field is a member of `oneof`_ ``_subblock``. + """ + + block: str = proto.Field( + proto.STRING, + number=93832333, + optional=True, + ) + cluster: str = proto.Field( + proto.STRING, + number=335221242, + optional=True, + ) + host: str = proto.Field( + proto.STRING, + number=3208616, + optional=True, + ) + subblock: str = proto.Field( + proto.STRING, + number=70446669, + optional=True, + ) + + class ResourceStatusScheduling(proto.Message): r""" @@ -92395,6 +92871,9 @@ class ProvisioningModel(proto.Enum): UNDEFINED_PROVISIONING_MODEL (0): A value indicating that the enum field is not set. + RESERVATION_BOUND (293538571): + Bound to the lifecycle of the reservation in + which it is provisioned. SPOT (2552066): Heavily discounted, no guaranteed runtime. STANDARD (484642493): @@ -92402,6 +92881,7 @@ class ProvisioningModel(proto.Enum): runtime, no discounts. """ UNDEFINED_PROVISIONING_MODEL = 0 + RESERVATION_BOUND = 293538571 SPOT = 2552066 STANDARD = 484642493 @@ -104667,6 +105147,20 @@ class Subnetwork(proto.Message): expandIpCidrRange. This field is a member of `oneof`_ ``_ip_cidr_range``. + ip_collection (str): + Reference to the source of IP, like a PublicDelegatedPrefix + (PDP) for BYOIP. The PDP must be a sub-PDP in + EXTERNAL_IPV6_SUBNETWORK_CREATION mode. Use one of the + following formats to specify a sub-PDP when creating a dual + stack subnetwork with external access using BYOIP: - Full + resource URL, as in + https://www.googleapis.com/compute/v1/projects/projectId/regions/region + /publicDelegatedPrefixes/sub-pdp-name - Partial URL, as in - + projects/projectId/regions/region/publicDelegatedPrefixes/ + sub-pdp-name - + regions/region/publicDelegatedPrefixes/sub-pdp-name + + This field is a member of `oneof`_ ``_ip_collection``. ipv6_access_type (str): The access type of IPv6 address this subnet holds. It's immutable and can only be specified during creation or the @@ -104679,6 +105173,20 @@ class Subnetwork(proto.Message): [Output Only] This field is for internal use. This field is a member of `oneof`_ ``_ipv6_cidr_range``. + ipv6_gce_endpoint (str): + [Output Only] Possible endpoints of this subnetwork. It can + be one of the following: - VM_ONLY: The subnetwork can be + used for creating instances and IPv6 addresses with VM + endpoint type. Such a subnetwork gets external IPv6 ranges + from a public delegated prefix and cannot be used to create + NetLb. - VM_AND_FR: The subnetwork can be used for creating + both VM instances and Forwarding Rules. It can also be used + to reserve IPv6 addresses with both VM and FR endpoint + types. Such a subnetwork gets its IPv6 range from Google IP + Pool directly. Check the Ipv6GceEndpoint enum for the list + of possible values. + + This field is a member of `oneof`_ ``_ipv6_gce_endpoint``. kind (str): [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources. @@ -104827,6 +105335,30 @@ class Ipv6AccessType(proto.Enum): INTERNAL = 279295677 UNSPECIFIED_IPV6_ACCESS_TYPE = 313080613 + class Ipv6GceEndpoint(proto.Enum): + r"""[Output Only] Possible endpoints of this subnetwork. It can be one + of the following: - VM_ONLY: The subnetwork can be used for creating + instances and IPv6 addresses with VM endpoint type. Such a + subnetwork gets external IPv6 ranges from a public delegated prefix + and cannot be used to create NetLb. - VM_AND_FR: The subnetwork can + be used for creating both VM instances and Forwarding Rules. It can + also be used to reserve IPv6 addresses with both VM and FR endpoint + types. Such a subnetwork gets its IPv6 range from Google IP Pool + directly. + + Values: + UNDEFINED_IPV6_GCE_ENDPOINT (0): + A value indicating that the enum field is not + set. + VM_AND_FR (41830108): + No description available. + VM_ONLY (236773428): + No description available. + """ + UNDEFINED_IPV6_GCE_ENDPOINT = 0 + VM_AND_FR = 41830108 + VM_ONLY = 236773428 + class PrivateIpv6GoogleAccess(proto.Enum): r"""This field is for internal use. This field can be both set at resource creation time and updated using patch. @@ -105026,6 +105558,11 @@ class State(proto.Enum): number=98117322, optional=True, ) + ip_collection: str = proto.Field( + proto.STRING, + number=176818358, + optional=True, + ) ipv6_access_type: str = proto.Field( proto.STRING, number=504658653, @@ -105036,6 +105573,11 @@ class State(proto.Enum): number=273141258, optional=True, ) + ipv6_gce_endpoint: str = proto.Field( + proto.STRING, + number=320382307, + optional=True, + ) kind: str = proto.Field( proto.STRING, number=3292052, @@ -106826,11 +107368,15 @@ class TargetHttpsProxy(proto.Message): serverTlsPolicy only applies to a global TargetHttpsProxy attached to globalForwardingRules with the loadBalancingScheme set to INTERNAL_SELF_MANAGED or EXTERNAL - or EXTERNAL_MANAGED. For details which ServerTlsPolicy - resources are accepted with INTERNAL_SELF_MANAGED and which - with EXTERNAL, EXTERNAL_MANAGED loadBalancingScheme consult - ServerTlsPolicy documentation. If left blank, communications - are not encrypted. + or EXTERNAL_MANAGED or INTERNAL_MANAGED. It also applies to + a regional TargetHttpsProxy attached to regional + forwardingRules with the loadBalancingScheme set to + EXTERNAL_MANAGED or INTERNAL_MANAGED. For details which + ServerTlsPolicy resources are accepted with + INTERNAL_SELF_MANAGED and which with EXTERNAL, + INTERNAL_MANAGED, EXTERNAL_MANAGED loadBalancingScheme + consult ServerTlsPolicy documentation. If left blank, + communications are not encrypted. This field is a member of `oneof`_ ``_server_tls_policy``. ssl_certificates (MutableSequence[str]): diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instances_report_host_as_faulty_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instances_report_host_as_faulty_sync.py new file mode 100644 index 000000000000..61664b7a086d --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_instances_report_host_as_faulty_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ReportHostAsFaulty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-compute + + +# [START compute_v1_generated_Instances_ReportHostAsFaulty_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import compute_v1 + + +def sample_report_host_as_faulty(): + # Create a client + client = compute_v1.InstancesClient() + + # Initialize request argument(s) + request = compute_v1.ReportHostAsFaultyInstanceRequest( + instance="instance_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.report_host_as_faulty(request=request) + + # Handle the response + print(response) + +# [END compute_v1_generated_Instances_ReportHostAsFaulty_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json index c0b06c52ec63..78a7aafebe90 100644 --- a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json +++ b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json @@ -19347,6 +19347,98 @@ ], "title": "compute_v1_generated_instances_remove_resource_policies_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.InstancesClient", + "shortName": "InstancesClient" + }, + "fullName": "google.cloud.compute_v1.InstancesClient.report_host_as_faulty", + "method": { + "fullName": "google.cloud.compute.v1.Instances.ReportHostAsFaulty", + "service": { + "fullName": "google.cloud.compute.v1.Instances", + "shortName": "Instances" + }, + "shortName": "ReportHostAsFaulty" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ReportHostAsFaultyInstanceRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "instance", + "type": "str" + }, + { + "name": "instances_report_host_as_faulty_request_resource", + "type": "google.cloud.compute_v1.types.InstancesReportHostAsFaultyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "report_host_as_faulty" + }, + "description": "Sample for ReportHostAsFaulty", + "file": "compute_v1_generated_instances_report_host_as_faulty_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Instances_ReportHostAsFaulty_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_instances_report_host_as_faulty_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py b/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py index c3936f054b3c..d73c935168d8 100644 --- a/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py +++ b/packages/google-cloud-compute/scripts/fixup_compute_v1_keywords.py @@ -135,6 +135,7 @@ class computeCallTransformer(cst.CSTTransformer): 'remove_peering': ('network', 'networks_remove_peering_request_resource', 'project', 'request_id', ), 'remove_resource_policies': ('disk', 'disks_remove_resource_policies_request_resource', 'project', 'zone', 'request_id', ), 'remove_rule': ('firewall_policy', 'priority', 'request_id', ), + 'report_host_as_faulty': ('instance', 'instances_report_host_as_faulty_request_resource', 'project', 'zone', 'request_id', ), 'reset': ('instance', 'project', 'zone', 'request_id', ), 'resize': ('disk', 'disks_resize_request_resource', 'project', 'zone', 'request_id', ), 'resume': ('instance', 'project', 'zone', 'request_id', ), diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py index 4a229f6d7de6..6f568ed9e62d 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py @@ -7430,6 +7430,9 @@ def test_insert_rest_call_success(request_type): { "balancing_mode": "balancing_mode_value", "capacity_scaler": 0.1575, + "custom_metrics": [ + {"dry_run": True, "max_utilization": 0.1633, "name": "name_value"} + ], "description": "description_value", "failover": True, "group": "group_value", @@ -7505,6 +7508,7 @@ def test_insert_rest_call_success(request_type): "minimum_ring_size": 1829, }, "creation_timestamp": "creation_timestamp_value", + "custom_metrics": [{"dry_run": True, "name": "name_value"}], "custom_request_headers": [ "custom_request_headers_value1", "custom_request_headers_value2", @@ -8104,6 +8108,9 @@ def test_patch_rest_call_success(request_type): { "balancing_mode": "balancing_mode_value", "capacity_scaler": 0.1575, + "custom_metrics": [ + {"dry_run": True, "max_utilization": 0.1633, "name": "name_value"} + ], "description": "description_value", "failover": True, "group": "group_value", @@ -8179,6 +8186,7 @@ def test_patch_rest_call_success(request_type): "minimum_ring_size": 1829, }, "creation_timestamp": "creation_timestamp_value", + "custom_metrics": [{"dry_run": True, "name": "name_value"}], "custom_request_headers": [ "custom_request_headers_value1", "custom_request_headers_value2", @@ -9463,6 +9471,9 @@ def test_update_rest_call_success(request_type): { "balancing_mode": "balancing_mode_value", "capacity_scaler": 0.1575, + "custom_metrics": [ + {"dry_run": True, "max_utilization": 0.1633, "name": "name_value"} + ], "description": "description_value", "failover": True, "group": "group_value", @@ -9538,6 +9549,7 @@ def test_update_rest_call_success(request_type): "minimum_ring_size": 1829, }, "creation_timestamp": "creation_timestamp_value", + "custom_metrics": [{"dry_run": True, "name": "name_value"}], "custom_request_headers": [ "custom_request_headers_value1", "custom_request_headers_value2", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py index 487694590718..210e72cd51b4 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py @@ -12557,6 +12557,7 @@ def test_insert_rest_call_success(request_type): "name": "name_value", "named_ports": [{"name": "name_value", "port": 453}], "region": "region_value", + "resource_policies": {"workload_policy": "workload_policy_value"}, "satisfies_pzi": True, "satisfies_pzs": True, "self_link": "self_link_value", @@ -13453,6 +13454,7 @@ def test_patch_rest_call_success(request_type): "name": "name_value", "named_ports": [{"name": "name_value", "port": 453}], "region": "region_value", + "resource_policies": {"workload_policy": "workload_policy_value"}, "satisfies_pzi": True, "satisfies_pzs": True, "self_link": "self_link_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py index 0f766e1861e6..85f7b6420363 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py @@ -7734,6 +7734,450 @@ def test_remove_resource_policies_unary_rest_flattened_error(transport: str = "r ) +def test_report_host_as_faulty_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.report_host_as_faulty + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.report_host_as_faulty + ] = mock_rpc + + request = {} + client.report_host_as_faulty(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.report_host_as_faulty(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_report_host_as_faulty_rest_required_fields( + request_type=compute.ReportHostAsFaultyInstanceRequest, +): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["instance"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_host_as_faulty._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instance"] = "instance_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_host_as_faulty._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.report_host_as_faulty(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_report_host_as_faulty_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.report_host_as_faulty._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instance", + "instancesReportHostAsFaultyRequestResource", + "project", + "zone", + ) + ) + ) + + +def test_report_host_as_faulty_rest_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "instance": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instance="instance_value", + instances_report_host_as_faulty_request_resource=compute.InstancesReportHostAsFaultyRequest( + disruption_schedule="disruption_schedule_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.report_host_as_faulty(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/reportHostAsFaulty" + % client.transport._host, + args[1], + ) + + +def test_report_host_as_faulty_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.report_host_as_faulty( + compute.ReportHostAsFaultyInstanceRequest(), + project="project_value", + zone="zone_value", + instance="instance_value", + instances_report_host_as_faulty_request_resource=compute.InstancesReportHostAsFaultyRequest( + disruption_schedule="disruption_schedule_value" + ), + ) + + +def test_report_host_as_faulty_unary_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.report_host_as_faulty + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.report_host_as_faulty + ] = mock_rpc + + request = {} + client.report_host_as_faulty_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.report_host_as_faulty_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_report_host_as_faulty_unary_rest_required_fields( + request_type=compute.ReportHostAsFaultyInstanceRequest, +): + transport_class = transports.InstancesRestTransport + + request_init = {} + request_init["instance"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_host_as_faulty._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instance"] = "instance_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).report_host_as_faulty._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.report_host_as_faulty_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_report_host_as_faulty_unary_rest_unset_required_fields(): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.report_host_as_faulty._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "instance", + "instancesReportHostAsFaultyRequestResource", + "project", + "zone", + ) + ) + ) + + +def test_report_host_as_faulty_unary_rest_flattened(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "instance": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + instance="instance_value", + instances_report_host_as_faulty_request_resource=compute.InstancesReportHostAsFaultyRequest( + disruption_schedule="disruption_schedule_value" + ), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.report_host_as_faulty_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/v1/projects/{project}/zones/{zone}/instances/{instance}/reportHostAsFaulty" + % client.transport._host, + args[1], + ) + + +def test_report_host_as_faulty_unary_rest_flattened_error(transport: str = "rest"): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.report_host_as_faulty_unary( + compute.ReportHostAsFaultyInstanceRequest(), + project="project_value", + zone="zone_value", + instance="instance_value", + instances_report_host_as_faulty_request_resource=compute.InstancesReportHostAsFaultyRequest( + disruption_schedule="disruption_schedule_value" + ), + ) + + def test_reset_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -22573,6 +23017,12 @@ def test_insert_rest_call_success(request_type): "resource_policies": ["resource_policies_value1", "resource_policies_value2"], "resource_status": { "physical_host": "physical_host_value", + "physical_host_topology": { + "block": "block_value", + "cluster": "cluster_value", + "host": "host_value", + "subblock": "subblock_value", + }, "scheduling": {"availability_domain": 2002}, "upcoming_maintenance": { "can_reschedule": True, @@ -23501,6 +23951,261 @@ def test_remove_resource_policies_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_report_host_as_faulty_rest_bad_request( + request_type=compute.ReportHostAsFaultyInstanceRequest, +): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "instance": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.report_host_as_faulty(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ReportHostAsFaultyInstanceRequest, + dict, + ], +) +def test_report_host_as_faulty_rest_call_success(request_type): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "instance": "sample3"} + request_init["instances_report_host_as_faulty_request_resource"] = { + "disruption_schedule": "disruption_schedule_value", + "fault_reasons": [ + {"behavior": "behavior_value", "description": "description_value"} + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.ReportHostAsFaultyInstanceRequest.meta.fields[ + "instances_report_host_as_faulty_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "instances_report_host_as_faulty_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, + len( + request_init[ + "instances_report_host_as_faulty_request_resource" + ][field] + ), + ): + del request_init[ + "instances_report_host_as_faulty_request_resource" + ][field][i][subfield] + else: + del request_init["instances_report_host_as_faulty_request_resource"][ + field + ][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.report_host_as_faulty(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_report_host_as_faulty_rest_interceptors(null_interceptor): + transport = transports.InstancesRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.InstancesRestInterceptor(), + ) + client = InstancesClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.InstancesRestInterceptor, "post_report_host_as_faulty" + ) as post, mock.patch.object( + transports.InstancesRestInterceptor, "post_report_host_as_faulty_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.InstancesRestInterceptor, "pre_report_host_as_faulty" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ReportHostAsFaultyInstanceRequest.pb( + compute.ReportHostAsFaultyInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.ReportHostAsFaultyInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.report_host_as_faulty( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_reset_rest_bad_request(request_type=compute.ResetInstanceRequest): client = InstancesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -28585,6 +29290,12 @@ def test_update_rest_call_success(request_type): "resource_policies": ["resource_policies_value1", "resource_policies_value2"], "resource_status": { "physical_host": "physical_host_value", + "physical_host_topology": { + "block": "block_value", + "cluster": "cluster_value", + "host": "host_value", + "subblock": "subblock_value", + }, "scheduling": {"availability_domain": 2002}, "upcoming_maintenance": { "can_reschedule": True, @@ -30272,6 +30983,28 @@ def test_remove_resource_policies_unary_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_report_host_as_faulty_unary_empty_call_rest(): + client = InstancesClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.report_host_as_faulty), "__call__" + ) as call: + client.report_host_as_faulty_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ReportHostAsFaultyInstanceRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_reset_unary_empty_call_rest(): @@ -30904,6 +31637,7 @@ def test_instances_base_transport(): "list_referrers", "perform_maintenance", "remove_resource_policies", + "report_host_as_faulty", "reset", "resume", "send_diagnostic_interrupt", @@ -31129,6 +31863,9 @@ def test_instances_client_transport_session_collision(transport_name): session1 = client1.transport.remove_resource_policies._session session2 = client2.transport.remove_resource_policies._session assert session1 != session2 + session1 = client1.transport.report_host_as_faulty._session + session2 = client2.transport.report_host_as_faulty._session + assert session1 != session2 session1 = client1.transport.reset._session session2 = client2.transport.reset._session assert session1 != session2 diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py index 8f28aa7c667a..6e575c048f3a 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py @@ -5555,6 +5555,9 @@ def test_insert_rest_call_success(request_type): { "balancing_mode": "balancing_mode_value", "capacity_scaler": 0.1575, + "custom_metrics": [ + {"dry_run": True, "max_utilization": 0.1633, "name": "name_value"} + ], "description": "description_value", "failover": True, "group": "group_value", @@ -5630,6 +5633,7 @@ def test_insert_rest_call_success(request_type): "minimum_ring_size": 1829, }, "creation_timestamp": "creation_timestamp_value", + "custom_metrics": [{"dry_run": True, "name": "name_value"}], "custom_request_headers": [ "custom_request_headers_value1", "custom_request_headers_value2", @@ -6238,6 +6242,9 @@ def test_patch_rest_call_success(request_type): { "balancing_mode": "balancing_mode_value", "capacity_scaler": 0.1575, + "custom_metrics": [ + {"dry_run": True, "max_utilization": 0.1633, "name": "name_value"} + ], "description": "description_value", "failover": True, "group": "group_value", @@ -6313,6 +6320,7 @@ def test_patch_rest_call_success(request_type): "minimum_ring_size": 1829, }, "creation_timestamp": "creation_timestamp_value", + "custom_metrics": [{"dry_run": True, "name": "name_value"}], "custom_request_headers": [ "custom_request_headers_value1", "custom_request_headers_value2", @@ -7368,6 +7376,9 @@ def test_update_rest_call_success(request_type): { "balancing_mode": "balancing_mode_value", "capacity_scaler": 0.1575, + "custom_metrics": [ + {"dry_run": True, "max_utilization": 0.1633, "name": "name_value"} + ], "description": "description_value", "failover": True, "group": "group_value", @@ -7443,6 +7454,7 @@ def test_update_rest_call_success(request_type): "minimum_ring_size": 1829, }, "creation_timestamp": "creation_timestamp_value", + "custom_metrics": [{"dry_run": True, "name": "name_value"}], "custom_request_headers": [ "custom_request_headers_value1", "custom_request_headers_value2", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py index 485220a1da92..95903d618b71 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_commitments.py @@ -3044,10 +3044,14 @@ def test_insert_rest_call_success(request_type): "id": 205, "kind": "kind_value", "name": "name_value", + "reservation_sharing_policy": { + "service_share_type": "service_share_type_value" + }, "resource_policies": {}, "resource_status": { "specific_sku_allocation": { - "source_instance_template_id": "source_instance_template_id_value" + "source_instance_template_id": "source_instance_template_id_value", + "utilizations": {}, } }, "satisfies_pzs": True, @@ -3508,10 +3512,14 @@ def test_update_rest_call_success(request_type): "id": 205, "kind": "kind_value", "name": "name_value", + "reservation_sharing_policy": { + "service_share_type": "service_share_type_value" + }, "resource_policies": {}, "resource_status": { "specific_sku_allocation": { - "source_instance_template_id": "source_instance_template_id_value" + "source_instance_template_id": "source_instance_template_id_value", + "utilizations": {}, } }, "satisfies_pzs": True, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py index c146dd13a86b..b0e6a4806338 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py @@ -12172,6 +12172,7 @@ def test_insert_rest_call_success(request_type): "name": "name_value", "named_ports": [{"name": "name_value", "port": 453}], "region": "region_value", + "resource_policies": {"workload_policy": "workload_policy_value"}, "satisfies_pzi": True, "satisfies_pzs": True, "self_link": "self_link_value", @@ -13083,6 +13084,7 @@ def test_patch_rest_call_success(request_type): "name": "name_value", "named_ports": [{"name": "name_value", "port": 453}], "region": "region_value", + "resource_policies": {"workload_policy": "workload_policy_value"}, "satisfies_pzi": True, "satisfies_pzs": True, "self_link": "self_link_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py index d6bef130dd07..059dac2243a7 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_reservations.py @@ -4807,10 +4807,14 @@ def test_insert_rest_call_success(request_type): "id": 205, "kind": "kind_value", "name": "name_value", + "reservation_sharing_policy": { + "service_share_type": "service_share_type_value" + }, "resource_policies": {}, "resource_status": { "specific_sku_allocation": { - "source_instance_template_id": "source_instance_template_id_value" + "source_instance_template_id": "source_instance_template_id_value", + "utilizations": {}, } }, "satisfies_pzs": True, @@ -5925,10 +5929,14 @@ def test_update_rest_call_success(request_type): "id": 205, "kind": "kind_value", "name": "name_value", + "reservation_sharing_policy": { + "service_share_type": "service_share_type_value" + }, "resource_policies": {}, "resource_status": { "specific_sku_allocation": { - "source_instance_template_id": "source_instance_template_id_value" + "source_instance_template_id": "source_instance_template_id_value", + "utilizations": {}, } }, "satisfies_pzs": True, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py index d834e0d55e97..552a93a591b1 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py @@ -5426,8 +5426,10 @@ def test_get_rest_call_success(request_type): id=205, internal_ipv6_prefix="internal_ipv6_prefix_value", ip_cidr_range="ip_cidr_range_value", + ip_collection="ip_collection_value", ipv6_access_type="ipv6_access_type_value", ipv6_cidr_range="ipv6_cidr_range_value", + ipv6_gce_endpoint="ipv6_gce_endpoint_value", kind="kind_value", name="name_value", network="network_value", @@ -5465,8 +5467,10 @@ def test_get_rest_call_success(request_type): assert response.id == 205 assert response.internal_ipv6_prefix == "internal_ipv6_prefix_value" assert response.ip_cidr_range == "ip_cidr_range_value" + assert response.ip_collection == "ip_collection_value" assert response.ipv6_access_type == "ipv6_access_type_value" assert response.ipv6_cidr_range == "ipv6_cidr_range_value" + assert response.ipv6_gce_endpoint == "ipv6_gce_endpoint_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.network == "network_value" @@ -5719,8 +5723,10 @@ def test_insert_rest_call_success(request_type): "id": 205, "internal_ipv6_prefix": "internal_ipv6_prefix_value", "ip_cidr_range": "ip_cidr_range_value", + "ip_collection": "ip_collection_value", "ipv6_access_type": "ipv6_access_type_value", "ipv6_cidr_range": "ipv6_cidr_range_value", + "ipv6_gce_endpoint": "ipv6_gce_endpoint_value", "kind": "kind_value", "log_config": { "aggregation_interval": "aggregation_interval_value", @@ -6260,8 +6266,10 @@ def test_patch_rest_call_success(request_type): "id": 205, "internal_ipv6_prefix": "internal_ipv6_prefix_value", "ip_cidr_range": "ip_cidr_range_value", + "ip_collection": "ip_collection_value", "ipv6_access_type": "ipv6_access_type_value", "ipv6_cidr_range": "ipv6_cidr_range_value", + "ipv6_gce_endpoint": "ipv6_gce_endpoint_value", "kind": "kind_value", "log_config": { "aggregation_interval": "aggregation_interval_value",