feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for Backup and DR backups."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class Backups(base.Group):
"""Manage Backup and DR backups."""

View File

@@ -0,0 +1,105 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Deletes a Backup and DR Backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.backupdr import util
from googlecloudsdk.api_lib.backupdr.backups import BackupsClient
from googlecloudsdk.api_lib.util import exceptions
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.backupdr import flags
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Delete the specified Backup."""
detailed_help = {
'BRIEF': 'Deletes a specific backup',
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To delete a backup `sample-backup` in backup vault `sample-vault`, data source `sample-ds`, project `sample-project` and location `us-central1` , run:
$ {command} sample-backup --backup-vault=sample-vault --data-source=sample-ds --project=sample-project --location=us-central1
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
base.ASYNC_FLAG.SetDefault(parser, True)
flags.AddBackupResourceArg(
parser,
'Name of the backup to delete.',
)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = BackupsClient()
is_async = args.async_
backup = args.CONCEPTS.backup.Parse()
console_io.PromptContinue(
message='The backup will be deleted. You cannot undo this action.',
default=True,
cancel_on_no=True,
)
try:
operation = client.Delete(backup)
except apitools_exceptions.HttpError as e:
raise exceptions.HttpException(e, util.HTTP_ERROR_FORMAT)
if is_async:
log.DeletedResource(
backup.RelativeName(),
kind='backup',
is_async=True,
details=util.ASYNC_OPERATION_MESSAGE.format(operation.name),
)
return operation
response = client.WaitForOperation(
operation_ref=client.GetOperationRef(operation),
message=(
'Deleting backup [{}]. (This operation usually takes 5 mins but'
' could take up to 60 mins.)'.format(backup.RelativeName())
),
has_result=False,
)
log.DeletedResource(backup.RelativeName(), kind='backup')
return response

View File

@@ -0,0 +1,23 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Show details of the backup.
description: Show all data associated with the specified backup.
examples: |
To view details for backup 'BACKUP', run:
$ {command} BACKUP
request:
collection: backupdr.projects.locations.backupVaults.dataSources.backups
response:
id_field: name
arguments:
resource:
help_text: Name of the backup to describe.
spec: !REF googlecloudsdk.command_lib.backupdr.resources:backup
is_positional: true
output:
format: json

View File

@@ -0,0 +1,126 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to fetch backups for a resource type."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.backupdr import backups
from googlecloudsdk.api_lib.util import common_args
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.backupdr import flags
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import log
BackupsClient = (
backups.BackupsClient
)
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class FetchForResourceType(base.ListCommand):
"""Fetch Backups for a given resource type and location."""
detailed_help = {
'BRIEF': (
'List backups in a specified location'
' and resource type in a project.'
),
'DESCRIPTION': (
'{description} List backups for the specified resource type for a '
'data source.'
),
'EXAMPLES': """\
To list backups for Cloud SQL instance resources for data source `my-data-source` with location `us-central1` under backup vault, `my-vault`.
$ {command} sqladmin.googleapis.com/Instance --data-source=my-data-source --backup-vault=my-vault --location=us-central1
""",
}
DEFAULT_LIST_FORMAT = """
table(
name.basename():label=NAME,
description:label=DESCRIPTION,
createTime:label=CREATE_TIME,
enforcedRetentionEndTime:label=ENFORCED_RETENTION_END_TIME,
state:label=STATE,
backupType:label=BACKUP_TYPE,
expireTime:label=EXPIRE_TIME,
resourceSizeBytes:label=RESOURCE_SIZE_BYTES
)
"""
@staticmethod
def Args(parser):
parser.add_argument(
'resource_type',
help=(
'Resource type for which backup plan associations should be'
' fetched.'
),
)
concept_parsers.ConceptParser.ForResource(
'--data-source',
flags.GetDataSourceResourceSpec(),
'Data source for which backups should be fetched.',
required=True).AddToParser(parser)
flags.AddOutputFormat(parser, FetchForResourceType.DEFAULT_LIST_FORMAT)
def _Validate_and_Parse_SortBy(self, args):
order_by = common_args.ParseSortByArg(args.sort_by)
# Only sort by name is supported by CLH right now.
if order_by is None:
return None
order_by_fields = order_by.split(' ')
if (
order_by_fields
and isinstance(order_by_fields[0], str)
and order_by_fields[0]
not in ('name', 'Name')
):
raise exceptions.InvalidArgumentException(
'sort_by',
'Invalid sort_by argument. Only sort_by'
' name/Name is'
' supported.',
)
order_by_fields[0] = 'name'
order_by = ' '.join(order_by_fields)
return order_by
def Run(self, args):
"""Run the command."""
resource_type = args.resource_type
data_source_ref = args.CONCEPTS.data_source.Parse()
try:
client = BackupsClient()
result = client.FetchForResourceType(
data_source_ref,
resource_type,
filter_expression=args.filter,
page_size=args.page_size,
order_by=self._Validate_and_Parse_SortBy(args),
)
if result and result.backups:
return result.backups # Return the list directly
else:
return [] # Return an empty list
except Exception as e: # pylint: disable=broad-except
log.error(f'Error fetching backups : {e}')
raise e # Raise the exception

View File

@@ -0,0 +1,29 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: List Backups
description: Displays all backups in a project.
examples: |
To list backups for all data sources, backup vaults and locations, run:
$ {command}
To list all backups for a data source ``my-data-source'' and a backup vault ``my-vault'' in a location ``my-location'', run:
$ {command} --data-source=my-data-source --backup-vault=my-vault --location=my-location
request:
collection: backupdr.projects.locations.backupVaults.dataSources.backups
modify_request_hooks:
- googlecloudsdk.command_lib.backupdr.declarative:SetBasicViewByDefaultRequestHook
response:
id_field: name
arguments:
resource:
help_text: Data source to list backups from.
spec: !REF googlecloudsdk.command_lib.backupdr.resources:dataSourceDefault
is_positional: false
output:
format: |
json

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for Backup and DR Backup Restore."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class Restore(base.Group):
"""Manage restore operations for resources."""

View File

@@ -0,0 +1,257 @@
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Restores a Compute Instance Backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.backupdr import util
from googlecloudsdk.api_lib.backupdr.backups import BackupsClient
from googlecloudsdk.api_lib.backupdr.backups import ComputeRestoreConfig
from googlecloudsdk.api_lib.util import exceptions
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.backupdr import flags
from googlecloudsdk.command_lib.backupdr.restore import compute_flags
from googlecloudsdk.core import log
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class Compute(base.Command):
"""Restores a Compute Engine VM Backup."""
detailed_help = {
'BRIEF': 'Restores the specified backup',
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To restore a backup `sample-backup` in project `sample-project` and location `us-central1`,
with `sample-data-store` and `sample-backup-vault`, and additional target properties, run:
$ {command} sample-backup --project=sample-project --location=us-central1 --backup-vault=sample-backup-vault --data-source=sample-data-source --<target-properties>
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
base.ASYNC_FLAG.SetDefault(parser, True)
flags.AddBackupResourceArg(
parser, 'The backup of a resource to be restored.'
)
compute_flags.AddNameArg(parser)
compute_flags.AddTargetZoneArg(parser)
compute_flags.AddTargetProjectArg(parser)
compute_flags.AddNetworkInterfaceArg(parser, False)
compute_flags.AddServiceAccountArg(parser, False)
compute_flags.AddScopesArg(parser, False)
compute_flags.AddCreateDiskArg(parser, False)
compute_flags.AddDescriptionArg(parser, False)
compute_flags.AddMetadataArg(parser, False)
compute_flags.AddLabelsArg(parser, False)
compute_flags.AddTagsArg(parser, False)
compute_flags.AddMachineTypeArg(parser, False)
compute_flags.AddHostnameArg(parser, False)
compute_flags.AddEnableUefiNetworkingArg(parser, False)
compute_flags.AddThreadsPerCoreArg(parser, False)
compute_flags.AddVisibleCoreCountArg(parser, False)
compute_flags.AddAcceleratorArg(parser, False)
compute_flags.AddMinCpuPlatform(parser, False)
# Scheduling Flags
compute_flags.AddMaintenancePolicyArg(parser, False)
compute_flags.AddPreemptibleArg(parser, False)
compute_flags.AddRestartOnFailureArg(parser, False)
compute_flags.AddMinNodeCpuArg(parser, False)
compute_flags.AddProvisioningModelArg(parser, False)
compute_flags.AddInstanceTerminationActionArg(parser, False)
compute_flags.AddLocalSsdRecoveryTimeoutArg(parser, False)
compute_flags.AddNodeAffinityFileArg(parser, False)
compute_flags.AddReservationArgs(parser, False)
compute_flags.AddEnableDisplayDeviceArg(parser, False)
compute_flags.AddCanIpForwardArg(parser, False)
compute_flags.AddPrivateIpv6GoogleAccessArg(parser, False)
compute_flags.AddNetworkPerformanceConfigsArg(parser, False)
compute_flags.AddConfidentialComputeArg(parser, False)
compute_flags.AddDeletionProtectionArg(parser, False)
compute_flags.AddResourceManagerTagsArg(parser, False)
compute_flags.AddResourcePoliciesArg(parser, False)
compute_flags.AddKeyRevocationActionTypeArg(parser, False)
compute_flags.AddInstanceKmsKeyArg(parser, False)
compute_flags.AddClearEncryptionKeyArg(parser)
def _ParseResourcePolicies(self, resource_policies, project, zone):
"""Parses the resource policies flag."""
resource_policy_uris = []
for policy in resource_policies:
if not policy.startswith('projects/'):
region = zone.rsplit('-', 1)[0]
policy = (
'projects/{}/regions/{}/resourcePolicies/{}'.format(
project, region, policy
)
)
resource_policy_uris.append(policy)
return resource_policy_uris
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = BackupsClient()
is_async = args.async_
backup = args.CONCEPTS.backup.Parse()
restore_config = ComputeRestoreConfig()
restore_config['Name'] = args.name
restore_config['TargetZone'] = args.target_zone
restore_config['TargetProject'] = args.target_project
if args.network_interface:
restore_config['NetworkInterfaces'] = args.network_interface
if args.service_account:
restore_config['ServiceAccount'] = args.service_account
if args.scopes:
restore_config['Scopes'] = args.scopes
restore_config['NoScopes'] = args.no_scopes if args.no_scopes else False
if args.create_disk:
restore_config['CreateDisks'] = args.create_disk
if args.description:
restore_config['Description'] = args.description
if args.metadata:
restore_config['Metadata'] = args.metadata
if args.labels:
restore_config['Labels'] = args.labels
if args.tags:
restore_config['Tags'] = args.tags
if args.machine_type:
if not args.machine_type.startswith('projects/'):
args.machine_type = 'projects/{}/zones/{}/machineTypes/{}'.format(
args.target_project, args.target_zone, args.machine_type
)
restore_config['MachineType'] = args.machine_type
if args.hostname:
restore_config['Hostname'] = args.hostname
if args.enable_uefi_networking is not None:
restore_config['EnableUefiNetworking'] = args.enable_uefi_networking
if args.threads_per_core:
restore_config['ThreadsPerCore'] = args.threads_per_core
if args.visible_core_count:
restore_config['VisibleCoreCount'] = args.visible_core_count
if args.accelerator:
if not args.accelerator['type'].startswith('projects/'):
args.accelerator['type'] = (
'projects/{}/zones/{}/acceleratorTypes/{}'.format(
args.target_project, args.target_zone, args.accelerator['type']
)
)
restore_config['Accelerator'] = args.accelerator
if args.min_cpu_platform:
restore_config['MinCpuPlatform'] = args.min_cpu_platform
if args.maintenance_policy:
restore_config['MaintenancePolicy'] = args.maintenance_policy
if args.preemptible is not None:
restore_config['Preemptible'] = args.preemptible
if args.restart_on_failure is not None:
restore_config['RestartOnFailure'] = args.restart_on_failure
if args.min_node_cpu:
restore_config['MinNodeCpus'] = args.min_node_cpu
if args.provisioning_model:
restore_config['ProvisioningModel'] = args.provisioning_model
if args.instance_termination_action:
restore_config['InstanceTerminationAction'] = (
args.instance_termination_action
)
if args.local_ssd_recovery_timeout:
restore_config['LocalSsdRecoveryTimeout'] = (
args.local_ssd_recovery_timeout
)
if args.node_affinity_file:
restore_config['NodeAffinityFile'] = args.node_affinity_file
if args.reservation_affinity:
restore_config['ReservationAffinity'] = args.reservation_affinity
if args.reservation:
restore_config['Reservation'] = args.reservation
if args.enable_display_device is not None:
restore_config['EnableDisplayDevice'] = args.enable_display_device
if args.can_ip_forward is not None:
restore_config['CanIpForward'] = args.can_ip_forward
if args.private_ipv6_google_access_type:
restore_config['PrivateIpv6GoogleAccessType'] = (
args.private_ipv6_google_access_type
)
if args.network_performance_configs:
restore_config['NetworkPerformanceConfigs'] = (
args.network_performance_configs
)
if args.confidential_compute:
restore_config['ConfidentialCompute'] = args.confidential_compute
if args.deletion_protection is not None:
restore_config['DeletionProtection'] = args.deletion_protection
if args.resource_manager_tags:
restore_config['ResourceManagerTags'] = args.resource_manager_tags
if args.resource_policies:
restore_config['ResourcePolicies'] = self._ParseResourcePolicies(
args.resource_policies, args.target_project, args.target_zone
)
if args.key_revocation_action_type:
restore_config['KeyRevocationActionType'] = (
args.key_revocation_action_type
)
if args.instance_kms_key:
restore_config['InstanceKmsKey'] = args.instance_kms_key
if args.clear_encryption_key:
restore_config['ClearOverridesFieldMask'] = (
'compute_instance_restore_properties.disks.*.disk_encryption_key'
)
try:
operation = client.RestoreCompute(backup, restore_config)
except apitools_exceptions.HttpError as e:
raise exceptions.HttpException(e, util.HTTP_ERROR_FORMAT) from e
if is_async:
log.RestoredResource(
backup.Name(),
kind='backup',
is_async=True,
details=util.ASYNC_OPERATION_MESSAGE.format(operation.name),
)
return operation
# For sync operation
return client.WaitForOperation(
operation_ref=client.GetOperationRef(operation),
message=(
'Restoring backup'
' [{}].'
' (This operation could take up to 15 minutes.)'.format(
backup.Name()
)
),
has_result=False,
)

View File

@@ -0,0 +1,179 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Restores a Compute Disk Backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.backupdr import util
from googlecloudsdk.api_lib.backupdr.backups import BackupsClient
from googlecloudsdk.api_lib.backupdr.backups import DiskRestoreConfig
from googlecloudsdk.api_lib.util import exceptions
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.backupdr import flags
from googlecloudsdk.command_lib.backupdr.restore import disk_flags
from googlecloudsdk.core import log
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class Disk(base.Command):
"""Restores a Compute Disk Backup."""
detailed_help = {
'BRIEF': 'Restores the specified backup',
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To restore a backup `sample-backup` in project `sample-project` and location `us-central1`,
with `sample-data-store` and `sample-backup-vault`, and additional target properties, run:
$ {command} sample-backup --project=sample-project --location=us-central1 --backup-vault=sample-backup-vault --data-source=sample-data-source --<target-properties>
""",
}
@staticmethod
def Args(parser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
base.ASYNC_FLAG.SetDefault(parser, True)
flags.AddBackupResourceArg(
parser, 'The backup of a resource to be restored.'
)
disk_flags.AddNameArg(parser)
disk_flags.AddTargetZoneArg(parser, False)
disk_flags.AddTargetRegionArg(parser, False)
disk_flags.AddTargetProjectArg(parser)
disk_flags.AddReplicaZonesArg(parser, False)
disk_flags.AddGuestOsFeaturesArgs(parser, False)
disk_flags.AddDescriptionArg(parser, False)
disk_flags.AddLicensesArg(parser, False)
disk_flags.AddLabelsArg(parser, False)
disk_flags.AddTypeArg(parser, False)
disk_flags.AddAccessModeArg(parser, False)
disk_flags.AddProvisionedIopsArg(parser, False)
disk_flags.AddProvisionedThroughputArg(parser, False)
disk_flags.AddArchitectureArg(parser, False)
disk_flags.AddStoragePoolArg(parser, False)
disk_flags.AddSizeArg(parser, False)
disk_flags.AddConfidentialComputeArg(parser, False)
disk_flags.AddResourcePoliciesArg(parser, False)
disk_flags.AddKmsKeyArg(parser, False)
disk_flags.AddClearEncryptionKeyArg(parser)
def _ParseResourcePolicies(self, resource_policies, project, zone):
"""Parses the resource policies flag."""
resource_policy_uris = []
for policy in resource_policies:
if not policy.startswith('projects/'):
region = zone.rsplit('-', 1)[0]
policy = 'projects/{}/regions/{}/resourcePolicies/{}'.format(
project, region, policy
)
resource_policy_uris.append(policy)
return resource_policy_uris
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = BackupsClient()
is_async = args.async_
backup = args.CONCEPTS.backup.Parse()
restore_config = DiskRestoreConfig()
restore_config['Name'] = args.name
restore_config['TargetProject'] = args.target_project
if args.target_zone:
restore_config['TargetZone'] = args.target_zone
if args.target_region:
restore_config['TargetRegion'] = args.target_region
if args.replica_zones:
restore_config['ReplicaZones'] = args.replica_zones
if args.guest_os_features:
restore_config['GuestOsFeatures'] = args.guest_os_features
if args.licenses:
restore_config['Licenses'] = args.licenses
if args.description:
restore_config['Description'] = args.description
if args.type:
restore_config['Type'] = args.type
if args.access_mode:
restore_config['AccessMode'] = args.access_mode
if args.provisioned_iops:
restore_config['ProvisionedIops'] = args.provisioned_iops
if args.provisioned_throughput:
restore_config['ProvisionedThroughput'] = args.provisioned_throughput
if args.architecture:
restore_config['Architecture'] = args.architecture
if args.storage_pool:
restore_config['StoragePool'] = args.storage_pool
if args.size:
restore_config['Size'] = args.size
if args.kms_key:
restore_config['KmsKey'] = args.kms_key
if args.labels:
restore_config['Labels'] = args.labels
restore_config['ConfidentialCompute'] = args.confidential_compute
if args.resource_policies:
restore_config['ResourcePolicies'] = self._ParseResourcePolicies(
args.resource_policies, args.target_project, args.target_zone
)
if (
hasattr(args, 'clear_encryption_key')
and args.clear_encryption_key
):
restore_config['ClearOverridesFieldMask'] = (
'disk_restore_properties.disk_encryption_key'
)
try:
operation = client.RestoreDisk(backup, restore_config)
except apitools_exceptions.HttpError as e:
raise exceptions.HttpException(e, util.HTTP_ERROR_FORMAT) from e
if is_async:
log.RestoredResource(
backup.Name(),
kind='backup',
is_async=True,
details=util.ASYNC_OPERATION_MESSAGE.format(operation.name),
)
return operation
# For sync operation
return client.WaitForOperation(
operation_ref=client.GetOperationRef(operation),
message=(
'Restoring backup'
' [{}].'
' (This operation could take upto 15 minutes.)'.format(
backup.Name()
)
),
has_result=False,
)

View File

@@ -0,0 +1,161 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Updates a Backup and DR Backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import argparse
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.backupdr import util
from googlecloudsdk.api_lib.backupdr.backups import BackupsClient
from googlecloudsdk.api_lib.util import exceptions
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.backupdr import flags
from googlecloudsdk.command_lib.backupdr import util as command_util
from googlecloudsdk.core import log
def _add_common_args(parser: argparse.ArgumentParser):
"""Specifies additional command flags.
Args:
parser: argparse.Parser: Parser object for command line inputs.
"""
base.ASYNC_FLAG.AddToParser(parser)
base.ASYNC_FLAG.SetDefault(parser, True)
flags.AddBackupResourceArg(
parser,
'Name of the backup to update.',
)
flags.AddUpdateBackupFlags(parser)
def _add_common_update_mask(args) -> str:
updated_fields = []
if args.IsSpecified('enforced_retention_end_time'):
updated_fields.append('enforcedRetentionEndTime')
if args.IsSpecified('expire_time'):
updated_fields.append('expireTime')
return ','.join(updated_fields)
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
"""Update the specified Backup."""
detailed_help = {
'BRIEF': 'Updates a specific backup',
'DESCRIPTION': '{description}',
'EXAMPLES': """\
To update the enforced retention of a backup sample-backup in backup vault sample-vault, data source
sample-ds, project sample-project and location us-central1, run:
$ {command} sample-backup --backup-vault=sample-vault --data-source=sample-ds --project=sample-project --location=us-central1 --enforced-retention-end-time="2025-02-14T01:10:20Z"
""",
}
@staticmethod
def Args(parser: argparse.ArgumentParser):
_add_common_args(parser)
def ParseUpdate(self, args, client):
updated_enforced_retention = command_util.VerifyDateInFuture(
args.enforced_retention_end_time, 'enforced-retention-end-time'
)
expire_time = command_util.VerifyDateInFuture(
args.expire_time, 'expire-time'
)
parsed_backup = client.ParseUpdate(updated_enforced_retention, expire_time)
return parsed_backup
def GetUpdateMask(self, args):
return _add_common_update_mask(args)
def Run(self, args):
"""Constructs and sends request.
Args:
args: argparse.Namespace, An object that contains the values for the
arguments specified in the .Args() method.
Returns:
ProcessHttpResponse of the request made.
"""
client = BackupsClient()
is_async = args.async_
backup = args.CONCEPTS.backup.Parse()
try:
parsed_backup = self.ParseUpdate(args, client)
update_mask = self.GetUpdateMask(args)
operation = client.Update(
backup,
parsed_backup,
update_mask=update_mask,
)
except apitools_exceptions.HttpError as e:
raise exceptions.HttpException(e, util.HTTP_ERROR_FORMAT)
if is_async:
log.UpdatedResource(
backup.RelativeName(),
kind='backup',
is_async=True,
details=util.ASYNC_OPERATION_MESSAGE.format(operation.name),
)
return operation
response = client.WaitForOperation(
operation_ref=client.GetOperationRef(operation),
message=(
'Updating backup [{}]. (This operation usually takes less than 1'
' minute.)'.format(backup.RelativeName())
),
has_result=False,
)
log.UpdatedResource(backup.RelativeName(), kind='backup')
return response
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(Update):
"""Update the specified Backup."""
@staticmethod
def Args(parser: argparse.ArgumentParser):
_add_common_args(parser)
def ParseUpdate(self, args, client):
updated_enforced_retention = command_util.VerifyDateInFuture(
args.enforced_retention_end_time, 'enforced-retention-end-time'
)
expire_time = command_util.VerifyDateInFuture(
args.expire_time, 'expire-time'
)
parsed_backup = client.ParseUpdate(updated_enforced_retention, expire_time)
return parsed_backup
def GetUpdateMask(self, args):
return _add_common_update_mask(args)