
                            d Z ddlmZ ddlmZ ddlmZ ddlZddl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Z	 	 	 	 	 d%dZ	 	 	 d&dZ	 	 	 	 	 	 	 	 	 d'dZ	 	 	 d(dZd)dZ	 	 	 d&dZ	 	 	 d*dZd Zd Z	 	 	 	 	 d%dZd)dZ	 	 	 	 d+dZ 	 	 	 	 	 	 	 	 d,dZ!d Z"d+dZ#d Z$d Z%	 	 	 d&dZ&d)dZ'd  Z(	 	 	 	 	 	 	 d-d!Z)	 d)d"Z*d.d#Z+	 	 	 d&d$Z,y)/zHReducer functions to generate instance props from prior state and flags.    )absolute_import)division)unicode_literalsN)api_util)	constants)
exceptions)	instances)arg_parsers)
properties)filesc                    t        |du|du|du|du|dug      }|sy| j                         }|||_        |||_        |8| j                  j                  j                  |j                               |_        |r||_        |||_	        |S )a  Generates the Active Directory configuration for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    domain: string, the Active Directory domain value.
    mode: string, the Active Directory mode value.
    dns_servers: list of strings, the list of dns servers.
    admin_credential_secret_key: string, the name of the admin credential secret
      manager key.
    organizational_unit: string, the organizational unit value.

  Returns:
    sql_messages.SqlActiveDirectoryConfig object.
  N)
anySqlActiveDirectoryConfigdomainadminCredentialSecretNameModeValueValuesEnumlookup_by_nameuppermode
dnsServersorganizationalUnit)sql_messagesr   r   dns_serversadmin_credential_secret_keyorganizational_unitshould_generate_configconfigs           8lib/googlecloudsdk/api_lib/sql/instance_prop_reducers.pyActiveDirectoryConfigr   $   s    . D
$!-%   
 002&FM ,'BF$	77KKZZ

