
    |!                         S r SSKrSSKJ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
rS r   SS jr " S S5      rg)z+Library to SSH into a Cloud Run Deployment.    N)Sequence)apis)
iap_tunnel)	ssh_utils)ssh)log)requestszFhttps://www.gstatic.com/cloud-run/ssh-ca-public-keys/keys-{region}.pubc                     [         R                  " SS5      n[         R                  " SS5      nUR                  U S9nUR                  R                  U5      nUR                  $ )zBReturns the Cloud project number associated with the `project_id`.cloudresourcemanagerv1)	projectId)r   GetMessagesModuleGetClientInstance&CloudresourcemanagerProjectsGetRequestprojectsGetprojectNumber)
project_idcrm_message_moduleresource_managerreqprojects        %lib/googlecloudsdk/api_lib/run/ssh.pyProjectIdToProjectNumberr   $   sg    --.DdK++,BDIAA 	B 	# %%))#.'			    c	                     0 n	X9S'   XIS'   XS'   XiS'   XyS'   [         R                  " 5       n
U R                  U
l        Xl        XZl        X*l        U(       a  U
R                  R                  SU-   5        U
$ )aD  Construct an SshTunnelArgs from command line args and values.

Args:
  track: ReleaseTrack, The currently running release track.
  project_number: str, the project number (string with digits).
  project: str, the project id.
  deployment_name: str, the name of the deployment.
  workload_type: Ssh.WorkloadType, the type of the workload.
  region: str, the region of the deployment.
  instance_id: str, the instance id (optional).
  container_id: str, the container id (optional).
  iap_tunnel_url_override: str, the IAP tunnel URL override (optional).

Returns:
  SshTunnelArgs.
deployment_nameworkload_typeproject_numberinstance_idcontainer_idz--iap-tunnel-url-override=)	r   SshTunnelArgsprefixtrackcloud_run_argsregionr   pass_through_argsappend)r$   r   r   r   r   r&   r    r!   iap_tunnel_url_overrider%   ress              r   CreateSshTunnelArgsr+   /   s    8 .&5"#$1!%3!""-#/   "#ll#)%*+  $'>>@ 
*r   c                       \ rS rSrSr " S S\R                  5      rS\R                  S\4S jr
S rS	 rS
 rS\\   S-  4S jrSrg)Ssh_   z SSH into a Cloud Run Deployment.c                   (    \ rS rSrSrSrSrSrSrSr	g)	Ssh.WorkloadTypeb   zThe type of the deployment.worker_pooljobserviceinstance N)
