diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr/__init__.py index 5ab4e805a40b..346133baf2bf 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr/__init__.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr/__init__.py @@ -24,6 +24,8 @@ CreateManagementServerRequest, DeleteManagementServerRequest, GetManagementServerRequest, + InitializeServiceRequest, + InitializeServiceResponse, ListManagementServersRequest, ListManagementServersResponse, ManagementServer, @@ -128,6 +130,8 @@ "CreateManagementServerRequest", "DeleteManagementServerRequest", "GetManagementServerRequest", + "InitializeServiceRequest", + "InitializeServiceResponse", "ListManagementServersRequest", "ListManagementServersResponse", "ManagementServer", diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py b/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py index cf5493b86bbc..558c8aab67c5 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.7" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/__init__.py index eddcfa53658f..35f5bc1adad8 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/__init__.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/__init__.py @@ -23,6 +23,8 @@ CreateManagementServerRequest, DeleteManagementServerRequest, GetManagementServerRequest, + InitializeServiceRequest, + InitializeServiceResponse, ListManagementServersRequest, ListManagementServersResponse, ManagementServer, @@ -173,6 +175,8 @@ "GetDataSourceRequest", "GetManagementServerRequest", "GuestOsFeature", + "InitializeServiceRequest", + "InitializeServiceResponse", "InstanceParams", "KeyRevocationActionType", "ListBackupPlanAssociationsRequest", diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_metadata.json b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_metadata.json index 902530688c39..5534a346d83c 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_metadata.json +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_metadata.json @@ -90,6 +90,11 @@ "get_management_server" ] }, + "InitializeService": { + "methods": [ + "initialize_service" + ] + }, "ListBackupPlanAssociations": { "methods": [ "list_backup_plan_associations" @@ -230,6 +235,11 @@ "get_management_server" ] }, + "InitializeService": { + "methods": [ + "initialize_service" + ] + }, "ListBackupPlanAssociations": { "methods": [ "list_backup_plan_associations" @@ -370,6 +380,11 @@ "get_management_server" ] }, + "InitializeService": { + "methods": [ + "initialize_service" + ] + }, "ListBackupPlanAssociations": { "methods": [ "list_backup_plan_associations" diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py index cf5493b86bbc..558c8aab67c5 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.7" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/async_client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/async_client.py index c8870919dd24..c19c93260a4c 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/async_client.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/async_client.py @@ -3153,6 +3153,7 @@ async def sample_create_backup_plan_association(): # Initialize request argument(s) backup_plan_association = backupdr_v1.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" backup_plan_association.resource = "resource_value" backup_plan_association.backup_plan = "backup_plan_value" @@ -3796,6 +3797,108 @@ async def sample_trigger_backup(): # Done; return the response. return response + async def initialize_service( + self, + request: Optional[Union[backupdr.InitializeServiceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Initializes the service related config for a project. + + .. 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 backupdr_v1 + + async def sample_initialize_service(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + ) + + # Make the request + operation = client.initialize_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.InitializeServiceRequest, dict]]): + The request object. Request message for initializing the + service. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1.types.InitializeServiceResponse` + Response message for initializing the service. + + """ + # Create or coerce a protobuf request object. + # - 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, backupdr.InitializeServiceRequest): + request = backupdr.InitializeServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.initialize_service + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupdr.InitializeServiceResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py index fa774032bfe4..7a0407870ceb 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py @@ -3590,6 +3590,7 @@ def sample_create_backup_plan_association(): # Initialize request argument(s) backup_plan_association = backupdr_v1.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" backup_plan_association.resource = "resource_value" backup_plan_association.backup_plan = "backup_plan_value" @@ -4226,6 +4227,106 @@ def sample_trigger_backup(): # Done; return the response. return response + def initialize_service( + self, + request: Optional[Union[backupdr.InitializeServiceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Initializes the service related config for a project. + + .. 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 backupdr_v1 + + def sample_initialize_service(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + ) + + # Make the request + operation = client.initialize_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.InitializeServiceRequest, dict]): + The request object. Request message for initializing the + service. + 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.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1.types.InitializeServiceResponse` + Response message for initializing the service. + + """ + # Create or coerce a protobuf request object. + # - 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, backupdr.InitializeServiceRequest): + request = backupdr.InitializeServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.initialize_service] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupdr.InitializeServiceResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "BackupDRClient": return self diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/base.py index 9b2382573ee9..776ac8fe0b13 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/base.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/base.py @@ -371,6 +371,20 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.initialize_service: gapic_v1.method.wrap_method( + self.initialize_service, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -698,6 +712,15 @@ def trigger_backup( ]: raise NotImplementedError() + @property + def initialize_service( + self, + ) -> Callable[ + [backupdr.InitializeServiceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc.py index e2e13a00be74..e1ba2336e745 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc.py @@ -1089,6 +1089,32 @@ def trigger_backup( ) return self._stubs["trigger_backup"] + @property + def initialize_service( + self, + ) -> Callable[[backupdr.InitializeServiceRequest], operations_pb2.Operation]: + r"""Return a callable for the initialize service method over gRPC. + + Initializes the service related config for a project. + + Returns: + Callable[[~.InitializeServiceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "initialize_service" not in self._stubs: + self._stubs["initialize_service"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/InitializeService", + request_serializer=backupdr.InitializeServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["initialize_service"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc_asyncio.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc_asyncio.py index 80a10bbe29be..8f1fb5520184 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc_asyncio.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc_asyncio.py @@ -1131,6 +1131,34 @@ def trigger_backup( ) return self._stubs["trigger_backup"] + @property + def initialize_service( + self, + ) -> Callable[ + [backupdr.InitializeServiceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the initialize service method over gRPC. + + Initializes the service related config for a project. + + Returns: + Callable[[~.InitializeServiceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "initialize_service" not in self._stubs: + self._stubs["initialize_service"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/InitializeService", + request_serializer=backupdr.InitializeServiceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["initialize_service"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -1368,6 +1396,20 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.initialize_service: self._wrap_method( + self.initialize_service, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest.py index e4db8c8a1cd0..f039c8a00b7b 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest.py @@ -205,6 +205,14 @@ def post_get_management_server(self, response): logging.log(f"Received response: {response}") return response + def pre_initialize_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_initialize_service(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_backup_plan_associations(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -699,6 +707,31 @@ def post_get_management_server( """ return response + def pre_initialize_service( + self, + request: backupdr.InitializeServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupdr.InitializeServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for initialize_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_initialize_service( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for initialize_service + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + def pre_list_backup_plan_associations( self, request: backupplanassociation.ListBackupPlanAssociationsRequest, @@ -3686,6 +3719,156 @@ def __call__( ) return resp + class _InitializeService( + _BaseBackupDRRestTransport._BaseInitializeService, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.InitializeService") + + @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: backupdr.InitializeServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the initialize service method over HTTP. + + Args: + request (~.backupdr.InitializeServiceRequest): + The request object. Request message for initializing the + service. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseInitializeService._get_http_options() + ) + + request, metadata = self._interceptor.pre_initialize_service( + request, metadata + ) + transcoded_request = _BaseBackupDRRestTransport._BaseInitializeService._get_transcoded_request( + http_options, request + ) + + body = _BaseBackupDRRestTransport._BaseInitializeService._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseBackupDRRestTransport._BaseInitializeService._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 = json_format.MessageToJson(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.backupdr_v1.BackupDRClient.InitializeService", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "InitializeService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._InitializeService._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_initialize_service(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.backupdr_v1.BackupDRClient.initialize_service", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "InitializeService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _ListBackupPlanAssociations( _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, BackupDRRestStub ): @@ -5471,6 +5654,14 @@ def get_management_server( # In C++ this would require a dynamic_cast return self._GetManagementServer(self._session, self._host, self._interceptor) # type: ignore + @property + def initialize_service( + self, + ) -> Callable[[backupdr.InitializeServiceRequest], operations_pb2.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._InitializeService(self._session, self._host, self._interceptor) # type: ignore + @property def list_backup_plan_associations( self, diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest_base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest_base.py index d8e87f3e754d..358a1995e71e 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest_base.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest_base.py @@ -902,6 +902,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseInitializeService: + 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": "/v1/{name=projects/*/locations/*/serviceConfig}:initialize", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = backupdr.InitializeServiceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseBackupDRRestTransport._BaseInitializeService._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListBackupPlanAssociations: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/__init__.py index 951186d655ee..8bd452cf0248 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/__init__.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/__init__.py @@ -17,6 +17,8 @@ CreateManagementServerRequest, DeleteManagementServerRequest, GetManagementServerRequest, + InitializeServiceRequest, + InitializeServiceResponse, ListManagementServersRequest, ListManagementServersResponse, ManagementServer, @@ -117,6 +119,8 @@ "CreateManagementServerRequest", "DeleteManagementServerRequest", "GetManagementServerRequest", + "InitializeServiceRequest", + "InitializeServiceResponse", "ListManagementServersRequest", "ListManagementServersResponse", "ManagementServer", diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupdr.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupdr.py index 2cbce001d7d5..4eac794dffeb 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupdr.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupdr.py @@ -34,6 +34,8 @@ "GetManagementServerRequest", "CreateManagementServerRequest", "DeleteManagementServerRequest", + "InitializeServiceRequest", + "InitializeServiceResponse", "OperationMetadata", }, ) @@ -185,9 +187,11 @@ class ManagementServer(proto.Message): state (google.cloud.backupdr_v1.types.ManagementServer.InstanceState): Output only. The ManagementServer state. networks (MutableSequence[google.cloud.backupdr_v1.types.NetworkConfig]): - Required. VPC networks to which the + Optional. VPC networks to which the ManagementServer instance is connected. For this version, only a single network is supported. + This field is optional if MS is created without + PSA etag (str): Optional. Server specified ETag for the ManagementServer resource to prevent @@ -548,6 +552,79 @@ class DeleteManagementServerRequest(proto.Message): ) +class InitializeServiceRequest(proto.Message): + r"""Request message for initializing the service. + + Attributes: + name (str): + Required. The resource name of the serviceConfig used to + initialize the service. Format: + ``projects/{project_id}/locations/{location}/serviceConfig``. + resource_type (str): + Required. The resource type to which the + default service config will be applied. Examples + include, "compute.googleapis.com/Instance" and + "storage.googleapis.com/Bucket". + request_id (str): + Optional. 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. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and t he 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). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class InitializeServiceResponse(proto.Message): + r"""Response message for initializing the service. + + Attributes: + backup_vault_name (str): + The resource name of the default ``BackupVault`` created. + Format: + ``projects/{project_id}/locations/{location}/backupVaults/{backup_vault_id}``. + backup_plan_name (str): + The resource name of the default ``BackupPlan`` created. + Format: + ``projects/{project_id}/locations/{location}/backupPlans/{backup_plan_id}``. + """ + + backup_vault_name: str = proto.Field( + proto.STRING, + number=1, + ) + backup_plan_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class OperationMetadata(proto.Message): r"""Represents the metadata of the long-running operation. @@ -570,9 +647,11 @@ class OperationMetadata(proto.Message): requested_cancellation (bool): Output only. Identifies whether the user has requested cancellation of the operation. Operations that have - successfully been cancelled have [Operation.error][] value - with a [google.rpc.Status.code][google.rpc.Status.code] of - 1, corresponding to 'Code.CANCELLED'. + successfully been cancelled have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to 'Code.CANCELLED'. api_version (str): Output only. API version used to start the operation. diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplan.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplan.py index ca0eabb6d9f1..afbd52562729 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplan.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplan.py @@ -76,8 +76,9 @@ class BackupPlan(proto.Message): resource_type (str): Required. The resource type to which the ``BackupPlan`` will be applied. Examples include, - "compute.googleapis.com/Instance" and - "storage.googleapis.com/Bucket". + "compute.googleapis.com/Instance", + "sqladmin.googleapis.com/Instance", or + "alloydb.googleapis.com/Cluster". etag (str): Optional. ``etag`` is returned from the service in the response. As a user of the service, you may provide an etag @@ -187,6 +188,14 @@ class BackupRule(proto.Message): “days”. The value should be greater than or equal to minimum enforced retention of the backup vault. + + Minimum value is 1 and maximum value is 90 for + hourly backups. Minimum value is 1 and maximum + value is 90 for daily backups. Minimum value is + 7 and maximum value is 186 for weekly backups. + Minimum value is 30 and maximum value is 732 for + monthly backups. Minimum value is 365 and + maximum value is 36159 for yearly backups. standard_schedule (google.cloud.backupdr_v1.types.StandardSchedule): Required. Defines a schedule that runs within the confines of a defined window of time. diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplanassociation.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplanassociation.py index 23a4309a3fd8..0ba462095b1d 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplanassociation.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplanassociation.py @@ -48,8 +48,8 @@ class BackupPlanAssociation(proto.Message): projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId} resource_type (str): - Optional. Resource type of workload on which - backupplan is applied + Required. Immutable. Resource type of + workload on which backupplan is applied resource (str): Required. Immutable. Resource name of workload on which backupplan is applied @@ -71,11 +71,9 @@ class BackupPlanAssociation(proto.Message): Output only. The config info related to backup rules. data_source (str): - Output only. Output Only. - - Resource name of data source which will be used - as storage location for backups taken. - Format : + Output only. Resource name of data source + which will be used as storage location for + backups taken. Format : projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource} """ @@ -150,16 +148,13 @@ class RuleConfigInfo(proto.Message): Attributes: rule_id (str): - Output only. Output Only. - - Backup Rule id fetched from backup plan. + Output only. Backup Rule id fetched from + backup plan. last_backup_state (google.cloud.backupdr_v1.types.RuleConfigInfo.LastBackupState): Output only. The last backup state for rule. last_backup_error (google.rpc.status_pb2.Status): - Output only. Output Only. - - google.rpc.Status object to store the last - backup error. + Output only. google.rpc.Status object to + store the last backup error. last_successful_backup_consistency_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The point in time when the last successful backup was captured from the source. diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupvault.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupvault.py index ced3cd195702..5e953af015f2 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupvault.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupvault.py @@ -199,9 +199,8 @@ class BackupVault(proto.Message): Output only. Total size of the storage used by all backup resources. uid (str): - Output only. Output only - Immutable after resource creation until resource - deletion. + Output only. Immutable after resource + creation until resource deletion. annotations (MutableMapping[str, str]): Optional. User annotations. See https://google.aip.dev/128#annotations Stores @@ -210,8 +209,6 @@ class BackupVault(proto.Message): Optional. Note: This field is added for future use case and will not be supported in the current release. - Optional. - Access restriction for the backup vault. Default value is WITHIN_ORGANIZATION if not provided during creation. """ @@ -244,7 +241,9 @@ class AccessRestriction(proto.Enum): Values: ACCESS_RESTRICTION_UNSPECIFIED (0): - Access restriction not set. + Access restriction not set. If user does not provide any + value or pass this value, it will be changed to + WITHIN_ORGANIZATION. WITHIN_PROJECT (1): Access to or from resources outside your current project will be denied. @@ -253,11 +252,16 @@ class AccessRestriction(proto.Enum): current organization will be denied. UNRESTRICTED (3): No access restriction. + WITHIN_ORG_BUT_UNRESTRICTED_FOR_BA (4): + Access to or from resources outside your + current organization will be denied except for + backup appliance. """ ACCESS_RESTRICTION_UNSPECIFIED = 0 WITHIN_PROJECT = 1 WITHIN_ORGANIZATION = 2 UNRESTRICTED = 3 + WITHIN_ORG_BUT_UNRESTRICTED_FOR_BA = 4 name: str = proto.Field( proto.STRING, @@ -1532,6 +1536,11 @@ class DeleteBackupVaultRequest(proto.Message): Optional. If true and the BackupVault is not found, the request will succeed but no action will be taken. + ignore_backup_plan_references (bool): + Optional. If set to true, backupvault + deletion will proceed even if there are backup + plans referencing the backupvault. The default + is 'false'. """ name: str = proto.Field( @@ -1558,6 +1567,10 @@ class DeleteBackupVaultRequest(proto.Message): proto.BOOL, number=6, ) + ignore_backup_plan_references: bool = proto.Field( + proto.BOOL, + number=7, + ) class ListDataSourcesRequest(proto.Message): diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_backup_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_backup_plan_association_async.py index 25dbf9cca081..d60bb539a629 100644 --- a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_backup_plan_association_async.py +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_backup_plan_association_async.py @@ -40,6 +40,7 @@ async def sample_create_backup_plan_association(): # Initialize request argument(s) backup_plan_association = backupdr_v1.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" backup_plan_association.resource = "resource_value" backup_plan_association.backup_plan = "backup_plan_value" diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_backup_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_backup_plan_association_sync.py index fc82ca77f706..2c439946c9a7 100644 --- a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_backup_plan_association_sync.py +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_backup_plan_association_sync.py @@ -40,6 +40,7 @@ def sample_create_backup_plan_association(): # Initialize request argument(s) backup_plan_association = backupdr_v1.BackupPlanAssociation() + backup_plan_association.resource_type = "resource_type_value" backup_plan_association.resource = "resource_value" backup_plan_association.backup_plan = "backup_plan_value" diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initialize_service_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initialize_service_async.py new file mode 100644 index 000000000000..c938b4515018 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initialize_service_async.py @@ -0,0 +1,57 @@ +# -*- 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 InitializeService +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_InitializeService_async] +# 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 backupdr_v1 + + +async def sample_initialize_service(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + ) + + # Make the request + operation = client.initialize_service(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END backupdr_v1_generated_BackupDR_InitializeService_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initialize_service_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initialize_service_sync.py new file mode 100644 index 000000000000..8bd114b067c2 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initialize_service_sync.py @@ -0,0 +1,57 @@ +# -*- 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 InitializeService +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_InitializeService_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 backupdr_v1 + + +def sample_initialize_service(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + ) + + # Make the request + operation = client.initialize_service(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END backupdr_v1_generated_BackupDR_InitializeService_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json index 8963d463b241..0f3972263529 100644 --- a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json +++ b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-backupdr", - "version": "0.1.7" + "version": "0.1.0" }, "snippets": [ { @@ -68,12 +68,12 @@ "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlanAssociation_async", "segments": [ { - "end": 61, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 62, "start": 27, "type": "SHORT" }, @@ -83,18 +83,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], @@ -156,12 +156,12 @@ "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlanAssociation_sync", "segments": [ { - "end": 61, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 62, "start": 27, "type": "SHORT" }, @@ -171,18 +171,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], @@ -2651,6 +2651,159 @@ ], "title": "backupdr_v1_generated_backup_dr_get_management_server_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.initialize_service", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.InitializeService", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "InitializeService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.InitializeServiceRequest" + }, + { + "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.operation_async.AsyncOperation", + "shortName": "initialize_service" + }, + "description": "Sample for InitializeService", + "file": "backupdr_v1_generated_backup_dr_initialize_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_InitializeService_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_initialize_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.initialize_service", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.InitializeService", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "InitializeService" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.InitializeServiceRequest" + }, + { + "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.operation.Operation", + "shortName": "initialize_service" + }, + "description": "Sample for InitializeService", + "file": "backupdr_v1_generated_backup_dr_initialize_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_InitializeService_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_initialize_service_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-backupdr/scripts/fixup_backupdr_v1_keywords.py b/packages/google-cloud-backupdr/scripts/fixup_backupdr_v1_keywords.py index c0dd15568f46..a3de29cabf96 100644 --- a/packages/google-cloud-backupdr/scripts/fixup_backupdr_v1_keywords.py +++ b/packages/google-cloud-backupdr/scripts/fixup_backupdr_v1_keywords.py @@ -46,7 +46,7 @@ class backupdrCallTransformer(cst.CSTTransformer): 'delete_backup': ('name', 'request_id', ), 'delete_backup_plan': ('name', 'request_id', ), 'delete_backup_plan_association': ('name', 'request_id', ), - 'delete_backup_vault': ('name', 'request_id', 'force', 'etag', 'validate_only', 'allow_missing', ), + 'delete_backup_vault': ('name', 'request_id', 'force', 'etag', 'validate_only', 'allow_missing', 'ignore_backup_plan_references', ), 'delete_management_server': ('name', 'request_id', ), 'fetch_usable_backup_vaults': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'get_backup': ('name', 'view', ), @@ -55,6 +55,7 @@ class backupdrCallTransformer(cst.CSTTransformer): 'get_backup_vault': ('name', 'view', ), 'get_data_source': ('name', ), 'get_management_server': ('name', ), + 'initialize_service': ('name', 'resource_type', 'request_id', ), 'list_backup_plan_associations': ('parent', 'page_size', 'page_token', 'filter', ), 'list_backup_plans': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', 'view', ), diff --git a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py index 80493a625975..87936c9d9952 100644 --- a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py +++ b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py @@ -11911,6 +11911,267 @@ async def test_trigger_backup_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + backupdr.InitializeServiceRequest, + dict, + ], +) +def test_initialize_service(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupdr.InitializeServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_initialize_service_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = backupdr.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.initialize_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == backupdr.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + ) + + +def test_initialize_service_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # 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.initialize_service 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.initialize_service + ] = mock_rpc + request = {} + client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.initialize_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_initialize_service_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # 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_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.initialize_service + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.initialize_service + ] = mock_rpc + + request = {} + await client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.initialize_service(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_initialize_service_async( + transport: str = "grpc_asyncio", request_type=backupdr.InitializeServiceRequest +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupdr.InitializeServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_initialize_service_async_from_dict(): + await test_initialize_service_async(request_type=dict) + + +def test_initialize_service_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.InitializeServiceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_initialize_service_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = backupdr.InitializeServiceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.initialize_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + def test_list_management_servers_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -13991,6 +14252,7 @@ def test_delete_backup_vault_rest_required_fields( "allow_missing", "etag", "force", + "ignore_backup_plan_references", "request_id", "validate_only", ) @@ -14052,6 +14314,7 @@ def test_delete_backup_vault_rest_unset_required_fields(): "allowMissing", "etag", "force", + "ignoreBackupPlanReferences", "requestId", "validateOnly", ) @@ -17690,6 +17953,144 @@ def test_trigger_backup_rest_flattened_error(transport: str = "rest"): ) +def test_initialize_service_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 = BackupDRClient( + 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.initialize_service 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.initialize_service + ] = mock_rpc + + request = {} + client.initialize_service(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.initialize_service(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_initialize_service_rest_required_fields( + request_type=backupdr.InitializeServiceRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request_init["resource_type"] = "" + 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() + ).initialize_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["resourceType"] = "resource_type_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).initialize_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + 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.initialize_service(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_initialize_service_rest_unset_required_fields(): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.initialize_service._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "resourceType", + ) + ) + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.BackupDRGrpcTransport( @@ -18399,6 +18800,29 @@ def test_trigger_backup_empty_call_grpc(): 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_initialize_service_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = BackupDRAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -19194,6 +19618,33 @@ async def test_trigger_backup_empty_call_grpc_asyncio(): 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. +@pytest.mark.asyncio +async def test_initialize_service_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = BackupDRClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -23338,6 +23789,122 @@ def test_trigger_backup_rest_interceptors(null_interceptor): post.assert_called_once() +def test_initialize_service_rest_bad_request( + request_type=backupdr.InitializeServiceRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/serviceConfig"} + 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.initialize_service(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.InitializeServiceRequest, + dict, + ], +) +def test_initialize_service_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/serviceConfig"} + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + 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.initialize_service(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_initialize_service_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BackupDRRestInterceptor, "post_initialize_service" + ) as post, mock.patch.object( + transports.BackupDRRestInterceptor, "pre_initialize_service" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = backupdr.InitializeServiceRequest.pb( + backupdr.InitializeServiceRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = backupdr.InitializeServiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.initialize_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -24484,6 +25051,28 @@ def test_trigger_backup_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_initialize_service_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + client.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + + assert args[0] == request_msg + + def test_backup_dr_rest_lro_client(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -24561,6 +25150,7 @@ def test_backup_dr_base_transport(): "list_backup_plan_associations", "delete_backup_plan_association", "trigger_backup", + "initialize_service", "set_iam_policy", "get_iam_policy", "test_iam_permissions", @@ -24911,6 +25501,9 @@ def test_backup_dr_client_transport_session_collision(transport_name): session1 = client1.transport.trigger_backup._session session2 = client2.transport.trigger_backup._session assert session1 != session2 + session1 = client1.transport.initialize_service._session + session2 = client2.transport.initialize_service._session + assert session1 != session2 def test_backup_dr_grpc_transport_channel():