
    P?                     $   S r SSKrSSKrSSK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rS
rSrSrSr\S-   r\S-   r\S-   rS rS rS rS r S r!S r"S r#S r$ " S S\RJ                  5      r&g)Direct Connectivity Diagnostic.    N)	path_util)
diagnostic)gcs_resource_reference)execution_utils)log)	gce_cache)fileszDirect Connectivity CallzSuccess.z[Not Found]z<http://metadata.google.internal/computeMetadata/v1/instance/zoneznetwork-interfaces/0/mtuznetwork-interfaces/0/networkc                      [         R                  " U SS0SS9nUR                  S:X  a  UR                  R	                  5       $  g! [         R
                  R                   a     gf = f)z+Returns response from the Metadata service.zMetadata-FlavorGoogle   )headerstimeout    )requestsgetstatus_codetextstrip
exceptionsRequestException)urlresponses     Qlib/googlecloudsdk/command_lib/storage/diagnose/direct_connectivity_diagnostic.py_get_metadata_service_responser   .   ss    
	||"H-	H s"]]  "" # 
 
			-	- 			s   AA A'&A'c                    / n[         R                  " U S[         R                  S9 H  nUS   [         R                  R                  :X  a2  UR                  [        R                  " US   S   5      US-   45        MV  US   [         R                  R                  :X  d  My  UR                  [        R                  " US   S   5      US-   45        M     U$ )zBReturns IPv4 and IPv6 addresses associated with a regular web URL.i  )portprotor      z IPv6z IPv4)	socketgetaddrinfoIPPROTO_TCPAddressFamilyAF_INET6append	ipaddress
ip_addressAF_INET)dns_pathservice_nameresips       r   _get_ipsr/   >   s    
#xc9K9KLb	!u$$---	jj)&&r!uQx0,2HIJ	A&&&..	.	jj)&&r!uQx0,2HIJ	 M
 
*    c                 Z    U (       a  SR                  U R                  5       5      $ [        $ )Nz"{}")formatlower
_NOT_FOUND)ss    r   !_get_location_string_or_not_foundr6   I   s    %&qwwy	!6J6r0   c                 \    UR                  5       R                  U R                  5       5      $ )z9Returns true if the region is a prefix of the given zone.)r3   
startswith)regionr   s     r   _check_zone_prefixr:   M   s    		 	 	00r0   c                     [         R                  " 5       n[        R                  " U SUR                  S9  UR                  5       R                  5       $ )z1Returns standard output from executing a command.T)no_exitout_func)ioStringIOr   Execwritegetvaluer   )commandouts     r   _exec_and_return_stdoutrE   R   s?    
#yy
 
			r0   c                 H    [         R                  " 5       U -   n[        U5      $ )z6Returns standard output from executing gcloud command.)r   ArgsForGcloudrE   )command_argsrC   s     r   _exec_gcloud_and_return_stdoutrI   ]   s     ))+l:'	 	))r0   c                  J    [        [        5      n U R                  SS5      S   $ )z2Gets the zone of the VM from the Metadata service./   )r   _METADATA_ZONE_URLrsplit)r   s    r   	_get_zonerP   c   s#    +,>?(	a	 	$$r0   c                 N    [         R                  " SR                  U 5      5        g )NzRunning Check: {})r   infor2   )
