
    cC                        S r SSKrSSKrSSKrSSKrSSKJr  SSKJr  SSKJ	r	  SSKJ
r  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKr\R4                  " SS5      rSrSrSrSr " S S\ 5      r!S r"S r#S&S jr$S'S jr%S r&S r' S(S jr(S r)        S)S jr*S*S  jr+S! r, " S" S#\ 5      r- " S$ S%\-5      r.g)++Common utility functions for sql instances.    N)
list_pager)api_util)	constants)
exceptions)apis)config)execution_utils)log)
properties)
console_io)encoding)filessqlv1beta4z#Failed to start the Cloud SQL ProxyMYSQLPOSTGRES	SQLSERVERc                   *    \ rS rSrSrS rS rS rSrg)DatabaseInstancePresentation/   zKRepresents a DatabaseInstance message that is modified for user visibility.c                 <   UR                  5        GH  nUR                  S:X  ai  UR                  (       aE  UR                  R                  [        R
                  R                  R                  :X  a	  SU l        Mj  UR                  U l        M}  [        XR                  5      nUc  M  [        U[        5      (       a	  U(       d  M  UR                  S;   a,  [        XR                  [        R                  " U5      5        M  [        XR                  U5        GM
     g )NstateSTOPPED)currentDiskSizemaxDiskSize)
all_fieldsnamesettingsactivationPolicymessagesSettingsActivationPolicyValueValuesEnumNEVERr   getattr
isinstancelistsetattrsix	text_type)selforigfieldvalues       +lib/googlecloudsdk/api_lib/sql/instances.py__init__%DatabaseInstancePresentation.__init__2   s    "	w	==T]];;x?P?P?p?p?v?vv $*zz$*jj)j&=&=eeZZ==D**cmmE&:;D**e, #    c                 `    [        U[        5      (       a  U R                  UR                  :H  $ g)zAOverrides the default implementation by checking attribute dicts.F)r&   r   __dict__r+   others     r/   __eq__#DatabaseInstancePresentation.__eq__A   s&    %566]]enn,,r2   c                 .    U R                  U5      (       + $ )z@Overrides the default implementation (only needed for Python 2).)r7   r5   s     r/   __ne__#DatabaseInstancePresentation.__ne__G   s    {{5!!!r2   )r   N)	__name__
__module____qualname____firstlineno____doc__r0   r7   r:   __static_attributes__ r2   r/   r   r   /   s    S-"r2   r   c                 L    U R                  S5      nSR                  USS 5      $ )z>Parses and returns the region string from the gce_zone string.-N)splitjoin)gce_zonezone_componentss     r/   GetRegionFromZonerJ   L   s&    NN3'/	/#2&	''r2   c                     [         R                  R                  U 5      =(       a%    [         R                  " U [         R                  5      $ )zBChecks if cloud_sql_proxy_path binary is present in cloud sdk bin.)ospathexistsaccessX_OK)cloud_sql_proxy_paths    r/   _IsCloudSqlProxyPresentInSdkBinrR   S   s0    
''..-
. 3
))("''
24r2   c                 T   [         R                  " 5       R                  nU(       a1  [        R                  R                  X5      n[        U5      (       a  U$ [        R                  " U 5      nU(       a  [        R                  " SU  SU S35        U$ [        R                  " S5      e)zDetermines the path to the Cloud SQL Proxy binary.

Args:
  binary_name: Name of Cloud SQL Proxy binary to look for in path. (v1:
    'cloud_sql_proxy', v2: 'cloud-sql-proxy')

Returns:
  str: The path to the Cloud SQL Proxy binary.
zUsing z found at []zbA Cloud SQL Proxy SDK root could not be found, or access is denied.Please check your installation.)r	   Pathssdk_bin_pathrL   rM   rG   rR   
file_utilsFindExecutableOnPathr   debugsql_exceptionsSqlProxyNotFound)binary_namerV   rQ   
proxy_paths       r/   _GetCloudSqlProxyPathr^   Y   s     ,,, 77<<B&';<<!! ..{;*II{m;zl!<=

)
)	*+ +r2   c                     SR                  [        5      nU (       a  SR                  [        U 5      n[        R                  " U5      e)Nz{}.z{}: {})format_BASE_CLOUD_SQL_PROXY_ERRORrZ   CloudSqlProxyError)	error_msgmessages     r/   _RaiseProxyErrorre   x   s6    LL45'oo99EG))'22r2   c                 ^    [         R                  " U R                  R                  5       5      $ )z=Reads and returns the next line from the proxy stderr stream.)r   Decodestderrreadlineproxy_processs    r/   _ReadLineFromStderrrl           	--668	99r2   c                 ^    [         R                  " U R                  R                  5       5      $ )z=Reads and returns the next line from the proxy stdout stream.)r   rg   stdoutri   rj   s    r/   _ReadLineFromStdoutrp      rm   r2   c                    SnSnU R                  5       c  [        U 5      nU(       a  [        R                  R	                  U5        [
        R                  U;   a  [        SR                  U5      5        O,U(       a  SU;   a  U $ U(       d  [
        R                  U;   a  U $ [        U 5      nU(       a  M  XB:  a  [        S5        XE-  n[        R                  " U5        U R                  5       c  M  U(       a=   [        U 5      nU(       d  O)[        R                  R	                  U5        SU;   a  U $ M<  U R                  R                  5       nU(       a  [        R                  " U5      nUR!                  5       n	/ n
U	 H,  nUR#                  S5      (       a    OU
R%                  U5        M.     SR'                  U
5      R)                  5       nU(       a  [        U5        g[        U5        g[        5         g)	a  Wait for the proxy to be ready for connections, then return proxy_process.

Args:
  proxy_process: The Process corresponding to the Cloud SQL Proxy (v2).
  port: int, the port that the proxy was started on.
  seconds_to_timeout: Seconds to wait before timing out.
  run_connection_test: if true, waits for connection test success message.

Returns:
  The Process object corresponding to the Cloud SQL Proxy (v2).
r   皙?NePort already in use. Exit the process running on port {} or try connecting again on a different port.zConnection test passed
Timed out.zUsage:
)pollrp   r   statuswriter   PROXY_ADDRESS_IN_USE_ERRORre   r`   "PROXY_V2_READY_FOR_CONNECTIONS_MSGtimesleeprh   readr   rg   
splitlines
startswithappendrG   strip)rk   portseconds_to_timeoutrun_connection_testtotal_wait_secondsseconds_to_sleeplineerrdecoded_err	err_lineserror_only_linesrc   s               r/   _WaitForProxyV2ToStartr      s    $}-D
	jjt		-	-	544:F4L	
 #;t#C!::dB  /d $$ /|$ *JJ 3 	$: 
 /d	jjt	!T	)  	!!##//#&K&&(I		"	"d# 
 		*+113Iy!{#r2   c                    SnSnU R                  5       c  [        U 5      nU(       ax  [        R                  R	                  U5        [
        R                  U;   a  [        SR                  U5      5        O[
        R                  U;   a  U $ [        U 5      nU(       a  Mx  X2:  a  [        S5        X4-  n[        R                  " U5        U R                  5       c  M  [        5         g)aQ  Wait for the proxy to be ready for connections, then return proxy_process.

Args:
  proxy_process: Process, the process corresponding to the Cloud SQL Proxy.
  port: int, the port that the proxy was started on.
  seconds_to_timeout: Seconds to wait before timing out.

Returns:
  The Process object corresponding to the Cloud SQL Proxy.
r   rr   Nrs   rt   )rv   rl   r   rw   rx   r   ry   re   r`   PROXY_READY_FOR_CONNECTIONS_MSGr{   r|   )rk   r   r   r   r   r   s         r/   _WaitForProxyToStartr      s     $}-D
	jjt		-	-	544:F4L	B 44< /d $ /|$ *JJ ' 	$, r2   c
                 H   [        SS9n
U R                  S[        U5      /nU(       a  UR                  S5        U(       a  UR                  S5        U(       a  UR                  S5        U(       a  UR                  S5        U(       a  UR                  S5        [        R
                  R                  R                  R                  5       (       a7  US	[        R
                  R                  R                  R                  5       /-  nU	(       a  UR                  S
5        U(       a  USU/-  n[        R                  " U
/UQ76 n[        R                  R                  SR                  SR                  U5      S95         [         R"                  " U[         R$                  [         R$                  [         R$                  S9n[1        XX)5      $ ! [&         aI  nUR(                  [(        R*                  :X  a%  [,        R.                  " SR                  U
5      5      ee SnAff = f)a  Starts the Cloud SQL Proxy (v2) for instance on the given port.

Args:
  instance: The instance to start the proxy for.
  port: The port to bind the proxy to.
  seconds_to_timeout: Seconds to wait before timing out.
  impersonate_service_account: Service account to impersonate.
  auto_iam_authn: Whether to use IAM DB Authentication.
  private_ip: Whether to use private IP.
  psc: Whether to use PSC.
  auto_ip: Whether to use auto IP detection.
  debug_logs: Whether to enable verbose logs in proxy.
  run_connection_test: Whether to run connection test.

Returns:
  The Process object corresponding to the Cloud SQL Proxy.

Raises:
  CloudSqlProxyError: An error starting the Cloud SQL Proxy.
  SqlProxyNotFound: An error finding a Cloud SQL Proxy installation.
zcloud-sql-proxy)r\   z--portz--private-ipz--pscz	--auto-ipz--debug-logsz--auto-iam-authnz--sqladmin-api-endpointz--run-connection-testz--impersonate-service-accountz#Starting Cloud SQL Proxy: [{args}]
 argsro   stdinrh   '  Failed to start Cloud SQL Proxy. Please make sure it is available in the PATH [{}]. Learn more about installing the Cloud SQL Proxy here: https://cloud.google.com/sql/docs/mysql/connect-auth-proxy#install. If you would like to report this issue, please run the following command: gcloud feedbackN)r^   connectionNamestrr   r   VALUESapi_endpoint_overridesr   Getr
   ArgsForExecutableToolr   rw   rx   r`   rG   
subprocessPopenPIPEEnvironmentErrorerrnoENOENTrZ   rb   r   )instancer   r   impersonate_service_accountauto_iam_authn
private_ippscauto_ip
debug_logsr   command_pathr   
proxy_argsrk   es                  r/   StartCloudSqlProxyV2r      s   > '3DE, 
!
!8SY	7$KKKKKKKKKK"#--115577!004488: D KK'( ,.IJJD44\IDI***,33*9M3N
$$oo	M( 
 -
  
 
ww%,, --% &,VL%9  

s   AG 
H!AHH!c                    [        5       nSSR                  U R                  U5      /n[        R                  R
                  R                  R                  SS9nUS[        R                  " 5       R                  U5      /-  n[        R                  " U/UQ76 n[        R                  R                  SR                  SR!                  U5      S95         ["        R$                  " U["        R&                  ["        R&                  ["        R&                  S	9n[3        XqU5      $ ! [(         aI  nUR*                  [*        R,                  :X  a%  [.        R0                  " S
R                  U5      5      ee SnAff = f)a  Starts the Cloud SQL Proxy (v1) for instance on the given port.

Args:
  instance: The instance to start the proxy for.
  port: The port to bind the proxy to.
  seconds_to_timeout: Seconds to wait before timing out.

Returns:
  The Process object corresponding to the Cloud SQL Proxy.

Raises:
  CloudSqlProxyError: An error starting the Cloud SQL Proxy.
  SqlProxyNotFound: An error finding a Cloud SQL Proxy installation.
z
-instancesz	{}=tcp:{}Trequiredz-credential_filez$Starting Cloud SQL Proxy: [{args}]]
r   r   r   r   N)r^   r`   r   r   r   coreaccountr   r	   rU   LegacyCredentialsAdcPathr
   r   r   rw   rx   rG   r   r   r   r   r   r   rZ   rb   r   )	r   r   r   r   r   r   r   rk   r   s	            r/   StartCloudSqlProxyr   N  s<    '(, **8+B+BDI	J$""**...='v||~FFwO
PP$44\IDI***-44#((::N4O
$$oo	M* 
m3E	FF 
 
ww%,, --&
 '-f\&:  

s   AD# #
E6-AE11E6c                 \    UR                   U R                  R                  R                  :H  $ )zDReturns a boolean indicating if the database instance is second gen.)backendTypeDatabaseInstanceBackendTypeValueValuesEnum
SECOND_GEN)sql_messagesr   s     r/   IsInstanceV2r     s%    			!>!>!Y!Y!d!d	ddr2   c                   |    \ rS rSrSr\SS j5       r\S 5       r\S 5       r\S 5       r	\S 5       r
\S	 5       rS
rg)_BaseInstancesi  r   Nc                   ^	 [         R                  " [         R                  5      nUR                  nUR                  n[
        R                  R                  R                  R                  SS9n0 nU b  XS'   SnUb  UOUUS'   [        R                  " UR                  UR                  US940 UD6m	U	4S jnU" 5       $ )a~  Gets SQL instances in a given project.

Modifies current state of an individual instance to 'STOPPED' if
activationPolicy is 'NEVER'.

Args:
  limit: int, The maximum number of records to yield. None if all available
      records should be yielded.
  batch_size: int, The number of items to retrieve per request.

Returns:
  List of yielded DatabaseInstancePresentation instances.
Tr   limiti  
batch_size)projectc               3   :   >#    T H  n [        U 5      v   M     g 7fN)r   )resultyieldeds    r/    YieldInstancesWithAModifiedStateM_BaseInstances.GetDatabaseInstances.<locals>.YieldInstancesWithAModifiedState  s     &*622 s   )r   	SqlClientAPI_VERSION_DEFAULT
sql_clientr   r   r   r   r   r   r   YieldFromList	instancesSqlInstancesListRequest)
r   r   clientr   r   
project_idparamsdefault_batch_sizer   r   s
            @r/   GetDatabaseInstances#_BaseInstances.GetDatabaseInstances  s       < <=F""J&&L""''//33T3BJFWo  ,
2D < &&,,Z,@LDJLG3 ,--r2   c                  0    [         R                  " SSSS9  g )NzWhen adding a new IP address to authorized networks, make sure to also include any IP addresses that have already been authorized. Otherwise, they will be overwritten and de-authorized.Trd   defaultcancel_on_nor   PromptContinuerB   r2   r/   *PrintAndConfirmAuthorizedNetworksOverwrite9_BaseInstances.PrintAndConfirmAuthorizedNetworksOverwrite  s    M r2   c                  0    [         R                  " SSSS9  g )NzThis request will trigger a simulated maintenance event and will not change the maintenance version on the instance. Downtime will occur on the instance.FTr   r   rB   r2   r/   (PrintAndConfirmSimulatedMaintenanceEvent7_BaseInstances.PrintAndConfirmSimulatedMaintenanceEvent  s    & r2   c                 @    U R                   R                  [        5      $ )z>Returns a boolean indicating if the database version is MySQL.)r   r   _MYSQL_DATABASE_VERSION_PREFIXdatabase_versions    r/   IsMysqlDatabaseVersion%_BaseInstances.IsMysqlDatabaseVersion  s       ++,JKKr2   c                 @    U R                   R                  [        5      $ )zAReturns a boolean indicating if the database version is Postgres.)r   r   !_POSTGRES_DATABASE_VERSION_PREFIXr   s    r/   IsPostgresDatabaseVersion(_BaseInstances.IsPostgresDatabaseVersion  s       ++,MNNr2   c                 @    U R                   R                  [        5      $ )zCReturns a boolean indicating if the database version is SQL Server.)r   r   "_SQLSERVER_DATABASE_VERSION_PREFIXr   s    r/   IsSqlServerDatabaseVersion)_BaseInstances.IsSqlServerDatabaseVersion  s       ++,NOOr2   rB   )NN)r<   r=   r>   r?   r@   staticmethodr   r   r   r   r   r   rA   rB   r2   r/   r   r     s    3%. %.N     L L O O P Pr2   r   c                   8    \ rS rSrSr\S 5       r\S 5       rSrg)InstancesV1Beta4i  z3Common utility functions for sql instances V1Beta4.c                 H    UR                   U l         UR                  U l        g r   )r   r   r   )instance_resourceinstance_refs     r/   SetProjectAndInstanceFromRef-InstancesV1Beta4.SetProjectAndInstanceFromRef  s      , 4 4)22r2   c                     Xl         g r   )backupConfiguration)r   backup_configs     r/   AddBackupConfigToSettings*InstancesV1Beta4.AddBackupConfigToSettings  s    #0 r2   rB   N)	r<   r=   r>   r?   r@   r   r   r   rA   rB   r2   r/   r   r     s+    ;3 3 1 1r2   r   )cloud_sql_proxyr   )F)
   NFFFFFF)r   )/r@   r   rL   r   r{   apitools.base.pyr   googlecloudsdk.api_lib.sqlr   r   r   rZ   googlecloudsdk.api_lib.utilr   googlecloudsdk.corer	   r
   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r   rW   r)   GetMessagesModuler!   ra   r   r   r   objectr   rJ   rR   r^   re   rl   rp   r   r   r   r   r   r   r   rB   r2   r/   <module>r     s    2  	   ' / 0 C , & / # * 2 - 8 
 !!%3C !( $. !%0 ""6 ":(4+>3:
: BGFR$R -/59(-$)"!&$)-2Rj1GheJPV JPZ
1~ 
1r2   