
    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rSSKrSrSrSrSr " S S\
R<                  5      r " S S\5      r " S S\5      r  " S S\5      r! " S S\5      r"S r#S r$S r%  S$S  jr&S%S! jr' " S" S#\(5      r)g)&z<Implementations of installers for different component types.    )absolute_import)division)unicode_literalsN)
exceptions)local_file_adapter)log)
properties)	transport)
console_io)files)http_encoding)retryUPDATE_MANAGER<      i @  c                       \ rS rSrSrSrg)Error1   z)Base exception for the installers module. N__name__
__module____qualname____firstlineno____doc____static_attributes__r       -lib/googlecloudsdk/core/updater/installers.pyr   r   1       1r   r   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )ComponentDownloadFailedError6   zBException for when we cannot download a component for some reason.c                 t   > [         [        U ]  SR                  US9[        R
                  " U5      -   5        g )Nz4The component [{component_id}] failed to download.

)component_id)superr!   __init__formatsix	text_type)selfr$   e	__class__s      r   r&   %ComponentDownloadFailedError.__init__9   s;    	
&6@GG% 	H 	'),q)9	:;r   r   r   r   r   r   r   r&   r   __classcell__r,   s   @r   r!   r!   6   s    J; ;r   r!   c                       \ rS rSrSrSrg)URLFetchError?   z)Exception for problems fetching via HTTP.r   Nr   r   r   r   r2   r2   ?   r   r   r2   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )AuthenticationErrorD   z?Exception for when the resource is protected by authentication.c                 `   > [         [        U ]  US-   [        R                  " U5      -   5        g )Nz

)r%   r5   r&   r(   r)   )r*   msgr+   r,   s      r   r&   AuthenticationError.__init__G   s%    	
t-cFlS]]1=M.MNr   r   r.   r0   s   @r   r5   r5   D   s    GO Or   r5   c                       \ rS rSrSrSrg)UnsupportedSourceErrorK   zGAn exception when trying to install a component with an unknown source.r   Nr   r   r   r   r;   r;   K   s    Or   r;   c                    SSK Jn  U R                  [        R                  5      (       a/  U R                  [        R                  [        R                  S5      n S[        R                  " [        R                  " U5      5      S.n[        nU[        :X  a  [        n [        XUS9$ ! [        R                   R"                   Ga>  nUR$                  R&                  S:w  d8  UR$                  R(                  R                  [        R                  5      (       d  Ue UR+                  SS	9nUR-                  U5        O(! [.        R0                   a  n[3        S
U5      eSnAff = f [        XUS9s SnA$ ! [        R                   R"                   aj  nUR$                  R&                  S:w  a  Ue[3        SR5                  [6        R8                  R:                  R<                  R?                  5       S9U5      eSnAff = fSnAff = f)a  Gets the request object for the given URL using the requests library.

If the URL is for cloud storage and we get a 403, this will try to load the
active credentials and use them to authenticate the download.

Args:
  url: str, the URL to download.
  command_path: str, the command path to include in the User-Agent header if
    the URL is HTTP.

Raises:
  AuthenticationError: If this download requires authentication and there
    are no credentials or the credentials do not have access.

Returns:
  requests.Response object
r   )store   s   no-cache)s   Cache-Controls
   User-Agent)headerstimeouti  T)use_google_authz5This component requires valid credentials to install.NzAccount [{account}] does not have permission to install this component.  Please
ensure that this account should have access or run:

$ gcloud config set account `ACCOUNT`

to choose another account.)account) googlecloudsdk.core.credentialsr>   
startswithComponentInstallerGCS_BROWSER_DL_URLreplaceGCS_API_DL_URLr   Encoder
   MakeUserAgentStringTIMEOUT_IN_SECUPDATE_MANAGER_COMMAND_PATHUPDATE_MANAGER_TIMEOUT_IN_SEC_RawRequestrequestsr   	HTTPErrorresponsestatus_codeurlLoadFreshCredentialapplycreds_exceptionsr   r5   r'   r	   VALUEScorerC   Get)rT   command_pathr>   r@   rA   r+   credss          r   MakeRequestr]   P   s   & 4^^&99::
++(;;(77<C 


y<<\J
K	' '00+G6sW==				&	& 6zz$AJJNN,E,E))-+ -+gF'''=ekk'!! F  
A1F FF
6w??(( 6	
		3	&   %f""**..0 % 2346 666sb   	B( (HAH  D=<H =E"EE""H &	E5/H5G=A%G88G==H  Hc                  8   S nS n[         R                  " SSSUS9n UR                  [        U UUSS9$ ! [         R                   aO  nUR
                  S	   (       a5  [        R                  " UR
                  S	   S	   UR
                  S	   S   S
9  e SnAff = f)zExecutes an HTTP request.c                 |    U [         R                  R                  :H  =(       a    UR                  R                  S:H  $ )Ni  )rP   r   rQ   rR   rS   )exc_type	exc_valueunused_tracebackunused_states       r   RetryIf_RawRequest.<locals>.RetryIf   s4    ++555 2**c13r   c                 0    [         R                  " S5        g )NzRetrying request...)r   debug)unused_resultrc   s     r   StatusUpdate!_RawRequest.<locals>.StatusUpdate   s    II#$r   r      d   )max_retrialsexponential_sleep_multiplier	jitter_msstatus_update_funci  )should_retry_ifsleep_msr?   )tbN)r   RetryerRetryOnException!_ExecuteRequestAndRaiseExceptionsRetryExceptionlast_resultr   reraise)argskwargsrd   ri   retryerr+   s         r   rO   rO      s    3% MM#$%	''

##) $   
		 
}}Qq)!,q1A!1DE		
s   6 B
A
BBc                     SSK Jn  UR                  5       nU R                  S5      (       a%  UR	                  S[
        R                  " 5       5        UR                  XUSS9nUR                  5         U$ )a>  Executes an HTTP request using requests.

Args:
  url: str, the url to download.
  headers: obj, the headers to include in the request.
  timeout: int, the timeout length for the request.

Returns:
  A response object from the request.

Raises:
  requests.exceptions.HTTPError in the case of a client or server error.
r   )rP   zfile://T)r@   rA   stream)	googlecloudsdk.corerP   
GetSessionrE   mountr   LocalFileAdaptergetraise_for_status)rT   r@   rA   core_requestsrequests_sessionrR   s         r   rv   rv      sl     <"--/^^I9&8&I&I&KL!!	GD " :(
	/r   c                 D   U=(       d    [         R                  n[        R                  R	                  U5      (       d  [
        R                  " U5        [        R                  R                  U[        R                  R                  U 5      5      n[        R                  R	                  U5      (       a  [        R                  " U5         [        X5      n[
        R                  " U5       nSn[        UR                  5      nUR                  [        S9 H,  n	UR!                  U	5        U[        U	5      -  nU" Xx-  5        M.     SSS5        U" S5        U$ ! , (       d  f       N= f! ["        R$                  R&                  [(        4 a  n
[+        U
5      eSn
A
ff = f)a  Download the given tar file.

Args:
  url: str, The URL to download.
  download_dir: str, The path to put the temporary download file into.
  progress_callback: f(float), A function to call with the fraction of
    completeness.
  command_path: the command path to include in the User-Agent header if the
    URL is HTTP

Returns:
  str, The path of the downloaded tar file.

Raises:
  URLFetchError: If there is a problem fetching the given URL.
r   )
chunk_sizeNr?   )r   DefaultProgressBarCallbackospathexists
file_utilsMakeDirjoinbasenameremover]   BinaryFileWriterlencontentiter_contentWRITE_BUFFER_SIZEwriterP   r   rQ   OSErrorr2   )rT   download_dirprogress_callbackr[   download_file_pathrR   fptotal_written
total_sizechunkr+   s              r   DownloadTarr      s;   $ (P:+P+P		%	%|$ww||L"''2B2B32GHWW^^&''II !3-H		$	$%7	8Bmx''(j((4E(F%
U#-45 G 
9 a 
 
9	8 


'
'	1 

s1   !E+ -AEE+ 
E($E+ +$FFFc                    U=(       d    [         R                  n[        R                  R	                  U5      (       d  [
        R                  " U5        [        R                  " U S9 nUR                  5       n[        U5      n/ n[        USS9 GH  u  pxUR                  UR                  5       (       a  UR                  S-   OUR                  5        UR                  X5        [        R                  R!                  XR                  5      n	[        R                  R#                  U	5      (       a`  [        R$                  " U	[        R&                  5      (       d6  [        R(                  " U	[*        R,                  [*        R.                  -  5        U" Xu-  5        GM     U" S5        SSS5        [        R0                  " U 5        W$ ! , (       d  f       N&= f)a@  Extracts the given archive.

Args:
  downloaded_archive: str, The path to the archive downloaded previously.
  extract_dir: str, The path to extract the tar into.
  progress_callback: f(float), A function to call with the fraction of
    completeness.

Returns:
  [str], The files that were extracted from the tar file.
)namer?   )start/N)r   r   r   r   r   r   r   tarfileopen
getmembersr   	enumerateappendisdirr   extractr   isfileaccessW_OKchmodstatS_IWUSRS_IREADr   )
downloaded_archiveextract_dirr   tarmemberstotal_filesr   nummember	full_paths
             r   
ExtractTarr      s2    (P:+P+P		$	${#||+,nnGg,KE 2ll6;;$FKKH	kk&&'',,{KK8i			"	"299Y+H+H
DLL56)* 3 a -  ))	,# -,s   (EG


Gc                   L    \ rS rSrSrSrSrSrS rSS jr	SS	 jr
  SS
 jrSrg)rF   i  zBA class to install Cloud SDK components of different source types.z	.downloadz!https://storage.cloud.google.com/zhttps://storage.googleapis.com/c                     Xl         X l        [        R                  R	                  U R                  [
        R                  5      U l        g)zInitializes an installer for components of different source types.

Args:
  sdk_root:  str, The path to the root directory of all Cloud SDK files.
  state_directory: str, The path to the directory where the local state is
    stored.
N)_ComponentInstaller__sdk_root$_ComponentInstaller__state_directoryr   r   r   rF   DOWNLOAD_DIR_NAME'_ComponentInstaller__download_directory)r*   sdk_rootstate_directorys      r   r&   ComponentInstaller.__init__%  s7     O, " 2 D D!FDr   Nc                     UR                   nU(       d  gUR                  S:X  a  U R                  XUS9$ [        SR	                  UR                  S95      e)ar  Downloads the given component for whatever source type it has.

Args:
  component: schemas.Component, The component from the snapshot to install.
  progress_callback: f(float), A function to call with the fraction of
    completeness.
  command_path: the command path to include in the User-Agent header if the
    URL is HTTP

Returns:
  Optional[str], The path of the downloaded archive, or None if the
    component has no actual sources.

Raises:
  UnsupportedSourceError: If the component data source is of an unknown
    type.
  URLFetchError: If the URL associated with the component data source
    cannot be fetched.
Nr   r   r[   z4tar is the only supported source format [{datatype}])datatype)datatype_DownloadTarr;   r'   )r*   	componentr   r[   r   s        r   DownloadComponentInstaller.Download2  sg    ( >>DyyE
#  % % !>EEYY 	F 	 ! !r   c                 4    Uc  / $ [        XR                  US9$ )aP  Extracts the archive previously downloaded from self.Download().

Args:
  downloaded_archive: Optional[str], The path to the archive downloaded
    previously.
  progress_callback: f(float), A function to call with the fraction of
    completeness.

Returns:
  list of str, The files that were installed or [] if nothing was installed.
)r   )r   r   )r*   r   r   s      r   ExtractComponentInstaller.ExtractU  s&     !iOO+- -r   c                 F   UR                   R                  nU(       d  g[        R                  " SU5      (       d$  [	        SR                  UR                  5      5      e [        X@R                  UUS9$ ! [        [        4 a  n[        UR                  U5      eSnAff = f)a  Download implementation for a component with source in a .tar.gz.

Downloads the .tar for the component and returns its path.

Args:
  component: schemas.Component, The component to install.
  progress_callback: f(float), A function to call with the fraction of
    completeness.
  command_path: the command path to include in the User-Agent header if the
    URL is HTTP

Returns:
  Optional[str], The path of the downloaded archive, or None if the
    component has no actual sources.

Raises:
  ValueError: If the source URL for the tar file is relative, but there is
    no location information associated with the snapshot we are installing
    from.
  URLFetchError: If there is a problem fetching the component's URL.
Nz^\w+://zhCannot install component [{0}] from a relative path because the base URL of the snapshot is not defined.r   )r   sourceresearch
ValueErrorr'   idr   r   r2   r5   r!   )r*   r   r   r[   rT   r+   s         r   r   ComponentInstaller._DownloadTari  s    . ..

C99Z%% Ny||,. .:
((<M#% % ./ :(q99:s    A5 5B BB )__download_directory
__sdk_root__state_directoryNunknownN)r   r   r   r   r   r   rG   rI   r&   r   r   r   r   r   r   r   rF   rF     s8    J!
 ; 5.F!!F-( 7; )&:r   rF   r   r   )*r   
__future__r   r   r   r   r   r   r   r   r   r   r   r	   r
   googlecloudsdk.core.consoler   rD   rW   googlecloudsdk.core.utilr   r   r   r   rP   r(   rM   rL   rN   r   r   r!   r2   r5   r;   r]   rO   rv   r   r   objectrF   r   r   r   <module>r      s     C &  ' 	 	   * 2 # * ) 2 J 8 2 *  
 /  !  J 
;5 ;E 
O% OU 
@6F
:4 6:&&R!Hx: x:r   