
    C                        S r SSKJr  SSKJr  SSKJ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\R<                  " 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$ r0 " S% S&\$5      r1 " S' S(\15      r2g).+Common utility functions for sql instances.    )absolute_import)division)unicode_literalsN)
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)DatabaseInstancePresentation2   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__5   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     r2   __eq__#DatabaseInstancePresentation.__eq__D   s&    %566]]enn,,r5   c                 .    U R                  U5      (       + $ )z@Overrides the default implementation (only needed for Python 2).)r:   r8   s     r2   __ne__#DatabaseInstancePresentation.__ne__J   s    {{5!!!r5   )r   N)	__name__
__module____qualname____firstlineno____doc__r3   r:   r=   __static_attributes__ r5   r2   r   r   2   s    S-"r5   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     r2   GetRegionFromZonerM   O   s&    NN3'/	/#2&	''r5   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    r2   _IsCloudSqlProxyPresentInSdkBinrU   V   s0    
''..-
. 3
))("''
24r5   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_pathrO   rP   rJ   rU   
file_utilsFindExecutableOnPathr   debugsql_exceptionsSqlProxyNotFound)binary_namerY   rT   
proxy_paths       r2   _GetCloudSqlProxyPathra   \   s     ,,, 77<<B&';<<!! ..{;*II{m;zl!<=

)
)	*+ +r5   c                     SR                  [        5      nU (       a  SR                  [        U 5      n[        R                  " U5      e)Nz{}.z{}: {})format_BASE_CLOUD_SQL_PROXY_ERRORr]   CloudSqlProxyError)	error_msgmessages     r2   _RaiseProxyErrorrh   {   s6    LL45'oo99EG))'22r5   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    r2   _ReadLineFromStderrro           	--668	99r5   c                 ^    [         R                  " U R                  R                  5       5      $ )z=Reads and returns the next line from the proxy stdout stream.)r   rj   stdoutrl   rm   s    r2   _ReadLineFromStdoutrs      rp   r5   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:
)pollrs   r   statuswriter	   PROXY_ADDRESS_IN_USE_ERRORrh   rc   "PROXY_V2_READY_FOR_CONNECTIONS_MSGtimesleeprk   readr   rj   
splitlines
startswithappendrJ   strip)rn   portseconds_to_timeoutrun_connection_testtotal_wait_secondsseconds_to_sleeplineerrdecoded_err	err_lineserror_only_linesrf   s               r2   _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!{#r5   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   ru   Nrv   rw   )ry   ro   r   rz   r{   r	   r|   rh   rc   PROXY_READY_FOR_CONNECTIONS_MSGr~   r   )rn   r   r   r   r   r   s         r2   _WaitForProxyToStartr      s     $}-D
	jjt		-	-	544:F4L	B 44< /d $ /|$ *JJ ' 	$, r5   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rr   stdinrk   '  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)ra   connectionNamestrr   r   VALUESapi_endpoint_overridesr   Getr   ArgsForExecutableToolr   rz   r{   rc   rJ   
subprocessPopenPIPEEnvironmentErrorerrnoENOENTr]   re   r   )instancer   r   impersonate_service_accountauto_iam_authn
private_ippscauto_ip
debug_logsr   command_pathr   
proxy_argsrn   es                  r2   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)ra   rc   r   r   r   coreaccountr   r   rX   LegacyCredentialsAdcPathr   r   r   rz   r{   rJ   r   r   r   r   r   r   r]   re   r   )	r   r   r   r   r   r   r   rn   r   s	            r2   StartCloudSqlProxyr   Q  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     r2   IsInstanceV2r     s%    			!>!>!Y!Y!d!d	ddr5   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    r2    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
            @r2   GetDatabaseInstances#_BaseInstances.GetDatabaseInstances  s       < <=F""J&&L""''//33T3BJFWo  ,
2D < &&,,Z,@LDJLG3 ,--r5   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rg   defaultcancel_on_nor   PromptContinuerE   r5   r2   *PrintAndConfirmAuthorizedNetworksOverwrite9_BaseInstances.PrintAndConfirmAuthorizedNetworksOverwrite  s    M r5   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   rE   r5   r2   (PrintAndConfirmSimulatedMaintenanceEvent7_BaseInstances.PrintAndConfirmSimulatedMaintenanceEvent  s    & r5   c                 @    U R                   R                  [        5      $ )z>Returns a boolean indicating if the database version is MySQL.)r!   r   _MYSQL_DATABASE_VERSION_PREFIXdatabase_versions    r2   IsMysqlDatabaseVersion%_BaseInstances.IsMysqlDatabaseVersion  s       ++,JKKr5   c                 @    U R                   R                  [        5      $ )zAReturns a boolean indicating if the database version is Postgres.)r!   r   !_POSTGRES_DATABASE_VERSION_PREFIXr   s    r2   IsPostgresDatabaseVersion(_BaseInstances.IsPostgresDatabaseVersion  s       ++,MNNr5   c                 @    U R                   R                  [        5      $ )zCReturns a boolean indicating if the database version is SQL Server.)r!   r   "_SQLSERVER_DATABASE_VERSION_PREFIXr   s    r2   IsSqlServerDatabaseVersion)_BaseInstances.IsSqlServerDatabaseVersion  s       ++,NOOr5   rE   )NN)r?   r@   rA   rB   rC   staticmethodr   r   r   r   r   r   rD   rE   r5   r2   r   r     s    3%. %.N     L L O O P Pr5   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     r2   SetProjectAndInstanceFromRef-InstancesV1Beta4.SetProjectAndInstanceFromRef  s      , 4 4)22r5   c                     Xl         g r   )backupConfiguration)r"   backup_configs     r2   AddBackupConfigToSettings*InstancesV1Beta4.AddBackupConfigToSettings  s    #0 r5   rE   N)	r?   r@   rA   rB   rC   r   r   r   rD   rE   r5   r2   r   r     s+    ;3 3 1 1r5   r   )cloud_sql_proxyr   )F)
   NFFFFFF)r   )3rC   
__future__r   r   r   r   rO   r   r~   apitools.base.pyr   googlecloudsdk.api_lib.sqlr   r	   r
   r]   googlecloudsdk.api_lib.utilr   googlecloudsdk.corer   r   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r   rZ   r,   GetMessagesModuler$   rd   r   r   r   objectr   rM   rU   ra   rh   ro   rs   r   r   r   r   r   r   r   rE   r5   r2   <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~ 
1r5   