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,36 @@
# -*- coding: utf-8 -*- #
# Copyright 2013 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.
"""Provide commands for working with backups of Cloud SQL instances."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class BackupRuns(base.Group):
"""Provide commands for working with backups of Cloud SQL instances.
Provide commands for working with backups of Cloud SQL instances
including listing and getting information about backups for a Cloud SQL
instance.
"""
category = base.DATABASES_CATEGORY

View File

@@ -0,0 +1,133 @@
# -*- coding: utf-8 -*- #
# Copyright 2016 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.
"""Creates a backup of a Cloud SQL instance."""
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.sql import api_util
from googlecloudsdk.api_lib.sql import operations
from googlecloudsdk.api_lib.sql import validate
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.sql import flags
from googlecloudsdk.command_lib.sql import instances as command_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class CreateBackup(base.CreateCommand):
"""Creates a backup of a Cloud SQL instance."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
"""
flags.AddInstance(parser)
flags.AddProjectLevelBackupEndpoint(parser)
parser.add_argument(
'--description', help='A friendly description of the backup.')
parser.add_argument(
'--location',
help=('Choose where to store your backup. Backups are stored in the '
'closest multi-region location to you by default. Only '
'customize if needed.'))
base.ASYNC_FLAG.AddToParser(parser)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
"""Restores a backup of a Cloud SQL instance.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the
restoreBackup operation if the restoreBackup was successful.
"""
client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
sql_client = client.sql_client
sql_messages = client.sql_messages
validate.ValidateInstanceName(args.instance)
instance_ref = client.resource_parser.Parse(
args.instance,
params={'project': properties.VALUES.core.project.GetOrFail},
collection='sql.instances')
# Check if instance has customer-managed key; show warning if so.
try:
instance_resource = sql_client.instances.Get(
sql_messages.SqlInstancesGetRequest(
project=instance_ref.project, instance=instance_ref.instance))
if instance_resource.diskEncryptionConfiguration:
command_util.ShowCmekWarning('backup', 'this instance')
except apitools_exceptions.HttpError:
# This is for informational purposes, so don't throw an error if failure.
pass
if args.project_level:
result_operation = sql_client.backups.CreateBackup(
sql_messages.SqlBackupsCreateBackupRequest(
parent='projects/'+instance_ref.project,
backup=sql_messages.Backup(
description=args.description,
instance=instance_ref.instance,
location=args.location,
kind='sql#backup',
),
)
)
else:
result_operation = sql_client.backupRuns.Insert(
sql_messages.SqlBackupRunsInsertRequest(
project=instance_ref.project,
instance=instance_ref.instance,
backupRun=sql_messages.BackupRun(
description=args.description,
instance=instance_ref.instance,
location=args.location,
kind='sql#backupRun',
),
)
)
operation_ref = client.resource_parser.Create(
'sql.operations',
operation=result_operation.name,
project=instance_ref.project)
if args.async_:
return sql_client.operations.Get(
sql_messages.SqlOperationsGetRequest(
project=operation_ref.project, operation=operation_ref.operation))
operations.OperationsV1Beta4.WaitForOperation(
sql_client, operation_ref, 'Backing up Cloud SQL instance')
log.status.write('[{instance}] backed up.\n'.format(instance=instance_ref))
return None

View File

@@ -0,0 +1,126 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 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 run for a Cloud SQL instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.sql import api_util
from googlecloudsdk.api_lib.sql import exceptions
from googlecloudsdk.api_lib.sql import operations
from googlecloudsdk.api_lib.sql import validate
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.sql import flags
from googlecloudsdk.command_lib.sql import validate as command_validate
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA
)
class Delete(base.DeleteCommand):
"""Delete a backup of a Cloud SQL instance."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
"""
base.ASYNC_FLAG.AddToParser(parser)
flags.AddBackupId(parser)
flags.AddOptionalInstance(parser)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
"""Deletes a backup of a Cloud SQL instance.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the delete
operation if the api request was successful.
"""
client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
sql_client = client.sql_client
sql_messages = client.sql_messages
operation_ref = None
# TODO(b/36051078): validate on FE that a backup run id is valid.
console_io.PromptContinue(
message='The backup will be deleted. You cannot undo this action.',
default=True,
cancel_on_no=True,
)
is_project_level_backup_deletion = (
command_validate.IsProjectLevelBackupRequest(args.id)
)
if is_project_level_backup_deletion:
result = sql_client.backups.DeleteBackup(
sql_messages.SqlBackupsDeleteBackupRequest(name=args.id)
)
operation_ref = client.resource_parser.Create(
'sql.operations', operation=result.name, project=args.id.split('/')[1]
)
else:
if args.instance is None:
raise exceptions.ArgumentError(
"[--instance | --i] is required for instance's backup deletion."
)
validate.ValidateInstanceName(args.instance)
instance_ref = client.resource_parser.Parse(
args.instance,
params={'project': properties.VALUES.core.project.GetOrFail},
collection='sql.instances',
)
result = sql_client.backupRuns.Delete(
sql_messages.SqlBackupRunsDeleteRequest(
project=instance_ref.project,
instance=instance_ref.instance,
id=int(args.id),
)
)
operation_ref = client.resource_parser.Create(
'sql.operations', operation=result.name, project=instance_ref.project
)
if args.async_:
# Don't wait for the running operation to complete when async is used.
return sql_client.operations.Get(
sql_messages.SqlOperationsGetRequest(
project=operation_ref.project, operation=operation_ref.operation
)
)
message = 'backup run'
if is_project_level_backup_deletion:
message = 'backup'
operations.OperationsV1Beta4.WaitForOperation(
sql_client, operation_ref, 'Deleting {0}'.format(message)
)
log.DeletedResource(args.id, message)

View File

@@ -0,0 +1,88 @@
# -*- coding: utf-8 -*- #
# Copyright 2013 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.
"""Retrieves information about a backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.sql import api_util
from googlecloudsdk.api_lib.sql import validate
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.sql import flags
from googlecloudsdk.command_lib.sql import validate as command_validate
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA
)
class Describe(base.DescribeCommand):
"""Retrieves information about a backup.
Retrieves information about a backup.
"""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
"""
flags.AddBackupId(parser)
flags.AddOptionalInstance(parser)
def _GetById(self, backup_id, instance_name):
client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
sql_client = client.sql_client
sql_messages = client.sql_messages
if command_validate.IsProjectLevelBackupRequest(backup_id):
request = sql_messages.SqlBackupsGetBackupRequest(name=backup_id)
return sql_client.backups.GetBackup(request)
instance_ref = client.resource_parser.Parse(
instance_name,
params={'project': properties.VALUES.core.project.GetOrFail},
collection='sql.instances',
)
request = sql_messages.SqlBackupRunsGetRequest(
project=instance_ref.project,
instance=instance_ref.instance,
id=int(backup_id),
)
return sql_client.backupRuns.Get(request)
def Run(self, args):
"""Retrieves information about a backup.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object that has the backup run resource if the command ran
successfully.
"""
if args.instance:
validate.ValidateInstanceName(args.instance)
return self._GetById(args.id, args.instance)

View File

@@ -0,0 +1,122 @@
# -*- coding: utf-8 -*- #
# Copyright 2013 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.
"""Lists all backups associated with a given instance.
Lists all backups associated with a given instance and configuration
in the reverse chronological order of the enqueued time.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.sql import api_util
from googlecloudsdk.api_lib.sql import validate
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.sql import filter_rewrite
from googlecloudsdk.command_lib.sql import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class List(base.ListCommand):
"""Lists all backups associated with the project or a given instance.
Lists all backups associated with the project or a given Cloud SQL instance
and configuration in the reverse chronological order of the enqueued time.
"""
@staticmethod
def Args(parser):
flags.AddOptionalInstance(parser, True)
parser.display_info.AddFormat("""
table(
id,
windowStartTime.iso(),
error.code.yesno(no="-"):label=ERROR,
status,
instance
)
""")
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
"""Lists all backups associated with a given instance.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object that has the list of backup run resources if the command ran
successfully.
"""
client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
sql_client = client.sql_client
sql_messages = client.sql_messages
if not args.instance:
# For project-level backups, this command updates the output table.
# pylint:disable-next=protected-access
args._GetParser().ai.display_info.AddFormat("""table(
name,
backupInterval.startTime.iso():label=WINDOW_START_TIME,
error.errors[0].code.yesno(no="-"):label=ERROR,
state:label=STATE,
instance,
type,
instanceDeletionTime.iso(undefined='-'):label=INSTANCE_DELETION_TIME
)""")
args.filter, server_filter = filter_rewrite.Backend().Rewrite(
args.filter)
if args.filter:
log.info('client_filter: %s', args.filter)
if server_filter:
log.info('server_filter: %s', server_filter)
return list_pager.YieldFromList(
sql_client.backups,
sql_messages.SqlBackupsListBackupsRequest(
parent='projects/{0}'.format(
properties.VALUES.core.project.GetOrFail()
),
filter=server_filter,
),
limit=args.limit,
batch_size=args.page_size,
batch_size_attribute='pageSize',
method='ListBackups',
field='backups',
)
validate.ValidateInstanceName(args.instance)
instance_ref = client.resource_parser.Parse(
args.instance,
params={'project': properties.VALUES.core.project.GetOrFail},
collection='sql.instances')
return list_pager.YieldFromList(
sql_client.backupRuns,
sql_messages.SqlBackupRunsListRequest(
project=instance_ref.project, instance=instance_ref.instance))

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.
"""Update the expiry time of the FINAL backup."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.sql import api_util
from googlecloudsdk.api_lib.sql import operations
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.sql import flags
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA
)
class Patch(base.UpdateCommand):
"""Update the Final backup of a Cloud SQL project."""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
flags.AddBackupName(parser)
update_group = parser.add_group(required=True)
flags.AddBackupDescription(update_group)
expiration_group = update_group.add_mutually_exclusive_group(required=False)
flags.AddBackupExpiryTime(expiration_group)
flags.AddBackupTtlDays(expiration_group)
def Run(self, args):
"""Update the Final backup of a Cloud SQL project.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the delete
operation if the api request was successful.
"""
client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
sql_client = client.sql_client
sql_messages = client.sql_messages
console_io.PromptContinue(
message='This backup will be updated.',
default=True,
cancel_on_no=True,
)
patch_backup = sql_messages.Backup(
name=args.name,
)
update_mask = None
if args.ttl_days is not None and args.ttl_days > 0:
patch_backup.ttlDays = args.ttl_days
update_mask = 'ttl_days'
if args.expiry_time is not None:
patch_backup.expiryTime = args.expiry_time.strftime(
'%Y-%m-%dT%H:%M:%S.%fZ')
update_mask = 'expiry_time'
if args.backup_description is not None:
patch_backup.description = args.backup_description
if update_mask is not None:
update_mask = update_mask + ','
update_mask = (update_mask if update_mask else '') + 'description'
request = sql_messages.SqlBackupsUpdateBackupRequest(
backup=patch_backup,
name=args.name,
updateMask=update_mask,
)
result = sql_client.backups.UpdateBackup(request)
operation_ref = client.resource_parser.Create(
'sql.operations', operation=result.name, project=args.name.split('/')[1]
)
operations.OperationsV1Beta4.WaitForOperation(
sql_client, operation_ref, 'Updating backup'
)
log.UpdatedResource(args.name)

View File

@@ -0,0 +1,259 @@
# -*- coding: utf-8 -*- #
# Copyright 2016 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 backup of a Cloud SQL instance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.sql import api_util
from googlecloudsdk.api_lib.sql import exceptions
from googlecloudsdk.api_lib.sql import operations
from googlecloudsdk.api_lib.sql import validate
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.sql import constants
from googlecloudsdk.command_lib.sql import flags
from googlecloudsdk.command_lib.sql import instances as command_util
from googlecloudsdk.command_lib.sql import validate as command_validate
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.console import console_io
def _ValidateBackupRequest(is_project_backup, args, overrides):
"""Validates the backup request.
Args:
is_project_backup: bool, Whether the backup request is for a project level
backup.
args: argparse.Namespace, The arguments that this command was invoked with.
overrides: list[str], The list of flags that were overridden.
"""
validate.ValidateInstanceName(args.restore_instance)
if command_validate.IsBackupDrBackupRequest(args.id) or is_project_backup:
if args.backup_project:
raise exceptions.ArgumentError(
' --backup-project is not supported when using backup name based'
' restore command.'
)
if args.backup_instance:
raise exceptions.ArgumentError(
' --backup-instance is not supported when using backup name based'
' restore command.'
)
else:
if overrides:
raise exceptions.ArgumentError(
'Overrides are only supported for backup name based restore to new'
f' instance. Unsupported flags: {overrides}'
)
def _GetRestoreBackupRequest(args, sql_messages, instance_ref):
"""Get the restore backup request.
Args:
args: argparse.Namespace, The arguments that this command was invoked with.
sql_messages: sql_v1beta4_messages.SqlMessagesV1Beta4, The SQL API messages.
instance_ref: base.ResourceParse, The parsed instance reference.
Returns:
A SqlInstancesRestoreBackupRequest.
"""
if command_validate.IsBackupDrBackupRequest(args.id):
return sql_messages.SqlInstancesRestoreBackupRequest(
project=instance_ref.project,
instance=instance_ref.instance,
instancesRestoreBackupRequest=sql_messages.InstancesRestoreBackupRequest(
backupdrBackup=args.id
),
)
else:
return sql_messages.SqlInstancesRestoreBackupRequest(
project=instance_ref.project,
instance=instance_ref.instance,
instancesRestoreBackupRequest=sql_messages.InstancesRestoreBackupRequest(
backup=args.id
),
)
@base.DefaultUniverseOnly
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA
)
class RestoreBackup(base.RestoreCommand):
"""Restores a backup of a Cloud SQL instance.
The command lets you restore to an existing instance using ID. To restore
using a backupDR backup, use the backupDR ID. When backup Name is used to
restore it lets you restore to an existing instance or a new instance. When
restoring to new instance, optional flags can be used to customize the new
instance.
"""
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
flags.AddBackupId(
parser,
help_text=(
'The ID of the backup run to restore from or the backup NAME for'
' restore to existing/new instance. To find the NAME, run the'
' following command:'
' $ gcloud sql backups list --filter=instance:{instance}'
),
)
parser.add_argument(
'--restore-instance',
required=True,
completer=flags.InstanceCompleter,
help=(
'The ID of the target Cloud SQL instance that the backup is '
'restored to.'
),
)
parser.add_argument(
'--backup-instance',
completer=flags.InstanceCompleter,
help=(
'The ID of the instance that the backup was taken from. This'
' argument must be specified when the backup instance is different'
' from the restore instance. If it is not specified, the backup'
' instance is considered the same as the restore instance. This'
' flag is not supported when restore happens from backup name, only'
' supported when restore happens from backup ID in timestamp'
' format.'
),
)
parser.add_argument(
'--backup-project',
help=(
'The project of the instance to which the backup belongs. If it'
" isn't specified, backup and restore instances are in the same"
' project. This flag is not supported when restore happens from'
' backup name, only supported when restore happens from backup ID'
' in timestamp format.'
),
)
base.ASYNC_FLAG.AddToParser(parser)
flags.AddSourceInstanceOverrideArgs(parser)
def Run(self, args):
"""Restores a backup of a Cloud SQL instance.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
A dict object representing the operations resource describing the
restoreBackup operation if the restoreBackup was successful.
"""
client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
sql_client = client.sql_client
sql_messages = client.sql_messages
specified_args_dict = getattr(args, '_specified_args', None)
overrides = [
key
for key in specified_args_dict
if key in constants.TARGET_INSTANCE_OVERRIDE_FLAGS
]
clears = [
key
for key in specified_args_dict
if key in constants.TARGET_INSTANCE_CLEAR_FLAGS
]
is_project_backup = command_validate.IsProjectLevelBackupRequest(args.id)
_ValidateBackupRequest(is_project_backup, args, overrides)
instance_ref = client.resource_parser.Parse(
args.restore_instance,
params={'project': properties.VALUES.core.project.GetOrFail},
collection='sql.instances',
)
if not console_io.PromptContinue(
'1. All current data on the instance will be lost when the backup is'
' restored to an existing instance.\n2. If restoring to a new instance,'
' settings will be applied from the backups unless they are overriden.'
):
return None
if is_project_backup:
restore_backup_request = _GetRestoreBackupRequest(
args, sql_messages, instance_ref
)
if overrides:
instance_resource = (
command_util.InstancesV1Beta4.ConstructCreateInstanceFromArgs(
sql_messages, args, instance_ref=instance_ref
)
)
restore_backup_request.instancesRestoreBackupRequest.restoreInstanceSettings = (
instance_resource
)
if clears:
restore_backup_request.instancesRestoreBackupRequest.restoreInstanceClearOverridesFieldNames = (
flags.GetInstanceClearOverrides(args)
)
result_operation = sql_client.instances.RestoreBackup(
restore_backup_request
)
else:
if not args.backup_instance:
args.backup_instance = args.restore_instance
backup_run_id = int(args.id)
result_operation = sql_client.instances.RestoreBackup(
sql_messages.SqlInstancesRestoreBackupRequest(
project=instance_ref.project,
instance=instance_ref.instance,
instancesRestoreBackupRequest=(
sql_messages.InstancesRestoreBackupRequest(
restoreBackupContext=sql_messages.RestoreBackupContext(
backupRunId=backup_run_id,
instanceId=args.backup_instance,
project=args.backup_project,
)
)
),
)
)
operation_ref = client.resource_parser.Create(
'sql.operations',
operation=result_operation.name,
project=instance_ref.project)
if args.async_:
return sql_client.operations.Get(
sql_messages.SqlOperationsGetRequest(
project=operation_ref.project,
operation=operation_ref.operation))
operations.OperationsV1Beta4.WaitForOperation(
sql_client, operation_ref, 'Restoring Cloud SQL instance')
log.status.write('Restored [{instance}].\n'.format(instance=instance_ref))
return None