
    D                        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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mZ ddlmZ ddlmZ ddlmZ ddlZ ej<                  dd      ZdZ dZ!dZ"dZ# G d de$      Z%d Z&d Z'd)dZ(d*dZ)d Z*d Z+	 d+d Z,d! Z-	 	 	 	 	 	 	 	 	 d,d"Z.d-d#Z/d$ Z0 G d% d&e$      Z1 G d' d(e1      Z2y).+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                   "    e Zd ZdZd Zd Zd Zy)DatabaseInstancePresentationzKRepresents a DatabaseInstance message that is modified for user visibility.c                    |j                         D ]  }|j                  dk(  ra|j                  rC|j                  j                  t        j
                  j                  j                  k(  rd| _        a|j                  | _        st        ||j                        }|t        |t              r|s|j                  dv r+t        | |j                  t        j                  |             t        | |j                  |        y )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__z%DatabaseInstancePresentation.__init__5   s    "	w	==T]];;x?P?P?p?p?v?vv $*zz$*ejj)j&=eZZ==D%**cmmE&:;D%**e, #    c                 V    t        |t              r| j                  |j                  k(  S y)zAOverrides the default implementation by checking attribute dicts.F)r(   r   __dict__r-   others     r1   __eq__z#DatabaseInstancePresentation.__eq__D   s#    %56]]enn,,r3   c                 &    | j                  |       S )z@Overrides the default implementation (only needed for Python 2).)r8   r6   s     r1   __ne__z#DatabaseInstancePresentation.__ne__J   s    {{5!!!r3   N)__name__
__module____qualname____doc__r2   r8   r:    r3   r1   r   r   2   s    S-"r3   r   c                 L    | j                  d      }dj                  |dd       S )z>Parses and returns the region string from the gce_zone string.-N)splitjoin)gce_zonezone_componentss     r1   GetRegionFromZonerG   O   s&    NN3'/	/#2&	''r3   c                     t         j                  j                  |       xr$ t        j                  | t         j                        S )zBChecks if cloud_sql_proxy_path binary is present in cloud sdk bin.)ospathexistsaccessX_OK)cloud_sql_proxy_paths    r1   _IsCloudSqlProxyPresentInSdkBinrO   V   s0    
''..-
. 3
))("''
24r3   c                 0   t        j                         j                  }|r-t        j                  j                  ||       }t        |      r|S t        j                  |       }|rt        j                  d|  d| d       |S t        j                  d      )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_pathrI   rJ   rD   rO   
file_utilsFindExecutableOnPathr   debugsql_exceptionsSqlProxyNotFound)binary_namerS   rN   
proxy_paths       r1   _GetCloudSqlProxyPathr[   \   s     ,,, 77<<kB&';<!! ..{;*II{m;zl!<=

)
)	*+ +r3   c                     dj                  t              }| rdj                  t        |       }t        j                  |      )Nz{}.z{}: {})format_BASE_CLOUD_SQL_PROXY_ERRORrW   CloudSqlProxyError)	error_msgmessages     r1   _RaiseProxyErrorrb   {   s6    LL45'oo99EG))'22r3   c                 \    t        j                  | j                  j                               S )z=Reads and returns the next line from the proxy stderr stream.)r   Decodestderrreadlineproxy_processs    r1   _ReadLineFromStderrri           	--668	99r3   c                 \    t        j                  | j                  j                               S )z=Reads and returns the next line from the proxy stdout stream.)r   rd   stdoutrf   rg   s    r1   _ReadLineFromStdoutrm      rj   r3   c                 |   d}d}| j                         t        |       }|rxt        j                  j	                  |       t
        j                  |v rt        dj                  |             n|rd|v r| S |st
        j                  |v r| S t        |       }|rx||k\  rt        d       ||z  }t        j                  |       | j                         |r5	 t        |       }|sn&t        j                  j	                  |       d|v r| S 4| j                  j                         }|rt        j                  |      }|j!                         }	g }
