
    e9                     6   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rSS0r " S S\
R<                  5      r " S S\ 5      r! " S S\ 5      r"g)z"Routes to/from Compute Engine VMs.    )absolute_import)division)unicode_literalsN)base_classes)lister)
exceptions)	ssh_utils)external_helper)internal_helpers)ssh)log)
properties)
console_io)filesEXAMPLESzg        To route to/from Compute Engine virtual machine instances, run:

          $ {command}
        c                   h   ^  \ rS rSrSr\r\S 5       rU 4S jr	S r
S rS rS r\S	 5       rS
rU =r$ )Routes3   ay  Routes to/from Compute Engine virtual machine instances.

Routes to/from Compute Engine virtual machine instances.

NOTE: The name filtering will cycle through all the VMs in the project.
Depending on the size of the project, this could be a considerable amount
of work.

If that is the case, use the --regexp flag to filter down the amount
of VMs considered in the filtering.
c                 .    [         R                  U5        g )N)_RoutesArgsArgsclsparsers     &lib/surface/compute/diagnose/routes.pyr   Routes.ArgsB   s    V    c           
      `  > [         [        U ]  U5        SU l        [        R
                  " U R                  5       5      nUR                  n[        R                  " 5       nUR                  U5        Xl
        X@l        [        R                  R                  R                  R!                  5       n["        R%                  U5      n[&        R)                  UR*                  U R,                  R.                  UUR0                  UU R2                  U R4                  S9nUR6                  nU(       d  [8        R:                  " 5       nUR<                  n	UR>                  n
UR@                  nURB                  n[D        RF                  " U5        SnU(       a#  U	(       d  [H        RJ                  " U5      (       d  g[L        RN                  RQ                  5         U GH(  nSURR                  -  n[L        RN                  RU                  U5        [L        RN                  RU                  S[W        U5      -  5         U RY                  XU	U5        U
(       a   U Re                  XU	U5      nU(       aV  U(       d  U Rg                  XU	U5      nU(       a  U Ri                  XUXU5        O@[L        RN                  RU                  S5        O [L        RN                  RU                  S	5         [L        RN                  RU                  S
5        GM+     g! [Z        R\                   aL  n[L        R^                  " S5        [L        R^                  " [`        Rb                  " U5      5         SnAGM  SnAff = f! [8        Rj                   a4  n[L        R^                  " [`        Rb                  " U5      5         SnANSnAff = f)z"Default run method implementation.F)serviceprojectzonesfiltershttp	batch_urlz&The following VMs will be tracerouted.NzChecking instance %s-zError routing to instancez#Unable to obtain self ip. Aborting.z<Please make sure traceroute is installed in PATH to move on. )6superr   Run_use_accounts_servicer   ComputeApiHolderReleaseTrack	resourcesr	   BaseSSHCLIHelper_args_ssh_helperr   VALUEScorer    	GetOrFailr   
GetFilters_RoutesQueriesObtainInstancesnamescompute	instancesr!   r#   r$   userr   GetDefaultSshUsernamedry_runreverse_traceroutetraceroute_argsexternal_route_ipr   PrintHeaderr   PromptContinuer   outflushnamePrintlenTracerouteInstancer   ToolExceptionerrorsix	text_typeCheckTracerouteObtainSelfIpReverseTracerouteInstanceCommandError)selfargsholderresource_registry
ssh_helperr    r"   r8   r9   r;   r<   r=   r>   promptinstanceheaderehas_traceroute	__class__s                     r   r(   
Routes.RunF   s   	&$D!!&D**4+<+<+>?F((++-JNN4 J! $$,,668G$$T*G..

&&jjYY.. / "I 99D&&(d llG00**O..  +5F)B)B6)J)JGGMMO%5f	ggmmF	ggmmC#f+%&7 1	3 
	&//0AC.$"&"3"3HG4E#G ,,X=N-<->@ ggmmABGGMMNP 
ggmmBC  %% 		-.		#--"#.  	&
))CMM!$
%
%	&s>   2LAM%M%=M%M"A MM"%N-9*N((N-c                    [         R                  " U5      n[        R                  R	                  SU-  5        [
        R                  " U5      nSU/nU(       a  Xr-  nU(       a&  [        R                  " SR                  U5      5        g[        R                  " SUS9  [        R                  R	                  S5        g)a(  Runs a traceroute from localhost to a GCE VM.

Args:
  instance: Compute Engine VM.
  traceroute_args: Additional traceroute args to be passed on.
  dry_run: Whether to only print commands instead of running them.
  resource_registry: gcloud class used for obtaining data from the
    resources.
z>>> Tracerouting to %s
traceroute 
Traceroute)	proc_namecommand_listz>>>N)r   GetInstanceNetworkTitleStringr   rA   rD   r	   GetExternalIPAddressr
   	DryRunLogjoinRunSubprocess)rO   rU   r=   r;   rR   instance_stringexternal_ipcmds           r   rF   Routes.TracerouteInstance   s     'DDXNOGGMM*_<=00:K
%C	c.##lM	ggmmEr   c           	         [         R                  " U5      n[        R                  R	                  SU-  5        [        R                  R                  5         U(       a  SnSU/nU(       a  X-  n[        R                  " UUUU R                  U R                  US9  U(       d   [        R                  R	                  S5        gg)a  Runs a traceroute from a GCE VM to localhost.

Args:
  instance: Compute Engine VM.
  user: The user to use to SSH into the instance.
  external_route_ip: the ip to which traceroute from the VM
  traceroute_args: Additional traceroute args to be passed on.
  dry_run: Whether to only print commands instead of running them.
  resource_registry: gcloud class used for obtaining data from the
    resources.
Raises:
  ssh.CommandError: there was an error running a SSH command
z <<< Reverse tracerouting from %s	<SELF-IP>r\   )r`   rU   r9   rP   rS   r;   z<<<N)
r   ra   r   rA   rD   rB   r
   RunSSHCommandToInstancer.   r/   )	rO   rU   r9   r>   r=   r;   rR   rf   rh   s	            r   rM    Routes.ReverseTracerouteInstance   s     'DDXNOGGMM4FG GGMMO%*
