
    >                        d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm	Z	 dd	l
mZ dd
lmZ ddlmZ ddlmZ ddlm	Z ddlmZ ddlmZ ddlmZ dZdZd Zd Zd Zd Zej>                   ej@                  ejB                  jD                  ejB                  jF                  ejB                  jH                         G d dejJ                                      Z&y)z*Restores a backup of a Cloud SQL instance.    )absolute_import)division)unicode_literals)api_util)
exceptions)
operations)validate)base)resource_args)flags)	instances)log)
properties)
console_ioi  )@activation_policyactive_directory_dns_serversactive_directory_domainactive_directory_mode$active_directory_organizational_unit#active_directory_secret_manager_key	assign_ipauthorized_networksavailability_typebackupbackup_start_timebackup_location"clear_active_directory_dns_serverscpu	collationenable_bin_logretained_backups_countretained_transaction_log_daysfailover_replica_namemaintenance_release_channelmaintenance_window_daymaintenance_window_hour"deny_maintenance_period_start_date deny_maintenance_period_end_datedeny_maintenance_period_time&insights_config_query_insights_enabled#insights_config_query_string_length'insights_config_record_application_tags%insights_config_record_client_address&insights_config_query_plans_per_minutememoryrequire_sslstorage_auto_increasestorage_sizestorage_provisioned_iopsstorage_provisioned_throughputstorage_typetiereditionenable_point_in_time_recoverynetworkclear_networkaudit_bucket_pathdeletion_protection	time_zoneconnector_enforcementtimeoutenable_google_private_pathenable_data_cacheenable_private_service_connectallowed_psc_projectsssl_modeenable_google_ml_integrationdatabase_versiondisk_encryption_keydisk_encryption_key_keyringdisk_encryption_key_locationdisk_encryption_key_projectpsc_auto_connectionsserver_ca_moderegionretain_backups_on_deletefinal_backupfinal_backup_retention_daysc                 >   | j                   j                  t        j                                t        j                  |        t        j
                  |        t        j                  |        t        j                  |        t        j                  |        t        j                  |        t        j                  |        t        j                  | d       t        j                  |        t        j                  |        t        j                  |        t        j                  |        t        j                   |        t        j"                  |        t        j$                  |        t        j&                  |        t        j(                  |        t        j*                  |        t        j,                  |        t        j.                  |        t        j0                  |        t        j2                  |        t        j4                  |        t        j6                  |        t        j8                  |        t        j:                  |        t        j<                  |        t        j>                  |        t        j@                  |        t        jB                  |        t        jD                  |        t        jF                  |        t        jH                  |        ddddd}tK        jL                  | d|	       t        jN                  |        t        jP                  |        t        jR                  |        t        jT                  |        t        jV                  |        t        jX                  |        t        jZ                  |        t        j\                  | t^               t        j`                  | d
       t        jb                  | d       | je                         }t        jf                  |       t        jh                  |       t        jj                  | d       t        jl                  |        t        jn                  | d       t        jp                  | d       t        jr                  | dd       t        jt                  | dddd       t        jv                  | d       t        jx                  | d       t        jz                  | d       t        j|                  |        t        j~                  |        t        j                  | d       t        j                  | d       t        j                  | d       t        j                  | d       t        j                  | d       t        j                  | d       y)z#Declare flag for instance settings.F)allow_emptyz--disk-encryption-keyz--disk-encryption-key-keyringz--disk-encryption-key-locationz--disk-encryption-key-project)zkms-keyzkms-keyringzkms-locationzkms-projectinstance)flag_overrides)show_negated_in_helpT)hidden)rV   specify_default_regionzt Note for restore to new instance major version upgrades are not supported. Only minor version upgrades are allowed.)restrict_choicesrV   support_default_versionadditional_help_textN)Fdisplay_info	AddFormatr   GetInstanceListFormatAddActivationPolicyAddActiveDirectoryDomainAddAssignIpAddAuthorizedNetworksAddAvailabilityType	AddBackupAddBackupStartTimeAddBackupLocationAddCPUAddInstanceCollationAddEnableBinLogAddRetainedBackupsCountAddRetainedTransactionLogDaysAddMaintenanceReleaseChannelAddMaintenanceWindowDayAddMaintenanceWindowHour!AddDenyMaintenancePeriodStartDateAddDenyMaintenancePeriodEndDateAddDenyMaintenancePeriodTime%AddInsightsConfigQueryInsightsEnabled"AddInsightsConfigQueryStringLength&AddInsightsConfigRecordApplicationTags$AddInsightsConfigRecordClientAddress$AddInsightsConfigQueryPlansPerMinute	AddMemoryAddRequireSslAddStorageAutoIncreaseAddStorageSizeAddStorageProvisionedIopsAddStorageProvisionedThroughputAddStorageTypeAddTier