|	D ]&  }|j#                  d      r n|
j%                  |       ( dj'                  |
      j)                         }|rt        |       yt        |       yt                y)	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:
)pollrm   r   statuswriter	   PROXY_ADDRESS_IN_USE_ERRORrb   r]   "PROXY_V2_READY_FOR_CONNECTIONS_MSGtimesleepre   readr   rd   
splitlines
startswithappendrD   strip)rh   portseconds_to_timeoutrun_connection_testtotal_wait_secondsseconds_to_sleeplineerrdecoded_err	err_lineserror_only_linesr`   s               r1   _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!{#r3   c                    d}d}| j                         t        |       }|rnt        j                  j	                  |       t
        j                  |v rt        dj                  |             nt
        j                  |v r| S t        |       }|rn||k\  rt        d       ||z  }t        j                  |       | j                         t                y)a_  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   ro   Nrp   rq   )rs   ri   r   rt   ru   r	   rv   rb   r]   PROXY_READY_FOR_CONNECTIONS_MSGrx   ry   )rh   r   r   r   r   r   s         r1   _WaitForProxyToStartr      s     $}-D
	jjt		-	-	544:F4L	B 44< /d  //|$ **JJ ' 	$, r3   c                    t        d      }| j                  dt        |      g}|r|j                  d       |r|j                  d       |r|j                  d       |r|j                  d       |r|j                  d       |	r|d	|	gz  }|
r|j                  d
       |r|d|gz  }n\t        j
                  j                  j                  j                  d      }|dt        j                         j                  |      gz  }t        j                  |g| }t        j                  j!                  dj#                  dj%                  |                   	 t'        j(                  |t&        j*                  t&        j*                  t&        j*                        }t7        ||||
      S # t,        $ rG}|j.                  t.        j0                  k(  r$t3        j4                  dj#                  |             d}~ww xY w)am  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.
    sqladmin_api_endpoint: Cloud SQL Admin API endpoint for Cloud SQL 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)rY   z--portz--private-ipz--pscz	--auto-ipz--debug-logsz--auto-iam-authnz--sqladmin-api-endpointz--run-connection-testz--impersonate-service-accountTrequiredz--credentials-filez#Starting Cloud SQL Proxy: [{args}]
 argsrl   stdinre   '  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coreaccountGetr   rR   LegacyCredentialsAdcPathr   ArgsForExecutableToolr   rt   ru   r]   rD   
subprocessPopenPIPEEnvironmentErrorerrnoENOENTrW   r_   r   )instancer   r   impersonate_service_accountauto_iam_authn
private_ippscauto_ip
debug_logssqladmin_api_endpointr   command_pathr   r   
proxy_argsrh   es                    r1   StartCloudSqlProxyV2r      s   B '3DE, 
!
!8SY	7$KKKKKKKKKK"#&(=>>DKK'( ,.IJJD $$,,00$0?G//8 D 44\IDI***,33*9M3N
$$oo	M( 
 T-/B
  
 
ww%,, --% &,VL%9  

s   AF, ,	G<5AG77G<c                    t               }ddj                  | j                  |      g}t        j                  j
                  j                  j                  d      }|dt        j                         j                  |      gz  }t        j                  |g| }t        j                  j                  dj                  dj!                  |                   	 t#        j$                  |t"        j&                  t"        j&                  t"        j&                  	      }t3        |||      S # t(        $ rG}|j*                  t*        j,                  k(  r$t/        j0                  d
j                  |             d}~ww xY w)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:{}Tr   z-credential_filez$Starting Cloud SQL Proxy: [{args}]]
r   r   r   r   N)r[   r]   r   r   r   r   r   r   r   rR   r   r   r   r   rt   ru   rD   r   r   r   r   r   r   rW   r_   r   )	r   r   r   r   r   r   r   rh   r   s	            r1   StartCloudSqlProxyr   W  s>    '(, **8+B+BDI	J$""**...='v||~FFwO
PP$44\IDI***-44#((::N4O
$$oo	M* 
mT3E	FF 
 
ww%,, --&
 '-f\&:  

s   AD* *	E:3AE55E:c                 \    |j                   | j                  j                  j                  k(  S )zDReturns a boolean indicating if the database instance is second gen.)backendTypeDatabaseInstanceBackendTypeValueValuesEnum
SECOND_GEN)sql_messagesr   s     r1   IsInstanceV2r     s%    			!>!>!Y!Y!d!d	ddr3   c                   r    e Zd ZdZed	d       Zed        Zed        Zed        Zed        Z	ed        Z
y)
_BaseInstancesr   Nc                   	 t        j                  t         j                        }|j                  }|j                  }t
        j                  j                  j                  j                  d      }i }| | |d<   d}||n||d<   t        j                  |j                  |j                  |      fi |		fd} |       S )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   6   K   D ]  } t        |         y wN)r   )resultyieldeds    r1    YieldInstancesWithAModifiedStatezM_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
            @r1   GetDatabaseInstancesz#_BaseInstances.GetDatabaseInstances  s       < <=F""J&&L""''//33T3BJFfWo  ,
2D < &&,,Z,@LDJLG3 ,--r3   c                  4    t        j                  ddd       y )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ra   defaultcancel_on_nor   PromptContinuer?   r3   r1   *PrintAndConfirmAuthorizedNetworksOverwritez9_BaseInstances.PrintAndConfirmAuthorizedNetworksOverwrite  s    M r3   c                  4    t        j                  ddd       y )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   r?   r3   r1   (PrintAndConfirmSimulatedMaintenanceEventz7_BaseInstances.PrintAndConfirmSimulatedMaintenanceEvent  s    & r3   c                 @    | j                   j                  t              S )z>Returns a boolean indicating if the database version is MySQL.)r    r|   _MYSQL_DATABASE_VERSION_PREFIXdatabase_versions    r1   IsMysqlDatabaseVersionz%_BaseInstances.IsMysqlDatabaseVersion  s       ++,JKKr3   c                 @    | j                   j                  t              S )zAReturns a boolean indicating if the database version is Postgres.)r    r|   !_POSTGRES_DATABASE_VERSION_PREFIXr   s    r1   IsPostgresDatabaseVersionz(_BaseInstances.IsPostgresDatabaseVersion  s       ++,MNNr3   c                 @    | j                   j                  t              S )zCReturns a boolean indicating if the database version is SQL Server.)r    r|   "_SQLSERVER_DATABASE_VERSION_PREFIXr   s    r1   IsSqlServerDatabaseVersionz)_BaseInstances.IsSqlServerDatabaseVersion  s       ++,NOOr3   )NN)r;   r<   r=   r>   staticmethodr   r   r   r   r   r   r?   r3   r1   r   r     s    3%. %.N     L L O O P Pr3   r   c                   0    e Zd ZdZed        Zed        Zy)InstancesV1Beta4z3Common utility functions for sql instances V1Beta4.c                 H    |j                   | _         |j                  | _        y r   )r   r   r    )instance_resourceinstance_refs     r1   SetProjectAndInstanceFromRefz-InstancesV1Beta4.SetProjectAndInstanceFromRef  s      , 4 4)22r3   c                     || _         y r   )backupConfiguration)r!   backup_configs     r1   AddBackupConfigToSettingsz*InstancesV1Beta4.AddBackupConfigToSettings  s
    #0H r3   N)r;   r<   r=   r>   r   r   r   r?   r3   r1   r   r     s+    ;3 3 1 1r3   r   )cloud_sql_proxyr   )F)	
   NFFFFFNF)r   )3r>   
__future__r   r   r   r   rI   r   rx   apitools.base.pyr   googlecloudsdk.api_lib.sqlr   r	   r
   rW   googlecloudsdk.api_lib.utilr   googlecloudsdk.corer   r   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r   rT   r+   GetMessagesModuler#   r^   r   r   r   objectr   rG   rO   r[   rb   ri   rm   r   r   r   r   r   r   r   r?   r3   r1   <module>r      s    2 &  '  	   ' / 0 C , & / # * 2 - 8 
 "4!!%3C !( $. !%0 ""6 ":(4+>3:
: BGFR$R -/59(-$)"!&$)/3-2Xv1GheJPV JPZ
1~ 
1r3   