__name__
__module____qualname____firstlineno____doc__WORKER_POOLJOBSERVICEINSTANCE__static_attributes__r6   r   r   WorkloadTyper0   b   s    %K
CGHr   rA   argsr   c                 b   UR                   U l         X l        UR                  U l        [        UR                  5      U l        [        USS5      U l        [        USS5      U l        UR                  U l        UR                  U l	        [        USS5      U l
        U R                  5       U l        g)zInitialize the SSH library.r5   N	containerr)   )r   r   r   r   r   getattrr5   rD   r&   release_trackr)   _GetServiceAccountFromWorkloadservice_account)selfrB   r   s      r   __init__Ssh.__init__j   s    //D&<<DL24<<@DD*d3DMT;5DN++DK++D#*'$D   >>@Dr   c           	         S/nU R                   U R                  R                  :X  a  UR                  / SQ5        OU R                   U R                  R                  :X  a  UR                  / SQ5        OU R                   U R                  R
                  :X  a  UR                  / SQ5        OPU R                   U R                  R                  :X  a  UR                  / SQ5        O[        SU R                    35      eUR                  U R                  SU R                  SU R                  S	S
/5         [        R                  " U[        R                  S9n[        R                  " U5      nUR!                  S0 5      R!                  S0 5      nUR!                  S0 5      R!                  S0 5      R!                  S5      nUS:X  a  [        S5      eUR!                  S0 5      R!                  S5      nU(       d  [        S5      eU$ ! [        R"                   a-  n[        SUR$                  R'                  S5       35      UeSnAff = f)z:Retrieves the service account from the Cloud Run workload.gcloud)runservicesdescribe)betarN   zworker-poolsrP   )rN   jobsrP   )alpharN   	instancesrP   zUnsupported workload type: z--regionz	--projectz--formatjson)stderrspectemplatemetadataannotationsz(run.googleapis.com/execution-environmentgen1z4SSH is not supported for Cloud Run gen1 deployments.serviceAccountNamez'Service account not found for workload.zError describing deployment: zutf-8N)r   rA   r>   extendr<   r=   r?   
ValueErrorr   r&   r   
subprocesscheck_outputPIPErU   loadsgetCalledProcessErrorrV   decode)rI   commandoutputservice_datarX   execution_environmentrH   es           r   rG   "Ssh._GetServiceAccountFromWorkloady   s   jGT..666nn45			t00<<	<nn@A			t0044	4nn01			t0099	9nn>?4T5G5G4HIJJNN &&wzGf ZZ'l!!&"-11*bAh
,,z2
&3}b!39: 
 
&	(OPP VR0445IJoBCC# (( )!((//'*B)C
Ds   3#H I(IIc                     g)z2Returns the host key alias for the SSH connection.zcloud-run-defaultr6   )rI   s    r   HostKeyAliasSsh.HostKeyAlias   s    r   c                    [         R                  R                  5       nUR                  5         [         R                  R                  5       nUR                  SS9  Sn[         R                  " SSUUR                  5       R                  5       SU R                  U R                  U R                  U R                  U R                  U R                  S.S9  [         R                   " U R                  U R                  U R                  U R                  S9nU R#                  5       n[         R$                  " XS5      nU R'                  5       nU(       aG  [         R(                  R+                  5       nUR-                  U[/        U5      S9  UR1                  5         [3        U R                  U R4                  U R                  U R                  U R                  U R                  U R6                  U R8                  U R:                  5	      n	[<        R>                  " 5       n
U
RA                  US	S
9n[         RB                  " UUU	UURD                  S9RG                  U5      $ )zRun the SSH command.F)	overwriterootN)r   r   r&   rH   r   )cloud_run_params)r   r&   
deploymentr   )host_patternca_public_keysno)host_key_aliasstrict_host_key_checking)remote	cert_fileiap_tunnel_argsoptionsidentity_file)$r   EnvironmentCurrent
RequireSSHKeysFromFilenameEnsureKeysExistGetOsloginStateGetPublicKeyToEntryrF   r   r   r&   rH   r   CertFileFromCloudRunDeploymentrm   Remote_FetchSshCaPublicKeys
KnownHostsFromDefaultFileAddCertAuthoritylistWriter+   r   r5   rD   r)   r   BaseSSHCLIHelper	GetConfig
SSHCommandkey_fileRun)rI   envkeysuserrz   	dest_addrry   ca_keysknown_hostsr{   
ssh_helperssh_optionss               r   r   Ssh.Run   s   
//
!
!
#CNN88  "D5)D ##%#33,,kk#33!//
 22{{''((	I !!#IZZ	(F((*GNN224k"" g #  )$$
O ++-J&& !% ' K
 >>'mm 
c#hr   returnNc                 R   [         R                  U R                  S9n [        R                  " 5        nUR                  USS9nSSS5        WR                  S:w  a#  [        R                  " SUUR                  5        gUR                  R                  5        Vs/ s H)  oDR                  5       (       d  M  UR                  5       PM+     sn$ ! , (       d  f       N= fs  snf ! [        R                  R                  R                   a    [        R                  " SUSS	9   gf = f)
zRetrieves the CA public keys for the current region from a gstatic URL.

Returns:
  A Sequence of strings, where each string is a public key, or None if
  the keys could not be fetched.
)r&   
   )timeoutN   zDFailed to fetch SSH CA public keys from %s. Received status code: %sz+Failed to fetch SSH CA public keys from %s.T)exc_info)SSH_CA_PUBLIC_KEY_URL_TEMPLATEformatr&   core_requests
GetSessionrc   status_coder   debugtext
splitlinesstripr	   
exceptionsRequestException)rI   endpointsessionresponseks        r   r   Ssh._FetchSshCaPublicKeys   s     .44DKK4HHJ##%;;x;4 & 
			$		  		
 !)!9!9!;I!;Awwyiaggi!;II% &%$ J! !!,,== 	ii
7

 s4   C% CC% C 8C 
CC% %>D&%D&)
rD   r   r)   r5   r   r   r&   rF   rH   r   )r7   r8   r9   r:   r;   enumEnumrA   argparse	NamespacerJ   rG   rm   r   r   strr   r@   r6   r   r   r-   r-   _   sZ    (TYY A8-- Al A+ZAFJXc]T%9 Jr   r-   )NNN)r;   r   collections.abcr   r   rU   r_   googlecloudsdk.api_lib.utilr   "googlecloudsdk.command_lib.computer   r   #googlecloudsdk.command_lib.util.sshr   googlecloudsdk.corer   r	   r   r   r   r+   r-   r6   r   r   <module>r      sZ    2  $    , 9 8 3 # 9 M 
$  -`jJ jJr   