AddEditionkms_resource_argsAddKmsKeyResourceArgAddEnablePointInTimeRecovery
AddNetworkAddClearNetworkAddSqlServerAuditAddDeletionProtectionAddSqlServerTimeZoneAddConnectorEnforcement
AddTimeout"_INSTANCE_CREATION_TIMEOUT_SECONDSAddEnableGooglePrivatePathAddEnableDataCache	add_groupAddEnablePrivateServiceConnectAddAllowedPscProjectsAddPscAutoConnections
AddSslModeAddEnableGoogleMLIntegrationAddEnableDataplexIntegrationAddLocationGroupAddDatabaseVersionAddServerCaModeAddTagsAddRetainBackupsOnDeleteAddFinalBackupAddFinalbackupRetentionDaysAddActiveDirectoryMode"AddActiveDirectorySecretManagerKey$AddActiveDirectoryOrganizationalUnitAddActiveDirectoryDNSServersClearActiveDirectoryDNSServersAddClearActiveDirectory)parserkms_flag_overridespsc_setup_groups      "lib/surface/sql/backups/restore.pyAddInstanceSettingsArgsr   j   s    ; ; =>F#  (Ff%F#//&6"&e4,,vV$'%%f-$$V,'  ())&1''/$$V,--f5**62..v6,,V4,,V4//&fv&v!!&)''/v--6(464	 ((j); $$V,6&!f%V$'6=>""6F6$/$$&/&&7o.fT26$$VD9$$VD9eL#A	 t,--t$  5v##F+vd3**6$?,,VDA$$VD9&&vd;t4    c                 >   t        j                  |j                         t        j                  |j
                        s| rC|j                  rt        j                  d      |j                  rt        j                  d      y|rt        j                  d|       y)a  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.
  zP --backup-project is not supported when using backup name based restore command.zQ --backup-instance is not supported when using backup name based restore command.z_Overrides are only supported for backup name based restore to new instance. Unsupported flags: N)
r	   ValidateInstanceNamerestore_instancecommand_validateIsBackupDrBackupRequestidbackup_projectr   ArgumentErrorbackup_instance)is_project_backupargs	overridess      r   _ValidateBackupRequestr      s      5 56--dgg6:K$$ 
 $$   $$++4+7  r   c                 H   t        j                  | j                        rB|j                  |j                  |j
                  |j                  | j                              S |j                  |j                  |j
                  |j                  | j                              S )aE  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.
  )backupdrBackupprojectrS   instancesRestoreBackupRequest)r   )r   r   r    SqlInstancesRestoreBackupRequestr   rS   InstancesRestoreBackupRequest)r   sql_messagesinstance_refs      r   _GetRestoreBackupRequestr      s     --dgg688$$&&&2&P&P77 'Q '
 9   88$$&&&2&P&P77 'Q '
 9  r   c                    g }| j                  d      r|j                  d       | j                  r|j                  d       | j                  d      r|j                  d       | j                  r|j                  d       |S )zGet the database instance clear overrides.

  Args:
    args: argparse.Namespace, The arguments that this command was invoked with.

  Returns:
    An array with the database instance fields that should be cleared.
  r:   z)settings.ip_configuration.private_networkz,settings.active_directory_config.dns_serversclear_disk_encryptiondisk_encryption_configz settings.active_directory_config)IsKnownAndSpecifiedappendr   clear_active_directory)r   cleared_fieldss     r   !_GetRestoreInstanceClearOverridesr      sz     .	o.EF	,,HI	5623	  <=	r   c                   &    e Zd ZdZed        Zd Zy)RestoreBackupam  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.
  c                 ^   t        j                  | d       | j                  ddt         j                  d       | j                  dt         j                  d	       | j                  d
