1# -*- coding: utf-8 -*- #
2# Copyright 2013 Google LLC. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Restores a backup of a Cloud SQL instance."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import unicode_literals
20
21from googlecloudsdk.api_lib.sql import api_util
22from googlecloudsdk.api_lib.sql import operations
23from googlecloudsdk.api_lib.sql import validate
24from googlecloudsdk.calliope import base
25from googlecloudsdk.command_lib.sql import flags
26from googlecloudsdk.core import log
27from googlecloudsdk.core import properties
28from googlecloudsdk.core.console import console_io
29
30
31@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
32                    base.ReleaseTrack.ALPHA)
33class RestoreBackup(base.Command):
34  """Restores a backup of a Cloud SQL instance.
35
36  DEPRECATED: This command is deprecated and will be removed.
37  Use 'gcloud beta sql backups restore' instead.
38  """
39
40  @staticmethod
41  def Args(parser):
42    """Args is called by calliope to gather arguments for this command.
43
44    Args:
45      parser: An argparse parser that you can use to add arguments that go
46          on the command line after this command. Positional arguments are
47          allowed.
48    """
49    parser.add_argument(
50        'instance',
51        completer=flags.InstanceCompleter,
52        help='Cloud SQL instance ID that will be restored.')
53    parser.add_argument(
54        '--backup-id',
55        type=int,
56        help='The ID of the backup run to restore from.')
57    parser.add_argument(
58        '--backup-instance',
59        completer=flags.InstanceCompleter,
60        help='The ID of the instance that the backup was taken from.')
61    base.ASYNC_FLAG.AddToParser(parser)
62
63  def Run(self, args):
64    """Restores a backup of a Cloud SQL instance.
65
66    Args:
67      args: argparse.Namespace, The arguments that this command was invoked
68          with.
69
70    Returns:
71      A dict object representing the operations resource describing the
72      restoreBackup operation if the restoreBackup was successful.
73    """
74    validate.ValidateInstanceName(args.instance)
75    console_io.PromptContinue(
76        message=('All current data on the instance will be lost when the '
77                 'backup is restored'),
78        default=True,
79        cancel_on_no=True)
80
81    return self._HandleBackupId(args)
82
83  def _HandleBackupId(self, args):
84    """Restores a backup using v1beta4. The backup is specified with backup_id.
85
86    Args:
87      args: argparse.Namespace, The arguments that this command was invoked
88          with.
89
90    Returns:
91      A dict object representing the operations resource describing the
92      restoreBackup operation if the restoreBackup was successful.
93    """
94    client = api_util.SqlClient(api_util.API_VERSION_DEFAULT)
95    sql_client = client.sql_client
96    sql_messages = client.sql_messages
97
98    instance_ref = client.resource_parser.Parse(
99        args.instance,
100        params={'project': properties.VALUES.core.project.GetOrFail},
101        collection='sql.instances')
102
103    if not args.backup_instance:
104      args.backup_instance = args.instance
105
106    result_operation = sql_client.instances.RestoreBackup(
107        sql_messages.SqlInstancesRestoreBackupRequest(
108            project=instance_ref.project,
109            instance=instance_ref.instance,
110            instancesRestoreBackupRequest=(
111                sql_messages.InstancesRestoreBackupRequest(
112                    restoreBackupContext=sql_messages.RestoreBackupContext(
113                        backupRunId=args.backup_id,
114                        instanceId=args.backup_instance,)))))
115
116    operation_ref = client.resource_parser.Create(
117        'sql.operations',
118        operation=result_operation.name,
119        project=instance_ref.project)
120
121    if args.async_:
122      return sql_client.operations.Get(
123          sql_messages.SqlOperationsGetRequest(
124              project=operation_ref.project, operation=operation_ref.operation))
125
126    # TODO(b/37302484): Use standard gcloud poller instead of WaitForOperation
127    operations.OperationsV1Beta4.WaitForOperation(
128        sql_client, operation_ref, 'Restoring Cloud SQL instance')
129
130    log.status.write('Restored [{instance}].\n'.format(instance=instance_ref))
131
132    return None
133