+C	c++ZZ## 	ggmmE r   c                 $   [         R                  " U5      n[        R                  R	                  SU-  5        U(       a  [        R                  R                  S5        [        R                  R                  5         SS/n [        R                  " [        R                  5       n[        R                  " UUUU R                  U R                  UUS9nSSS5        WS	:X  a   [        R                  R                  S
5        O[        R                  R                  S5        [        R                  R                  5         US	:H  $ ! , (       d  f       Nv= f! [         a  n	[        R                  R	                  [         R"                  " U	5      5        [        R                  R	                  S5        [        R                  R                  5         [$        R&                  " SR)                  U5      [         R"                  " U	5      5      eSn	A	ff = f)a  Checks whether the instance has traceroute in PATH.

Args:
  instance: Compute Engine VM.
  user: The user to use to SSH into the instance.
  dry_run: Whether to only print commands instead of running them.
  resource_registry: gcloud class used for obtaining data from the
    resources.
Returns:
  True if the instance has traceroute in PATH,
  False otherwise
Raises:
  ssh.CommandError: there was an error running a SSH command
zChecking traceroute for %s: z[DRY-RUN] No command executed.whichr\   r`   rU   r9   rP   rS   explicit_output_filer;   N
r]   r   zTraceroute found in PATHzTraceroute not found in PATH)r   ra   r   rA   writerD   rB   r   
FileWriterosdevnullr
   rl   r.   r/   	ExceptionrI   rJ   r   rN   rd   )
rO   rU   r9   r;   rR   rf   rh   dev_nullreturn_coderW   s
             r   rK   Routes.CheckTraceroute   sZ    'DDXNOGGMM0?BC	ggmm45GGMMOL
!C>BJJ'8%==''!) ( a	ggmm./	ggmm23GGMMO!) ('  >	ggmmCMM!$%	ggmmD	ggmmoSXXc]CMM!,<==	>s7   $E &/EE 
EE E 
H B*H

Hc           
         [         R                  " U5      n[        R                  R	                  SU-  5        [        R                  R                  5         U(       a  [        R                  R                  S5        [        R                  " 5       nSS/n [        R                  " UUUU R                  U R                  UUS9  UR'                  5       R)                  S	5      n	[*        R,                  " S
U	5      n
U
(       aP  U
R/                  S5      n[        R                  R                  U5        [        R                  R                  5         U$ g! [         a|  n[        R                  R	                  S5        [        R                  R                  5         [        R                  " SR!                  U5      ["        R$                  " U5      5      eSnAff = f)a  Returns the localhost ip as seen from the VM.

Args:
  instance: Compute Engine VM.
  user: The user to use to SSH into the instance.
  dry_run: Whether to only print commands instead of running them.
  resource_registry: gcloud class used for obtaining data from the
    resources.
Returns:
  A string containing the local ip,
  None if the obtaining was unsuccessful
Raises:
  ssh.CommandError: there was an error running a SSH command
zObtaining self ip from %s: rk   echoz$SSH_CLIENTrp   rr   r]   Nzutf-8z$(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})   )r   ra   r   rA   rs   rB   rD   ioBytesIOr
   rl   r.   r/   rw   r   rN   rd   rI   rJ   getvaluedecoderesearchgroup)rO   rU   r9   r;   rR   rf   temprh   rW   who_am_i_strresultress               r   rL   Routes.ObtainSelfIp  sB    'DDXNOGGMM//ABGGMMO	ggmmK ::<D=
!C>--zz%%# ==?))'2LYY>MFLLOc	ggmmC	ggmmoj  >	ggmmD	ggmmoSXXc]CMM!,<==>s   .E 
GA7GGc                     g)Nr8    )rO   s    r   resource_typeRoutes.resource_type4  s    r   )r.   r/   r)   )__name__
__module____qualname____firstlineno____doc__DETAILED_HELPdetailed_helpclassmethodr   r(   rF   rM   rK   rL   propertyr   __static_attributes____classcell__)rY   s   @r   r   r   3   sS    
  - Mf0#J,\.`  r   r   c                   8    \ rS rSrSr\S 5       r\S 5       rSrg)r   i9  z2Helper to setting and getting values for the args.c                 f   [         R                  R                  U5        [        R                  R                  U5        UR                  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SS9  UR                  S[        R                  SSS9  g)z(Creates the flags stmts for the command.z--containeraP              The name or ID of a container inside of the virtual machine instance
            to connect to. This only applies to virtual machines that are using
            a Container-Optimized OS virtual machine image.
            For more information, see
            [](https://cloud.google.com/compute/docs/containers)
            )helpz--external-route-ipNz{For reverse traceroute, this will be the ip given to the VM instance to traceroute to. This will override all obtained ips.)defaultr   z--reverse-traceroute
store_truez<If enabled, will also run traceroute from the VM to the host)actionr   z
--ssh-flagappendaA          Additional flags to be passed to *ssh(1)*. It is recommended that flags
        be passed using an assignment operator and quotes. This flag will
        replace occurences of ``%USER%'' and ``%INSTANCE%'' with their
        dereferenced values. Example:

          $ {command} example-instance --zone us-central1-a           --ssh-flag="-vvv" --ssh-flag="-L 80:%INSTANCE%:80"

        is equivalent to passing the flags ``--vvv'' and ``-L
        80:162.222.181.197:80'' to *ssh(1)* if the external IP address of
        'example-instance' is 162.222.181.197.
        z--userzm        User for login to the selected VMs.
        If not specified, the default user will be used.
        r=   zX            Flags and positionals passed to the underlying traceroute call.
            zC            $ {command} example-instance -- -w 0.5 -q 5 42
        )nargsr   example)r	   r-   r   r   ZonalListeradd_argumentargparse	REMAINDERr   s     r   r   _RoutesArgs.Args<  s     ##F+!!&)    
B	  D K  M   "        r   c                     / nUR                   (       a  UR                  SUR                   -  5        U(       d  g SR                  U5      nU$ )Nz
name eq %sz AND )regexpr   rd   )r   rP   r"   s      r   r3   _RoutesArgs.GetFilters~  s<    G{{nn\DKK/0ll7#GNr   r   N)	r   r   r   r   r   r   r   r3   r   r   r   r   r   r   9  s,    :? ?B  r   r   c                   (    \ rS rSrSr\S 5       rSrg)r4   i  z9Helper for getting instance queries using the gcloud SDK.c           
         / n[         R                  " US   US   US   US   US   US   US9n[        U5      n/ nU(       d  UnU$ U H  nSnSn	Sn
U H<  nX{R                  :X  a  Un  O*X{R                  ;   a  Un	M)  X{R                  ;   d  M:  Un
M>     U(       a  UR                  U5        Me  U	(       a  UR                  U	5        M  U
(       d  M  UR                  U
5        M     U$ )	z3Returns a list of instances according to the flags.r   r    r!   r"   r#   r$   )r   r    requested_zonesfilter_exprr#   r$   errorsN)r   GetZonalResourceslistrC   selfLinkr   )r   r6   kwargsr   r   r8   filtered_instancesrC   
name_matchin_namein_self_linkrU   s               r   r5   _RoutesQueries.ObtainInstances  s    F%%y!y!w9%F^%F VI $4 1 $
!H]]" "J}}$G(((#L " 

#
#J
/

#
#G
,\

#
#L
1- 0 r   r   N)r   r   r   r   r   r   r5   r   r   r   r   r4   r4     s    A* *r   r4   )#r   
__future__r   r   r   r   r~   ru   r   googlecloudsdk.api_lib.computer   r   googlecloudsdk.callioper   "googlecloudsdk.command_lib.computer	   +googlecloudsdk.command_lib.compute.diagnoser
   r   #googlecloudsdk.command_lib.util.sshr   googlecloudsdk.corer   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   rI   r   BaseCommandr   objectr   r4   r   r   r   <module>r      s    ) '  '  	 	 	 7 1 . 8 G H 3 # * 2 * 
 	C\%% CLN& Nb.V .r   