FK #F$ 3F	-    c                     |||y| j                         }|||_        |t        j                  |      dz   |_        |t        j                  |      dz   |_        |S )ay  Generates the Audit configuration for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    bucket: string, the GCS bucket name.
    retention_interval: duration, how long to keep generated audit files.
    upload_interval: duration, how often to upload generated audit files.

  Returns:
    sql_messages.SqlServerAuditConfig object.
  Ns)SqlServerAuditConfigbucketsix	text_typeretentionIntervaluploadInterval)r   r$   retention_intervalupload_intervalr   s        r   r#   r#   U   sp      ^*27N,,.&FM#"}}-?@3FF MM/:S@F	-r    c
           	      `   t        |du||du|du|du|du| g      }
|
sy|r|j                  j                  s| j                  dd|      }n|j                  j                  }|j                  | j                  j
                  j                  k(  }|	r|rt        j                  d      |||_	        d|_
        |r||_        d|_
        |X|j                  xs | j                         }| j                  j                  j                  |_        ||_        ||_        d|_
        |||_        d|_
        |s$||s||t        j                  d      d|_
        |||_        |||_        |j*                  ||_        |r-|j&                  s!|j(                  st        j                  d	      |S )
a  Generates the backup configuration for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    instance: sql_messages.DatabaseInstance, the original instance, if the
      previous state is needed.
    backup_enabled: boolean, True if backup should be enabled.
    backup_location: string, location where to store backups by default.
    backup_start_time: string, start time of backup specified in 24-hour format.
    enable_bin_log: boolean, True if binary logging should be enabled.
    enable_point_in_time_recovery: boolean, True if point-in-time recovery
      (using write-ahead log archiving) should be enabled.
    retained_backups_count: int, how many backups to keep stored.
    retained_transaction_log_days: int, how many days of transaction logs to
      keep stored.
    patch_request: boolean, True if this is a patch request.

  Returns:
    sql_messages.BackupConfiguration object, or None

  Raises:
    ToolException: Bad combination of arguments.
  Nzsql#backupConfigurationz00:00)kind	startTimeenabledzZBackup configuration cannot be changed for instances with a BackupDR backup plan attached.TzArgument --no-backup not allowed with --backup-location, --backup-start-time, --retained-backups-count, or --retained-transaction-log-daysFzArgument --retained-transaction-log-days only valid when transaction logs are enabled. To enable transaction logs, use --enable-bin-log for MySQL, and use --enable-point-in-time-recovery for Postgres and SQL Server.)r   settingsbackupConfigurationBackupConfiguration
backupTierBackupTierValueValuesEnumENHANCEDsql_exceptionsArgumentErrorlocationr.   r-   backupRetentionSettingsBackupRetentionSettingsRetentionUnitValueValuesEnumCOUNTretentionUnitretainedBackupstransactionLogRetentionDaysbinaryLogEnabledpointInTimeRecoveryEnabledreplicationLogArchivingEnabled)r   instancebackup_enabledbackup_locationbackup_start_timeenable_bin_logenable_point_in_time_recoveryretained_backups_countretained_transaction_log_dayspatch_requestr   backup_configgcbdr_managedbackup_retention_settingss                 r   r1   r1   s   s   F T!D #4/D(#4/
   
 	**>> 44& 5  M
 %%99M 		)	)	C	C	L	LM 
 }

&
&	! 
  ,M M/M M'-- 	/,,.  /;.R.R.o.o.u.u+0F-,EM) M".0MM- M	#'8*%1((,- - "M%3M""./LM,33?
' 2 $,,66

&
&	'  
r    c                     g }|rEt        |j                               D ]'  \  }}|j                  | j                  ||             ) |S |rg }|S |r|j                  }|S )a  Generates the database flags for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    settings: sql_messages.Settings, the original settings, if the previous
      state is needed.
    database_flags: dict of flags.
    clear_database_flags: boolean, True if flags should be cleared.

  Returns:
    list of sql_messages.DatabaseFlags objects
  namevalue)sorteditemsappendDatabaseFlagsdatabaseFlags)r   r/   database_flagsclear_database_flagsupdated_flagsrP   rQ   s          r   rU   rU      sv      - 4 4 67u<554u5MN 8 
 M 
 **M	r    c                 ^    g }|r(|D ]#  }|j                  | j                  |             % |S )zGenerates the tags for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    tags: list of tags.

  Returns:
    list of sql_messages.Tags objects
  )tag)rT   Tags)r   tagsupdated_tagsr[   s       r   r\   r\     s:     ,	,+++45  
r    c                 4   |}|}|}t        |||g      sy| j                  d      }|r"|j                  r|j                  j                  s||||t	        j
                  dd      |rj| j                  j                  j                  | j                  j                  j                  | j                  j                  j                  d}	|	|   |_
        |r7t        j                  j                  j                  |      }
|
dk(  rd}
|
|_        |||_        |S )aU  Generates the maintenance window for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    instance: sql_messages.DatabaseInstance, The original instance, if it might
      be needed to generate the maintenance window.
    maintenance_release_channel: string, which channel's updates to apply.
    maintenance_window_day: string, maintenance window day of week.
    maintenance_window_hour: int, maintenance window hour of day.

  Returns:
    sql_messages.MaintenanceWindow or None

  Raises:
    argparse.ArgumentError: no maintenance window specified.
  Nzsql#maintenanceWindow)r,   zlThere is currently no maintenance window on the instance. To add one, specify values for both day, and hour.)week5
productionpreviewr      )r   MaintenanceWindowr/   maintenanceWindowargparser6   UpdateTrackValueValuesEnumr`   stablecanaryupdateTrackr
   	DayOfWeekDAYSindexdayhour)r   rB   maintenance_release_channelmaintenance_window_daymaintenance_window_hourchannelrn   ro   maintenance_windownamesday_nums              r   rd   rd     s/   * ('#	 $	gsD!	"#55" 6 $
 (++



-
-	)	#/""
 ?@ @  **EEKK**EELL**EELLE &+7^"##((..s3G!|g$	"	r    c                    d}|rT|j                   rH|j                   j                  r2|j                   j                  d   r|j                   j                  d   }| j                         }|r@|}|rt        |       ||_        |rt        |       ||_        |rt        |       ||_        |S |r|st        j                  dd      t        |       ||_        t        |       ||_        |rt        |       ||_        |S )a  Generates the deny maintenance period for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    instance: sql_messages.DatabaseInstance, The original instance, if it might
      be needed to generate the deny maintenance period.
    deny_maintenance_period_start_date: date, Date when the deny maintenance
      period begins, i.e., 2020-11-01.
    deny_maintenance_period_end_date: date, Date when the deny maintenance
      period ends, i.e., 2021-01-10.
    deny_maintenance_period_time: Time when the deny maintenance period
      starts/ends, i.e., 05:00:00.

  Returns:
    sql_messages.DenyMaintenancePeriod or None

  Raises:
    argparse.ArgumentError: invalid deny maintenance period specified.
  Nr   zqThere is no deny maintenance period on the instance. To add one, specify values for both start date and end date.)