check_names    r   _log_running_checkrT   i   s    ((%%j12r0   c                      ^  \ rS rSrSr SS\R                  4S jjr\S\	4S j5       r
U 4S jrS rS	 rS
 rS rS rS rS rS rS rS rS r\S\R0                  4S j5       rSrU =r$ )DirectConnectivityDiagnosticm   r   bucket_resourcec                 V   Xl         SU l        SU l        / U l        [	        U5      U l        SU l        SU l        UcR  [        R                  R                  [        R                  " 5       S[        R                  " 5       -   S-   5      U l        g[         R"                  " U5      U l        g)z/Initializes the Direct Connectivity Diagnostic.FrL   Ndirect_connectivity_log_z.txt)_bucket_resource_cleaned_up_process_count_resultsbool_retain_logs_thread_count_vm_zoneospathjointempfile
gettempdirr   generate_random_int_for_path
_logs_pathr
   ExpandHomeDir)selfrX   	logs_paths      r   __init__%DirectConnectivityDiagnostic.__init__p   s     ,DDDMYDDDM




$2245do ++I6dor0   returnc                     g)NzDirect Connectivity Diagnostic rk   s    r   name!DirectConnectivityDiagnostic.name   s    +r0   c                 \   > U R                   (       d  [        [        U ]  5         SU l         gg)zDRestores environment variables and cleans up temporary cloud object.TN)r\   superrV   _post_process)rk   	__class__s    r   	_clean_up&DirectConnectivityDiagnostic._clean_up   s'    ($=?d r0   c                     [         R                  " U R                  5       nU H  nX;   d  M
    SSS5        g   SSS5        g! , (       d  f       g= f)z4Checks if target is substring of a line in the logs.NTF)r
   
FileReaderri   )rk   target_stringfile_readerlines       r   !_generic_check_for_string_in_logs>DirectConnectivityDiagnostic._generic_check_for_string_in_logs   sI    
 
		$//	*k$  