d       | j                  ddd       t        j
                  j                  |        t        |        y)zArgs 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.
    zThe 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})	help_textz--restore-instanceTzGThe ID of the target Cloud SQL instance that the backup is restored to.)required	completerhelpz--backup-instancea}  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.)r   r   z--backup-projecta  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.)r   z--clear-disk-encryptionFz'Disables CMEK in the restored instance.)r   r   N)r   AddBackupIdadd_argumentInstanceCompleterr
   
ASYNC_FLAGAddToParserr   )r   s    r   ArgszRestoreBackup.Args#  s     
F ))   ))	   $  	 !5	   	OO'F#r   c                    t        j                  t         j                        }|j                  }|j                  }t        |dd      }|D cg c]  }|t        v s| }}t        j                  |j                        }t        |||       |j                  j                  |j                  dt        j                  j                   j"                  j$                  id      }	t'        j(                  d      sy|rxt+        |||	      }
|rMt,        j.                  j1                  |||	      }||
j2                  _        t7        |      |
j2                  _        |j:                  j=                  |
      }n|j>                  s|j                  |_        tA        |j                        }|j:                  j=                  |jC                  |	j"                  |	jD                  |jG                  |jI                  ||j>                  |jJ                        	      
            }|j                  jM                  d|jN                  |	j"                        }|jP                  r@|jR                  jU                  |jW                  |j"                  |jX                              S tR        jZ                  j]                  ||d       t^        j`                  jc                  dje                  |	             yc c}w )a/  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.
    _specified_argsNr   zsql.instances)params
collectionz1. All current data on the instance will be lost when the backup is restored to an existing instance.
2. If restoring to a new instance, settings will be applied from the backups unless they are overriden.)r   )backupRunId
instanceIdr   )restoreBackupContextr   zsql.operations)	operationr   )r   r   zRestoring Cloud SQL instancezRestored [{instance}].
)rS   )3r   	SqlClientAPI_VERSION_DEFAULT
sql_clientr   getattrOVERRIDE_FLAGS_SETr   IsProjectLevelBackupRequestr   r   resource_parserParser   r   VALUEScorer   	GetOrFailr   PromptContinuer   command_utilInstancesV1Beta4ConstructCreateInstanceFromArgsr   restoreInstanceSettingsr   'restoreInstanceClearOverridesFieldNamesr   r   r   intr   rS   r   RestoreBackupContextr   Createnameasync_r   GetSqlOperationsGetRequestr   OperationsV1Beta4WaitForOperationr   statuswriteformat)selfr   clientr   r   specified_args_dictkeyr   r   r   restore_backup_requestinstance_resourceresult_operationbackup_run_idoperation_refs                  r   RunzRestoreBackup.Run^  s     < <=F""J&&L!$(94@**c5G.G*   )DD ,dI>))//:,,1199CCD" 0 L
 $$	P
 7
l  
))IId J  	  	<<T .d3 	<<d $--;;
  !!#44$''lm#--;;

7
7"**#,,<<+7+L+L&3%)%9%9"&"5"5 ,M , = 	 8   **11"''$$ 2 &M
 {{""&&

.
.#++%// / 12 2
   11M#AC JJ/666MNYs   K+K+N)__name__
__module____qualname____doc__staticmethodr   r    r   r   r   r     s"    
 8$ 8$t]r   r   N)'r  
__future__r   r   r   googlecloudsdk.api_lib.sqlr   r   r   r	   googlecloudsdk.callioper
   googlecloudsdk.command_lib.kmsr   r   googlecloudsdk.command_lib.sqlr   r   r   r   googlecloudsdk.corer   r   googlecloudsdk.core.consoler   r   r   r   r   r   r   DefaultUniverseOnlyReleaseTracksReleaseTrackGABETAALPHARestoreCommandr   r  r   r   <module>r     s    1 &  ' / 1 1 / ( M 0 D G # * 2 &* "A HS5l<:4 $++00$2C2C2I2IbD'' b br   