r/   denyMaintenancePeriodsDenyMaintenancePeriodValidateDate	startDateendDate	ValidTimetimerf   r6   )r   rB   "deny_maintenance_period_start_date deny_maintenance_period_end_datedeny_maintenance_period_timeold_deny_maintenance_perioddeny_maintenance_periods          r   ry   ry   \  s   0 !%8$$....q1"*"3"3"J"J1"M(>>@ 9)56*L''34(H%#,-%A"" 
!  /,""
 JK K 34(J%12&F##,-%A"	  r    c                     	 t         j                   j                  | d       y # t        $ r t        j                  d d      w xY w)Nz%H:%M:%Sz2Invalid time value. The format should be HH:mm:SS.datetimestrptime
ValueErrorrf   r6   r"   s    r   r}   r}     sJ    Dq*-	 D

 
 BD DDs	    #  Ac                     	 t         j                   j                  | d      S # t        $ rG 	 t         j                   j                  | d      cY S # t        $ r t        j                  d d      w xY ww xY w)Nz%Y-%m-%dz%m-%dz=Invalid date value. The format should be yyyy-mm-dd or mm-dd.r   r   s    r   rz   rz     s}    Q%%a44	 QQ''733 Q""
OQ QQQs    " 	A2AA2 A..A2c                     t        |du|du|du|du|dug      }|sy| j                         }|||_        |||_        |||_        |||_        |||_        |S )a  Generates the insights config for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    insights_config_query_insights_enabled: boolean, True if query insights
      should be enabled.
    insights_config_query_string_length: number, length of the query string to
      be stored.
    insights_config_record_application_tags: boolean, True if application tags
      should be recorded.
    insights_config_record_client_address: boolean, True if client address
      should be recorded.
    insights_config_query_plans_per_minute: number, number of query plans to
      sample every minute.

  Returns:
    sql_messages.InsightsConfig or None
  N)r   InsightsConfigqueryInsightsEnabledqueryStringLengthrecordApplicationTagsrecordClientAddressqueryPlansPerMinute)r   &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_minuter   insights_configs           r   r   r     s    2 ,D8)5-T9+47,D8   
  !//1/+7. ((4(KO%,8/ )*6*OO'+7*PO'	r    c                 ,    |y| j                  |      S )z?Generates the db aligned atomic writes Config for the instance.N)dbAlignedAtomicWrites)DbAlignedAtomicWritesConfig)r   db_aligned_atomic_writess     r   r   r     s&    %		1	14 
2 
 r    c                    t        |du |du |du g      ry|xs | j                         }|||_        |Ng }t        |j	                               D ]'  \  }}|j                  | j                  ||             ) ||_        |S |rg |_        |S )z9Generates the connection pooling config for the instance.NrO   )allConnectionPoolConfigconnectionPoolingEnabledrR   rS   rT   ConnectionPoolFlagsflags)	r   enable_connection_poolingconnection_pool_flagsclear_connection_pool_flagscurrent_configconnection_pool_configrY   rP   rQ   s	            r   r   r     s     	4't#!T)
 
 )P\-N-N-P*6O3&M399;<e