+	* 
+ 	 
+	* s   	AAA
Ac                    U R                  SS5        U R                  SS5        U R                  SS5        U R                  SS5        [        R                  " U R                  5       n[        R
                  " 5       S	S
SSU R                  R                  R                  /-   n[        R                  " UUR                  SS9nSSS5        WS:X  a_  [        R                  " U R                  5       nU H0  n[        R                  " SU5      (       d  M!  [        s  sSSS5        $    SSS5        SU R                  -   $ ! , (       d  f       N= f! , (       d  f       N.= f)zBReturns true if get bucket success over Direct Connectivity infra.ATTEMPT_DIRECT_PATHrL   CLOUDSDK_STORAGE_PREFERRED_APIgrpc_with_json_fallback
GRPC_TRACEhttpGRPC_VERBOSITYdebugz--verbosity=debugstoragebucketsdescribeT)err_funcr<   Nr   zG(?:\[ipv6:(?:%5B)?2001:4860:80[4-7].+\])|(?:\[ipv4:(?:%5B)?34\.126.+\])zFailed. See log at )_set_env_variabler
   
FileWriterri   r   rG   r[   storage_url
url_stringr@   rA   r|   research_SUCCESS)rk   file_writerrC   return_coder~   r   s         r   !_check_core_buckets_describe_call>DirectConnectivityDiagnostic._check_core_buckets_describe_call   s1   0!4(*C 	<0+W5			$//	*k--/







+
+
6
63 g $((
$$k 
+ aDOO,DYYX  O -, - !4??22/ 
+	*  -,s%   )AE3 EE(E
E
E c                 T    U R                  SS9(       a  SU R                  -   $ [        $ )z%Checks if connecting to PSC endpoint.z.p.googleapis.com)r}   zKFound PSC endpoint. For context, search for ".p.googleapis.com" in logs at )r   ri   r   rr   s    r   _check_private_service_connect;DirectConnectivityDiagnostic._check_private_service_connect   s5    --) . 
OO
 Or0   c                 D    [         R                  " 5       (       a  [        $ g)z"Checks if user is inside a GCE VM.z8Detected this command is not being run from within a VM.)r	   GetOnGCEr   rr   s    r   _check_inside_vm-DirectConnectivityDiagnostic._check_inside_vm   s    oEr0   c                      [         R                  " S5        [        $ ! [         R                  R                   a     gf = f)3Checks if user can access Traffic Director service.z(https://directpath-pa.googleapis.com:443z&Unable to connect to Traffic Director.)r   r   r   r   r   rr   s    r   _check_traffic_director_access;DirectConnectivityDiagnostic._check_traffic_director_access   s7    6ll=>o// 656s    ??c                    [         R                  " S5      S4[         R                  " S5      S4/n[        SS5      [        SS5      -   n[        R                  " [        / SQ5      5      nS	nU H  nUS
   S:w  d
  US   (       a  M  S	nUS    H  nSn[         R                  " U5      n	U H   u  p U	R                  U
5      (       a  UnM   M"     [         R                  " U5      nU H  u  pX:X  d  M  UnM     Uc  Mp  [        R                  " SR                  X5      5        SnM     U(       d  M  [        R                  " SR                  US   5      5        SnM     U(       a  g[        $ ! [         a     M  f = f)r   z34.126.0.0/18zDirect Connectivity IPv4z2001:4860:8040::/42zDirect Connectivity IPv6zstorage.googleapis.comzdirectpath-pa.googleapis.comTraffic Director)computezfirewall-ruleslistz--format=jsonF	directionEGRESSdisabledsourceRangesNz Found firewall blocking {}: "{}"TzCTo disable run "gcloud compute firewall-rules update --disabled {}"rs   z1Found conflicting firewalls. See STDERR messages.)r(   
ip_networkr/   jsonloadsrI   	subnet_of	TypeErrorr)   r   errorr2   r   )rk   desired_ip_networksdesired_ip_addressesfirewall_responsefound_any_problemfirewallfound_firewall_problemfirewall_ip_stringblocked_servicefirewall_networkdesired_ip_networkr,   firewall_ipdesired_ip_addresss                 r   _check_firewalls-DirectConnectivityDiagnostic._check_firewalls   s    
		o	.0JK  !67&	
 $  
 	/1CDE 

&B	

 %	+	(	*hz.B$ ( 8
$//0BC0C,))*<== ,o > 1D  **+=>0D,.*O 1E &
))077!
 $(
 + !9. 
 			6(6*+	
 !C &F @O3  s   1E..
E<	;E<	c                    U R                   R                  R                  5       n[        U R                  5      nU R                   R
                  S:X  a{  [        U R                   R                  (       a  U R                   R                  S   OS5      n[        X24;   d  X2:w  a,  SU R                    SU S[        R                  " 5        SU S3	$ U R                   R
                  S:X  a  U R                   R                  (       a  U R                   R                  nU H%  n[        XPR                  5      (       d  M  [        s  $    S	U R                    S
[        US   5       S[        US   5       S[        R                  " 5        SU 3
$ [        U R                   R                  5      nSU R                    S[        R                  " 5        SU SU SU S3$ U R                  (       a   [        XR                  5      (       a  [        $ SR                  U R                   [        U5      [        R                  " 5       U5      $ )z(Checks if bucket has problematic region.r   r   NzRapid storage bucket "z" zone z does not match VM "zA. Transfer performance between the bucket and VM may be degraded.zdual-regionzBucket "z" locations z and rL   z do not include VM "zFound bucket "z"" is in a dual-region. Ensure VM "zT" is in one of the regions covered by the dual-region by looking up the dual-region z\ in the following table: https://cloud.google.com/storage/docs/locations#predefined VM zone zA should start with one of the regions covered by the dual-region .z6Bucket "{}" location {} does not match VM "{}" zone {})r[   locationr3   r6   rb   location_typedata_locationsr4   r"   gethostnamer:   r   r2   )rk   bucket_locationvm_zonebucket_zoneregionsr9   location_strings          r   _check_bucket_region1DirectConnectivityDiagnostic._check_bucket_region  s4    ++44::<O/>G **f45""11 


.
.q
1k
 
-	-1G$T%:%:$;7m ++-.ggY ?NN	
 **m;				-	-''66F66O  t,,- .1'!*=> ?1'!*=> ?&&()	;	
 :



(
(o 4001 2##%& ';;J:K L I ,-Q0 }}+O]]KKoCJJ)/:	 r0   c           	          U R                   (       d  g[        SSS[        R                  " 5       SR	                  U R                   5      S/5      nU(       a  UR                  S5      (       a  [        $  g)	z#Checks if VM has a service account.zAFound no VM zone and, therefore, could not check service account.r   	instancesr   z	--zone={}z/--format=table[csv,no-heading](serviceAccounts)z[{zoCompute VM missing service account. See: https://cloud.google.com/compute/docs/instances/change-service-account)rb   rI   r"   r   r2   r8   r   )rk   service_accountss     r   _check_vm_has_service_account:DirectConnectivityDiagnostic._check_vm_has_service_accountP  sl    ==P54==)97  ,77==o	Qr0   c                 r    [        [        5      nU(       d  gUS:X  a  [        $ [        [        5      nSU S3$ )z(Checks if VM has a MTU of at least 1460.z.Could not determine MTU from metadata service.8896z&Set the MTU of VPC network interface "zv" to 8896 for optimal transfer performance. See: https://cloud.google.com/storage/docs/enable-grpc-api#configure-vpcsc)r   _METADATA_MTU_URLr   _METADATA_NETWORK_URL)rk   mtunetworks      r   _check_vm_mtu*DirectConnectivityDiagnostic._check_vm_mtud  sB    
():
;C=
f}o,-BCG
0	 :P 	Pr0   c           	         [         R                  " S5        [        [        5        U R                  R                  [        R                  " [        U R                  5       SS95        [        5       U l
        U R                  SS4U R                  SS4U R                  SS	4U R                  S
S4U R                  SS4U R                   SS4U R"                  SS44 HH  u  pn [        U5        U" 5       nU R                  R                  [        R                  " UUUS95        MJ     g! [$         a  nUn SnANESnAff = f)zRuns the diagnostic test.zThis diagnostic is experimental. The output may change, and checks may be added or removed at any time. Please do not rely on the diagnostic being present.zCAble to get bucket metadata using Direct Connectivity network path.)rs   resultpayload_descriptionzPrivate Service Connectz^Checks for string in logs containing incompatible PSC endpoint of format "*.p.googleapis.com".zCompute Engine VMzSDirect Connectivity is only accessible from within Compute Engine virtual machines.r   zDDirect Connectivity requires access to the Traffic Director service.	Firewallsz]Direct Connectivity requires access to various IP addresses that may be blocked by firewalls.zBucket Regionz[To get the best performance, the bucket should have a replica in the same region as the VM.zVM has Service Accountz;Direct Connectivity requires the VM have a service account.zVPC Network MTUzADirect Connectivity performs best with a VPC network MTU of 8896.N)r   warningrT   _CORE_CHECK_NAMEr^   r'   r   DiagnosticOperationResultr   rP   rb   r   r   r   r   r   r   r   	Exception)rk   checkrs   descriptionr-   es         r   _run!DirectConnectivityDiagnostic._runr  sn   KK	) '(MM,,!99;.		
	 KDM //%3		
 !!,		
 //		
 !!5		
 %%1		
 ..$I	
 		
_7% [p4 g
 mm

.
."-7%x  s   !D''
D=1D88D=c                 $    U R                  5         g)zSee _clean_up.

Using redundant calls because we can clean up earlier during _run, and
keeping _post_process ensures clean up if _run fails.
N)ry   rr   s    r   rw   *DirectConnectivityDiagnostic._post_process  s     	NNr0   c                 T    [         R                  " U R                  U R                  S9$ )z:Returns the summarized result of the diagnostic execution.)rs   operation_results)r   DiagnosticResultrs   r^   rr   s    r   r   #DirectConnectivityDiagnostic.result  s%     &&YY-- r0   )r[   r\   ri   r]   r^   r`   ra   rb   )N)__name__
__module____qualname____firstlineno____doc__r   GcsBucketResourcerm   propertystrrs   ry   r   r   r   r   r   r   r   r   r   r   rw   r   r   r   __static_attributes____classcell__)rx   s   @r   rV   rV   m   s    '
 7-??70 ,C , ,	 3DF6:x7r([z j11  r0   rV   )'r   r>   r(   r   rc   r   r"   rf   "googlecloudsdk.command_lib.storager   +googlecloudsdk.command_lib.storage.diagnoser   ,googlecloudsdk.command_lib.storage.resourcesr   googlecloudsdk.corer   r   googlecloudsdk.core.credentialsr	   googlecloudsdk.core.utilr
   r   r   r   r4   _METADATA_BASE_URLrN   r   r   r   r/   r6   r:   rE   rI   rP   rT   
DiagnosticrV   rq   r0   r   <module>r      s    & 	   	 	   8 B O / # 5 *  . 
B  (&0 &)CC *-KK  71
 *%3p:#8#8 pr0   