
    K^                     F   S r SSKJr  SSKJr  SSKJ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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r#S\#S.r$S\#S.r% S(S jr&S r'S r(S r)S)S jr*S*S jr+ S*S  jr,S*S! jr-\R\                  \R^                  " \R`                  Rb                  5       " S" S#\Rd                  5      5       5       r3\R\                  \R^                  " \R`                  Rh                  5       " S$ S%\Rd                  5      5       5       r5\Rl                  \R^                  " \R`                  Rn                  5       " S& S'\Rd                  5      5       5       r8g)+!Connects to a Cloud SQL instance.    )absolute_import)division)unicode_literalsN)client)
exceptions)api_util)	constants)	instances)network)
operations)arg_parsers)base)flags)log)
properties)files)iso_duration)retry)textz\    To connect to a Cloud SQL instance, run:

      $ {command} my-instance --user=root
    ag  
        Connects to a Cloud SQL instance.

        This command temporarily changes the authorized networks for this
        instance to allow the connection from your IP address.

        This command isn't supported for Cloud SQL instances with only
        private IP addresses.

        NOTE: If you're connecting from an IPv6 address, or are constrained by
        certain organization policies (restrictPublicIP,
        restrictAuthorizedNetworks), consider running the beta version of this
        command to avoid error by connecting through the Cloud SQL proxy:
        *gcloud beta sql connect*
        )DESCRIPTIONEXAMPLESz3
        Connects to a Cloud SQL instance.
        c                    [         R                  " 5       nSR                  U5      nUR                  SU[        R
                  " US9R                  U5      R                  SS9R                  5       SS9n UR                  R                  UR                  U R                  U R                  S95      nS
Ul        UR2                  R4                  R6                  R9                  U5         UR;                  UU R                  U R                  S9n
UR                  R=                  U
5      nURC                  SURD                  U R                  S9nSR                  U[F        RH                  " US5      5      n[J        RL                  RO                  XU5        U$ ! [        R                   al  n	U	R                   ["        R$                  :X  a3  [&        R(                  " S	R                  U R+                  5       5      5      e[,        R.                  " U	5      eS
n	A	ff = f! [        R                   a1  n	[>        R@                  " S5        [,        R.                  " U	5      eS
n	A	ff = f)a  Add CLIENT_IP to the authorized networks list.

Makes an API call to add CLIENT_IP to the authorized networks list.
The server knows to interpret the string CLIENT_IP as the address with which
the client reaches the server. This IP will be allowlisted for 1 minute.

Args:
  instance_ref: resources.Resource, The instance we're connecting to.
  sql_client: apitools.BaseApiClient, A working client for the sql version to
    be used.
  sql_messages: module, The module that defines the messages for the sql
    version to be used.
  resources: resources.Registry, The registry that can create resource refs
    for the sql version to be used.
  minutes: How long the client IP will be allowlisted for, in minutes.

Returns:
  string, The name of the authorized network rule. Callers can use this name
  to find out the IP the client reached the server with.
Raises:
  HttpException: An http error response was received while executing api
      request.
  ResourceNotFoundError: The SQL instance was not found.
zsql connect at time {0}zsql#aclEntry)minutesi'  )microsecond	CLIENT_IP)kindnameexpirationTimevalueprojectinstancezMThere was no instance found at {} or you are not authorized to connect to it.N)databaseInstancer"   r#   a  If you're connecting from an IPv6 address, or are constrained by certain organization policies (restrictPublicIP, restrictAuthorizedNetworks), consider running the beta version of this command by connecting through the Cloud SQL proxy: gcloud beta sql connectzsql.operations)	operationr"   z8Allowlisting your IP for incoming connection for {0} {1}minute)(r   GetCurrentTimeformatAclEntryr   DurationGetRelativeDateTimereplace	isoformatr   GetSqlInstancesGetRequestr"   r#   apitools_exceptions	HttpErrorstatus_codehttp_client	FORBIDDENr   ResourceNotFoundErrorRelativeNamecalliope_exceptionsHttpExceptionserverCaCertsettingsipConfigurationauthorizedNetworksappendSqlInstancesPatchRequestPatchr   warningCreater   r   	Pluralizer   OperationsV1Beta4WaitForOperation)instance_ref
sql_clientsql_messages	resourcesr   time_of_connectionacl_nameuser_acloriginalerrorpatch_requestresultoperation_refmessages                 lib/surface/sql/connect.py_AllowlistClientIPrS   R   s9   : --/&--.@A(""!**../AB
 w5w!))+ # 
(	3##''++ ((<3H3H 	, 	JKH (
##66==hG3 99!$$&& : (M !!''6F ""&++|7K7K # M-vgt~~gx'HI 
 //
079 
/E 
	&	& 3K111,,!6,";";"=>@ @ 
+
+E
223" 
	&	& 3KK	"# 
+
+E
223s2   6=F *A H H,A'HHI /,II c                 ,   UR                   R                  UR                  R                  U R                  U R
                  S95      nUR                  R                  R                  nSnU H#  nUR                  U:X  d  M  UR                  n  X54$    X54$ )z4Retrieves given instance and extracts its client ip.r!   N)r   r.   MESSAGES_MODULEr/   r"   r#   r:   r;   r<   r   r    )rE   rF   rJ   instance_infonetworks	client_ipnets          rR   _GetClientIPrZ      s    &&**  77&&1F1F 8 HI- ##33FF()c
xx8))i		!!	  
	!!    c                 f    U R                  S[        R                  SS9  U R                  SSSSS9  g	)
zDeclare flag and positional arguments for this command parser.

Args:
    parser: An argparse parser that you can use it to add arguments that go on
      the command line after this command. Positional arguments are allowed.
r#   Cloud SQL instance ID.	completerhelp--user-uF&Cloud SQL instance user to connect as.requiredr`   N)add_argument	sql_flagsInstanceCompleterparsers    rR   AddBaseArgsrk      sG     	++#  %
 	
3	  5r[   c                 j    U R                  S[        R                  " SSS9[        R                  SS9  g)zDeclare beta flag arguments for this command parser.

Args:
    parser: An argparse parser that you can use it to add arguments that go on
      the command line after this command. Positional arguments are allowed.
--port     lower_boundupper_boundUPort number that gcloud will use to connect to the Cloud SQL Proxy through localhost.typedefaultr`   N)rf   r   
BoundedIntr
   DEFAULT_PROXY_PORT_NUMBERri   s    rR   AddBetaArgsry      s8     	!!aUC11'	  )r[   c                    U R                  S[        R                  SS9  U R                  S[        R                  " SSS9[
        R                  SS	9  U R                  S
5      nUR                  SSSS9  UR                  SSSSS9  U R                  SSSS9  U R                  SSSS9  U R                  SSSS9  U R                  S5      nUR                  SSSS9  UR                  SSSS9  UR                  SSS S9  g!)"zDeclare alpha flag arguments for this command parser.

Args:
    parser: An argparse parser that you can use it to add arguments that go on
      the command line after this command. Positional arguments are allowed.
r#   r]   r^   rm   rn   ro   rp   rs   rt   z7User selection settings for Cloud SQL Proxy connection.--auto-iam-authn
store_truezTEnables IAM database authentication for connections to MySQL and Postgres instances.)actionr`   ra   rb   Frc   rd   
--skip-sslz6Skip SSL certificate verification for MySQL instances.z--debug-logsz.Enable verbose debug logs for Cloud SQL Proxy.z--run-connection-testz(Run connection test for Cloud SQL Proxy.z=IP address selection settings for Cloud SQL Proxy connection.z--private-ipz3Connect to the Cloud SQL instance using private IP.z--pscz@Connect to the Cloud SQL instance using Private Service Connect.z	--auto-ipz9Connect to the Cloud SQL instance with auto IP detection.N)rf   rg   rh   r   rw   r
   rx   add_mutually_exclusive_group)rj   
user_groupip_groups      rR   AddProxyV2Argsr      s}    	++#  %
 	!!aUC11'	  ) 22?A*!  "
 
3	  5
 	C  E 	;  = 	5  7
 00EG(
@  B M  O F  Hr[   c                    [         R                  " [         R                  5      nUR                  nUR                  n[
        R                  " X5      n[        XSUUR                  5      n[        R                  " SSS9n UR                  [        XSU/S SS9u  pUR                   R"                  R%                  S5      S   n
[&        R(                  R+                  U
S	5      n[,        R.                  " U5      nU(       d4  [        R0                  " S
R3                  UR5                  5       U5      5      e[6        R8                  " U	5      nU[6        R:                  :X  aW  UR<                  R>                  R@                  (       a  URB                  S   RD                  nOOSn[        RF                  " U5      eU[6        RH                  :X  a  URJ                  nO[        RF                  " S5      e[&        RL                  U   nU RN                  (       a  U RN                  n[&        RP                  U   nUUS   U/nURS                  US   U/5        SU;   a  URU                  US   5        U(       a&  URS                  [
        RV                  " U U5      5        [
        RX                  " UU5        g! [        R                   a    [        R                  " S5      ef = f)a  Connects to a Cloud SQL instance directly.

Args:
  args: argparse.Namespace, The arguments that this command was invoked with.
  supports_database: Whether or not the `--database` flag needs to be
    accounted for.

Returns:
  If no exception is raised this method does not return. A new process is
  started and the original one is killed.
Raises:
  HttpException: An http error response was received while executing api
      request.
  UpdateError: An error occurred while updating an instance.
  SqlClientNotFoundError: A local SQL client could not be found.
  ConnectionError: An error occurred while trying to connect to the instance.
   )max_retrialsexponential_sleep_multiplierc                     U S   S L $ )Nrn    )xss     rR   <lambda>#RunConnectCommand.<locals>.<lambda>4  s    QqTT\r[   i  )should_retry_ifsleep_mszLCould not allowlist client IP. Server did not reply with the allowlisted IP._r   mysql~{0} client not found.  Please install a {1} client and make sure it is in PATH to be able to connect to the database instance.zIt seems your client does not have ipv6 connectivity and the database instance does not have an ipv4 address. Please request an ipv4 address for this database instance.z Could not connect to SQL server.hostnameuserpasswordN)-r	   	SqlClientAPI_VERSION_DEFAULTrF   rG   instances_command_utilGetInstanceRefrS   resource_parserr   RetryerRetryOnResultrZ   RetryExceptionr   UpdateErrordatabaseVersionr   splitr
   DB_EXEgetr   FindExecutableOnPathSqlClientNotFoundErrorr(   titler   GetIpVersionIP_VERSION_4r:   r;   ipv4EnabledipAddresses	ipAddressConnectionErrorIP_VERSION_6ipv6AddressDEFAULT_SQL_USERr   	EXE_FLAGSextendr=   GetDatabaseArgsConnectToInstance)argssupports_databaser   rF   rG   rE   rJ   retryerrV   rX   db_typeexe_nameexeip_type
ip_addressrQ   sql_userr   sql_argss                      rR   RunConnectCommandr     s|   $ h::;&  *$$,'66tD,, & 6 68(
 MMqqI'G&44	8,1	  5  M ))..44S9!<'!!'73(""8,#	

+
+	HHNNNhI() )   +'$$$--99 ,,Q/99jNg &&w//'&&&**J

$
$%G
HH ''1(	YYyyH 

h
'%j):6(
//5=(+,5OOE*%&OO*::4GH**8X>[ 
		 G

 
  "F G GGs    J, ,+Kc                    [         R                  " [         R                  5      nUR                  nUR                  n[
        R                  " X5      nUR                  R                  UR                  UR                  UR                  S95      n[        R                  " XF5      (       d  [        X5      $ [        R                   " S5      nU(       d  ["        R$                  " S5      eUR&                  R(                  R+                  S5      S   n[,        R.                  R1                  US5      n	[        R                   " U	5      nU(       d4  ["        R2                  " SR5                  U	R7                  5       U	5      5      e[9        U R:                  5      n
[        R<                  " Xj5      n[>        R@                  " URB                  5        [,        RD                  U	   nU RF                  (       a  U RF                  n[,        RH                  U	   nU	/nU	S:X  a(  S	R5                  U
5      nURK                  US
   U/5        OURK                  US
   SUS   U
/5        URK                  US   U/5        SU;   a  URM                  US   5        U(       a%  URK                  [
        RN                  " X5      5        [
        RP                  " X5        URC                  5         g)a  Connects to a Cloud SQL instance through the Cloud SQL Proxy.

Args:
  args: argparse.Namespace, The arguments that this command was invoked with.
  supports_database: Whether or not the `--database` flag needs to be
    accounted for.

Returns:
  If no exception is raised this method does not return. A new process is
  started and the original one is killed.
Raises:
  HttpException: An http error response was received while executing api
      request.
  CloudSqlProxyError: Cloud SQL Proxy could not be found.
  SqlClientNotFoundError: A local SQL client could not be found.
  ConnectionError: An error occurred while trying to connect to the instance.
r!   cloud_sql_proxya  Cloud SQL Proxy (v1) couldn't be found in PATH. Either install the component with `gcloud components install cloud_sql_proxy` or see https://github.com/GoogleCloudPlatform/cloud-sql-proxy/releases to install the v1 Cloud SQL Proxy. The v2 Cloud SQL Proxy is currently not supported by the connect command. You need to install the v1 Cloud SQL Proxy binary to use the connect command.r   r   r   r   sqlcmdtcp:127.0.0.1,{0}r   	127.0.0.1portr   r   N))r	   r   r   rF   rG   r   r   r   r.   r/   r"   r#   instances_api_utilIsInstanceV2r   r   r   r   CloudSqlProxyErrorr   r   r   r
   r   r   r   r(   r   strr   StartCloudSqlProxyatexitregisterkillr   r   r   r   r=   r   r   )r   r   r   rF   rG   rE   rV   r   r   r   r   proxy_processr   r   r   r   s                   rR   RunProxyConnectCommandr   f  sa   & h::;&  *$$,'66tD,&&**))&&1F1F * HI- 
	(	(	E	ET55 	""#45#	

'
'	&' ' ))..44S9!<'!!'73(""8,#	

+
+	HHNNNhI() ) 
TYY$$77L-//-$$% ''1(	YYyyH 

h
'%Z("))$/HOOU:&12OOU:&U6]DIJ
//5=(+,5OOE*%&OO*::4GH**8>r[   c                 	   [         R                  " [         R                  5      nUR                  nUR                  n[
        R                  " X5      nUR                  R                  UR                  UR                  UR                  S95      n[        R                  " XF5      (       d  [        X5      $ [        R                   " S5      nU(       d  ["        R$                  " S5      eUR&                  R(                  R+                  S5      S   n[,        R.                  R1                  US5      n	[        R                   " U	5      nU(       d4  ["        R2                  " SR5                  U	R7                  5       U	5      5      e[9        U SS	5      n
U
(       a  U	S
:X  a  [:        R<                  " SS5      e[9        U SS	5      nU(       a  U	S:w  a  [:        R<                  " SS5      e[?        U R@                  5      n[B        RD                  RF                  RH                  R                  5       n[9        U SS	5      n[9        U SS	5      n[9        U SS	5      n[9        U SS	5      n[9        U SS	5      n[        RJ                  " UUUU
UUUUUS9	n[L        RN                  " URP                  5        U(       a  URQ                  5         gU
(       a  UnU(       d1  [B        RD                  RR                  RT                  R                  SS9nU	S:X  a  UR+                  S5      S   nO`U	S:X  a(  URW                  S5      (       a  URY                  SS5      nO1U RZ                  (       a  U RZ                  nO[,        R\                  U	   n[,        R^                  U	   nU	/nU	S
:X  a(  SR5                  U5      nURa                  US   U/5        OURa                  US   SUS    U/5        URa                  US!   U/5        S"U;   a  U
(       d  URc                  US"   5        U(       aj  U	S:X  a(  U Rd                  (       a  [:        R<                  " S#S$5      e[
        Rf                  " U U5      nU(       d  U	S:X  a  US%   S&/nURa                  U5        U(       a  U	S:X  a  URc                  S5        [
        Rh                  " UU5        URQ                  5         g)'a  Connects to a Cloud SQL instance through the Cloud SQL Proxy (v2).

Args:
  args: argparse.Namespace, The arguments that this command was invoked with.
  supports_database: Whether or not the `--database` flag needs to be
    accounted for.

Returns:
  If no exception is raised this method does not return. A new process is
  started and the original one is killed.
Raises:
  HttpException: An http error response was received while executing api
      request.
  CloudSqlProxyError: Cloud SQL Proxy (v2) could not be found.
  SqlClientNotFoundError: A local SQL client could not be found.
  ConnectionError: An error occurred while trying to connect to the instance.
r!   zcloud-sql-proxyzCloud SQL Proxy (v2) couldn't be found in PATH. Either install the component with `gcloud components install cloud-sql-proxy` or see https://github.com/GoogleCloudPlatform/cloud-sql-proxy/r   r   r   r   auto_iam_authnFr   r{   zIThe --auto-iam-authn flag is only valid for MySQL and Postgres instances.skip_sslr~   z6The --skip-ssl flag is only valid for MySQL instances.
private_ippscauto_ip
debug_logsrun_connection_test)impersonate_service_accountr   r   r   r   r   r   NT)re   @psqlz.gserviceaccount.com r   r   r   r   r   r   z
--databasezIThe --database flag is only valid for PostgreSQL or SQL Server instances.databasepostgres)5r	   r   r   rF   rG   r   r   r   r.   r/   r"   r#   r   r   r   r   r   r   r   r   r   r   r
   r   r   r   r(   r   getattrr7   InvalidArgumentExceptionr   r   r   VALUESauthr   StartCloudSqlProxyV2r   r   r   coreaccountendswithr,   r   r   r   r   r=   r   r   r   )r   r   r   rF   rG   rE   rV   r   r   r   r   r   r   r   r   r   r   r   r   r   database_userr   r   r   db_argss                            rR   RunProxyV2ConnectCommandr     sC   $ h::;&  *$$,'66tD,&&**))&&1F1F * - 
	(	(	E	ET55 	""#45#	

'
'	B  ))..44S9!<'!!'73(""8,#	

+
+	HHNNNhI
  4!159.H,

6
6	  T:u-((g%

6
6N 
 
TYY$88<<>  t\51*eU##D)U+'t\51*&;UC$99
"=#
-	/- 	//-$$%
 /M '',,4488$8Gm7#))#.q1m	V	 6 67M N N#++,BBGmyyIIM..x8M 

h
'%Z("))$/HOOU:&12OOU:&U6]DIJ
//5=-015OOE*%&7t}}88
 
 %44T5AGx6)z"J/gOOG(g%OOL!**8]Cr[   c                   2    \ rS rSrSr\r\S 5       rS r	Sr
g)ConnectiJ  r   c                 H    [        U 5        [        R                  " U S5        g)@Args is called by calliope to gather arguments for this command.z&The SQL Server database to connect to.N)rk   rg   AddDatabaseri   s    rR   ArgsConnect.ArgsQ  s      8:r[   c                     [        USS9$ r   T)r   )r   selfr   s     rR   RunConnect.RunX  s    TT::r[   r   N)__name__
__module____qualname____firstlineno____doc__DETAILED_GA_HELPdetailed_helpstaticmethodr   r   __static_attributes__r   r[   rR   r   r   J  s#     *"-: :;r[   r   c                   2    \ rS rSrSr\r\S 5       rS r	Sr
g)ConnectBetai]  r   c                 H    [        U 5        [        R                  " U S5        gr   z4The PostgreSQL or SQL Server database to connect to.Nr   rg   r   ri   s    rR   r   ConnectBeta.Argsd  s!     6FHr[   c                     [        USS9$ r   r   r   s     rR   r   ConnectBeta.Runk      #DDAAr[   r   Nr   r   r   r   r   DETAILED_ALPHA_BETA_HELPr   r   r   r   r   r   r[   rR   r   r   ]  s&     **-H HBr[   r   c                   2    \ rS rSrSr\r\S 5       rS r	Sr
g)ConnectAlphaip  r   c                 H    [        U 5        [        R                  " U S5        gr   r   ri   s    rR   r   ConnectAlpha.Argsw  s      6Fr[   c                     [        USS9$ r   r  r   s     rR   r   ConnectAlpha.Run  r  r[   r   Nr  r   r[   rR   r	  r	  p  s$     **- Br[   r	  )   )returnN)F)9r   
__future__r   r   r   r   httpr   r3   apitools.base.pyr   r0   googlecloudsdk.api_lib.sqlr	   r
   r   r   r   r   googlecloudsdk.callioper   r   r7   googlecloudsdk.command_lib.sqlr   rg   r   googlecloudsdk.corer   r   googlecloudsdk.core.utilr   r   r   r   r   r   r  rS   rZ   rk   ry   r   r   r   r   DefaultUniverseOnlyReleaseTracksReleaseTrackGACommandr   BETAr   UniverseCompatibleALPHAr	  r   r[   rR   <module>r      s   ( &  '  & > / 0 1 F . 1 / ( E = N # * * 1 * ) 		 # ,	    !	Rj"5&)8HvQ?j .3RjL^ D%%(();dll ; * ;" D%%**+B$,, B , B" D%%++,B4<< B - Br[   