*
*E
*
B = $1  
  ##% 	r    c	           
         t        |du |du |du |du |du |du |du g      ry|xs | j                         }	||rd|	_        n| j                  d      S |||	_        |||	_        |Kg |	_        |j                         D ]1  \  }
}|	j
                  j                  | j                  |
|             3 |||	_	        |||	_
        |||	_        |	S )z;Generates the read pool auto-scale config for the instance.NTF)r.   )metrictargetValue)r   ReadPoolAutoScaleConfigr.   minNodeCountmaxNodeCounttargetMetricsrS   rT   TargetMetricdisableScaleInscaleInCooldownSecondsscaleOutCooldownSeconds)r   auto_scale_enabledauto_scale_min_node_countauto_scale_max_node_countauto_scale_target_metricsauto_scale_disable_scale_inauto_scale_in_cooldown_secondsauto_scale_out_cooldown_secondsr   read_pool_auto_scale_configr   rQ   s               r   r   r     sC    	D 4'4'4'!T)$,%-
  ><<>  #,0!) 11%1@@*/H,*/H,*02- 
#	(	(	*	!//66

#
# $  
+ !,1L.#/&  6 %0'  7 
%$r    c                 *    dj                  | |      }|S )a/  Creates a custom machine type from the CPU and memory specs.

  Args:
    cpu: the number of cpu desired for the custom machine type
    memory_mib: the amount of ram desired in MiB for the custom machine type
      instance

  Returns:
    The custom machine type name for the 'instance create' call
  zdb-custom-{0}-{1})format)cpu
memory_mibmachine_types      r   _CustomMachineTypeStringr   L  s     %++C<,	r    c                     d}|r|}|s|rY|st        j                  dd      |st        j                  dd      |rt        j                  dd      t        ||dz        }|}|s| st        j
                  }|S )a  Generates the machine type for the instance.

  Adapted from compute.

  Args:
    instance: sql_messages.DatabaseInstance, The original instance, if it might
      be needed to generate the machine type.
    tier: string, the v1 or v2 tier.
    memory: string, the amount of memory.
    cpu: int, the number of CPUs.

  Returns:
    A string representing the URL naming a machine-type.

  Raises:
    exceptions.RequiredArgumentException when only one of the two custom
        machine type flags are used, or when none of the flags are used.
    exceptions.InvalidArgumentException when both the tier and
        custom machine type flags are used to generate a new instance.
  Nz--cpuzQBoth [--cpu] and [--memory] must be set to create a custom machine type instance.z--memoryz--tierzFCannot set both [--tier] and [--cpu]/[--memory] for the same instance.i   )r   RequiredArgumentExceptionInvalidArgumentExceptionr   r   DEFAULT_MACHINE_TYPE)rB   tiermemoryr   r   custom_type_strings         r   MachineTyper   [  s    . ,	L 	F00
 :; ; 00
 => > //
 67 7 25 &L 
h11L	r    c                 H    | j                  ddj                  ||            S )a[  Generates the external primary configuration for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    source_ip_address: string, the IP address of the external data source.
    source_port: number, the port number of the external data source.

  Returns:
    sql_messages.OnPremisesConfiguration object.
  zsql#onPremisesConfigurationz{0}:{1})r,   hostPort)OnPremisesConfigurationr   )r   source_ip_addresssource_ports      r   r   r     s2     
	-	-( 1;? 
. 
A Ar    c                     t        j                  t         j                        }|j                  j	                  | dt
        j                  j                  j                  j                  id      }|j                         S )zGenerates the self-link of the instance's private network.

  Args:
    network: The ID of the network.

  Returns:
    string, the URL of the network.
  projectcompute.networks)params
collection)common_api_util	SqlClientAPI_VERSION_DEFAULTresource_parserParser   VALUEScorer   	GetOrFailSelfLink)networkclientnetwork_refs      r   PrivateNetworkUrlr     sp     $$_%H%HI&&&,,
Z&&++33== $ - %+ 
			r    c                    | j                  d|||j                               }|rt        j                  |      |_        |rt        j                  |      |_        |rt        j                  |      |_        | j                  d|      S )a  Generates the config for an external primary replica.

  Args:
    sql_messages: module, The messages module that should be used.
    primary_username: The username for connecting to the external instance.
    primary_password: The password for connecting to the external instance.
    primary_dump_file_path: ObjectReference, a wrapper for the URI of the Cloud
      Storage path containing the dumpfile to seed the replica with.
    primary_ca_certificate_path: The path to the CA certificate PEM file.
    client_certificate_path: The path to the client certificate PEM file.
    client_key_path: The path to the client private key PEM file.

  Returns:
    sql_messages.MySqlReplicaConfiguration object.
  zsql#mysqlReplicaConfiguration)r,   usernamepassworddumpFilePathz)sql#demoteMasterMysqlReplicaConfiguration)r,   mysqlReplicaConfiguration)MySqlReplicaConfigurationToUrlr   ReadFileContentscaCertificateclientCertificate	clientKeyReplicaConfiguration)r   primary_usernameprimary_passwordprimary_dump_file_pathprimary_ca_certificate_pathclient_certificate_pathclient_key_pathmysql_replica_configurations           r   r   r     s    , !- F F*)//1	 !G !3
 !050F0F#1%-494J4J5!1,1,B,B-)		*	*6 ; 
+ 
= =r    c                     |rF|rDt        j                  |      }t        j                  |      }||k7  rt        j                  d      |rt        j                  |      }|S | S )aI  Generates the region string for the instance.

  Args:
    specified_region: string, the GCE region to create the instance in.
    gce_zone: string, the GCE zone to create the instance in.
    secondary_zone: string, the GCE zone to create the standby instance in.

  Returns:
    string, the region to create the instance in.
  zKZones in arguments --zone and --secondary-zone belong to different regions.)r   GetRegionFromZoner   ConflictingArgumentsException)specified_regiongce_zonesecondary_zoneregion_from_zoneregion_from_secondary_zonederived_regions         r   Regionr     sm     .11(;!)!;!;N!K5544)* * //9N	r    c                 n    |r3| j                   j                  j                  |j                               S y N)PasswordValidationPolicyComplexityValueValuesEnumr   r   )r   
complexitys     r   _ParseComplexityr    s3    00JJYY 	r    c           	         t        |du|du|du|du|du|dug      }|r|ry| j                         }	|||	_        |t        | |      |	_        |||	_        |||	_        |t        |      dz   |	_        |||	_	        |	S )aD  Generates or clears password policy for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    password_policy_min_length: int, Minimum number of characters allowed.
    password_policy_complexity: string, The complexity of the password.
    password_policy_reuse_interval: int, Number of previous passwords that
      cannot be reused.
    password_policy_disallow_username_substring: boolean, True if disallow
      username as a part of the password.
    password_policy_password_change_interval: duration, Minimum interval at
      which password can be changed.
    enable_password_policy: boolean, True if password validation policy is
      enabled.
    clear_password_policy: boolean, True if clear existing password policy.

  Returns:
    sql_messages.PasswordValidationPolicy or None
  Nr"   )
r   r   	minLengthr  r   reuseIntervaldisallowUsernameSubstringstrpasswordChangeIntervalenablePasswordPolicy)
r   password_policy_min_lengthpassword_policy_complexitypassword_policy_reuse_interval+password_policy_disallow_username_substring(password_policy_password_change_intervalenable_password_policyclear_password_policyshould_generate_policypassword_policys
             r   PasswordPolicyr    s    :  , ,$D01=.d:D(   
 #8 !99;/+ :O+!1,2L"NO#/$BO!0<0[O--9-00.247.8O*'+AO(	r    c                    g }|D ]  }| j                         }|j                  d      |_        |j                  d      x}r||_        n[t	        j
                  t        j                        }|j                  j                  |j                  d      }|j                  |_        |j                  r|j                  r|j                  |       t        j                  dd       |S )a~  Generates PSC auto connections for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    psc_auto_connections: dict of the allowed consumer projects and networks.

  Returns:
    list of sql_messages.PscAutoConnectionConfig objects

  Raises:
    exceptions.InvalidArgumentException when there is no valid network or
    project specified.
  r   r   r   )r   z--psc-auto-connectionsz0PSC auto connection must have network specified.)PscAutoConnectionConfiggetconsumerNetworkconsumerProjectr   r   r   r   ParseRelativeNamer   rT   r   r   )r   psc_auto_connectionsupdated_psc_auto_connections
connectioncurrent_psc_auto_connectionr   r   r   s           r   PscAutoConnectionsr  ;  s    " "$(j"."F"F"H2<..2K/..++w+4;!1(()L)LMf**<<
%
5
5' = k 5@4G4G!1 	$33'77"))*EF//
" % ) )0 
&%r    c                    g }|r|D ]  }	 |j                  dd      \  }}|j                  dd      \  }}|j                  | j                  ||| j                  j                  j                  |j                                             |S |rg }|S # t        $ r}	t        d      |	d}	~	wt        $ r}	t        d      |	d}	~	ww xY w)a2  Generates the database flags for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    unc_mappings: input unc mappings from the user.
    clear_unc_mappings: boolean, True if unc mappings should be cleared.

  Returns:
    list of sql_messages.UncMapping objects
  :   =)uncPathgcsPathr   z=Invalid UNC mapping input. Expected 'unc-path=gcs-path:mode'.Nz;Invalid mode. Expected 'snapshot_read' or 'snapshot_write'.)	rsplitsplitrT   
UncMappingr   r   r   r   KeyError)
r   unc_mappingsclear_unc_mappingsupdated_mappingsmapping_strrestmode_strunc_pathgcs_pathes
             r   UncMappingsr1  h  s     #$++C3h!ZZQ/(##  !,,@@OONN$ $ 	
	 $0 
 	  K
	  I
	s$   A>B	CB((C4C  Cc                 *   t        |du|dug      }|sy||s|t        j                  d      |r|j                  j                  s| j                         }n|j                  j                  }|||_        |||_        d|_        |	|sd|_        |S )a   Generates the Final Backup configuration for the instance.

  Args:
    sql_messages: module, The messages module that should be used.
    instance: sql_messages.DatabaseInstance, the original instance, if the
      previous state is needed.
    final_backup_enabled: boolean, True if final backup should be enabled.
    final_backup_retention_days: int, how many days to retain the final backup.

  Returns:
    sql_messages.FinalBackupConfiguration object, or None

  Raises:
    sql_exceptions.ArgumentError: Bad combination of arguments.
  NzPYou cannot set final-backup-retention-days while final-backup field is disabled.T)r   r5   r6   r/   finalBackupConfigFinalBackupConfigr.   retentionDays)r   rB   final_backup_enabledfinal_backup_retention_daysr   final_backup_configs         r   FinalBackupConfigurationr9    s    * $&!-  
 
  %.B".((
\  
**<<&88:"++== %"6 ,(C%"& %.B(,%	r    )NNNNN)NNN)	NNNNNNNNF)NNFr   )NNz00:00:00)NNNN)NNNNNNNN)NNNNNNN)NF)-__doc__
__future__r   r   r   rf   r   googlecloudsdk.api_lib.sqlr   r   r   r   r5   r	   googlecloudsdk.callioper
   googlecloudsdk.corer   googlecloudsdk.core.utilr   r%   r   r#   r1   rU   r\   rd   ry   r}   rz   r   r   r   r   r   r   r   r   r   r   r  r  r  r1  r9   r    r   <module>rA     s   O '  '   B 0 C < / . * * 

 	 $.d !%,0)-@ "&"&z|  !%',8( 37-1.2	;@ >B;?7A	>!BDQ ;?7;;?9=:>2j # $ H """ $#'$(9%x5pA  . 6:15)-&=R0  $##'04-1:~ *&Z%T  $	6r    