
    H                     `   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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\
R&                  5      r " S S\5      rSr " S S\5      rS S jr           S!S jrS rSrSrS\-   rS"S jr S#S jrS r S r!S r"g)$z-Utilities for loading and parsing kubeconfig.    )absolute_import)division)unicode_literalsN)config)
exceptions)log)
properties)yaml)encoding)files)	platformsc                       \ rS rSrSrSrg)Error#   z0Class for errors raised by kubeconfig utilities. N__name__
__module____qualname____firstlineno____doc____static_attributes__r       2lib/googlecloudsdk/api_lib/container/kubeconfig.pyr   r   #   s    8r   r   c                       \ rS rSrSrSrg)MissingEnvVarError'   zDAn exception raised when required environment variables are missing.r   Nr   r   r   r   r   r   '   s    Lr   r   gke_gcloud_auth_plugin_cachec                       \ rS rSrSrS r\S 5       r\S 5       rS r	S r
S r\S	 5       r\S
 5       r\S 5       r\S 5       r\S 5       rS rSrg)
Kubeconfig.   z1Interface for interacting with a kubeconfig file.c                    X l         Xl        0 U l        0 U l        0 U l        S n U R                  S    H  nUnX@R                  US   '   M     U R                  S    H  nUnXPR                  US   '   M     U R                  S    H  nUnX`R                  US   '   M     g ! [
         a  n[        SR                  Xs5      5      eS nAff = f)Nclustersnameuserscontextsz(expected key {0} not found for entry {1})	_filename_datar#   r%   r&   KeyErrorr   format)selfraw_datafilenameentryclusterusercontexterrors           r   __init__Kubeconfig.__init__1   s    NJDMDJDMEZZ
+')0gfo& , **W%$#'

4<  & ZZ
+')0gfo& ,  
4
;
;E
I s   A;B! !
C
+CC
c                      U R                   S   $ Ncurrent-contextr(   r+   s    r   current_contextKubeconfig.current_contextJ   s    ::'((r   c                     U R                   $ N)r'   r9   s    r   r-   Kubeconfig.filenameN   s    >>r   c                 
   U R                   R                  US 5        U R                  R                  US 5        U R                  R                  US 5        U R                  R                  S5      U:X  a  SU R                  S'   g g )Nr7    )r&   popr#   r%   r(   get)r+   keys     r   ClearKubeconfig.ClearR   sf    MMc4 MMc4 JJNN3zz~~'(C/&(djj"# 0r   c                    [        U R                  R                  5       5      U R                  S'   [        U R                  R                  5       5      U R                  S'   [        U R
                  R                  5       5      U R                  S'   [        R                  " U R                  SS9 n[        R                  " U R                  U5        SSS5        [        R                  R                  U R                  5      n[        R                  R                  U[        5      n[        R                  R!                  U5      (       a  [        R"                  " US5        gg! , (       d  f       N= f)znSave kubeconfig to file.

Raises:
  Error: don't have the permission to open kubeconfig or plugin cache file.
r#   r%   r&   T)privateNr@   )listr#   valuesr(   r%   r&   
file_utils
FileWriterr'   r
   dumpospathdirnamejoin&GKE_GCLOUD_AUTH_PLUGIN_CACHE_FILE_NAMEexistsWriteFileAtomically)r+   fprO    gke_gcloud_auth_plugin_file_paths       r   
SaveToFileKubeconfig.SaveToFileY   s     "$--"6"6"89DJJztzz0023DJJw!$--"6"6"89DJJz			t~~t	<
ii

B 
= ggoodnn-G')ww||7($ 
ww~~677$$%ErJ 8 
=	<s   0"E$$
E2c                      XR                   S'   g r6   r8   )r+   r1   s     r   SetCurrentContextKubeconfig.SetCurrentContextp   s    $+JJ !r   c           
         U(       d  [        S5      e S HB  n[        X   [        5      (       a  M  [        SR                  X   [	        X   5      5      5      e   g! [
         a  n[        SR                  U5      5      eSnAff = f)z2Make sure we have the main fields of a kubeconfig.z
empty file)r#   r%   r&   zinvalid type for {0}: {1}zexpected key {0} not foundN)r   
isinstancerH   r*   typer)   )clsdatarC   r2   s       r   	_ValidateKubeconfig._Validates   s~     ,>2#$)T**)00DOL  3
  >.55e<==>s   A *A 
B'BBc                      [         R                  " U5      nU R                  U5        U " X!5      $ ! [         R                   a)  n[        SR                  XR                  5      5      eS nAff = f)Nz&unable to load kubeconfig for {0}: {1})r
   	load_pathr   r*   inner_errorr`   )r^   r-   r_   r2   s       r   LoadFromFileKubeconfig.LoadFromFile   sh    ^^H%d MM$t :: 
2
9
9)) s   1 A.$A))A.c                    [         R                  R                  U5      (       a  [        SR	                  U5      5      e[         R                  R                  U5      (       a   U R                  U5      $ [        R                  " [         R                  R                  U5      5        U " [        5       U5      nUR                  5         U$ ! [        [        4 a/  n[        R                  " SR	                  X!5      5         SnANSnAff = f)zARead in the kubeconfig, and if it doesn't exist create one there.z*{0} is a directory. File must be provided.z6unable to load default kubeconfig: {0}; recreating {1}N)rM   rN   isdirIsADirectoryErrorr*   isfilere   r   IOErrorr   debugrJ   MakeDirrO   EmptyKubeconfigrV   )r^   rN   r2   
kubeconfigs       r   LoadOrCreateKubeconfig.LoadOrCreate   s     
ww}}T
6
=
=d
C  
ww~~d
%% rwwt,-_&-J W 
		DKK	
 	

s   $C D
%DD
c                 H    U R                  [        R                  5       5      $ r=   )rp   r    DefaultPath)r^   s    r   DefaultKubeconfig.Default   s    J22455r   c                     [         R                  " [        R                  S5      n U (       aP  U R	                  [        R
                  5      nU H+  n U (       d  M  [        R                  R                  U 5      s  $    [         R                  " [        R                  S5      nU(       d  [        R                  R                  5       (       a  [         R                  " [        R                  S5      n[         R                  " [        R                  S5      nU(       a&  U(       a  [        R                  R                  X45      nU(       d%  [         R                  " [        R                  S5      nU(       dC  [        SR                  [        R                  R                  5       (       a  SS95      eSS95      e[        R                  R                  US	S
5      $ )z(Return default path for kubeconfig file.
KUBECONFIGHOME	HOMEDRIVEHOMEPATHUSERPROFILEzVenvironment variable {vars} or KUBECONFIG must be set to store credentials for kubectlz&HOMEDRIVE/HOMEPATH, USERPROFILE, HOME,)varsz.kuber   )r   GetEncodedValuerM   environsplitpathseprN   abspathr   OperatingSystem	IsWindowsrP   r   r*   )ro   kubeconfigshome_dir
home_drive	home_paths        r   rs   Kubeconfig.DefaultPath   sN    ))"**lCJ$$RZZ0k#*:,
, $ ''

F;H	11;;==++BJJDj**2::zBi		77<<
6++BJJF$$*F**4466 < %+ % 
  %+ %  77<<'844r   c                 ^   U R                  U R                  =(       d    UR                  5        [        [        UR                  R                  5       5      [        U R                  R                  5       5      -   5      U l        [        [        UR                  R                  5       5      [        U R                  R                  5       5      -   5      U l        [        [        UR                  R                  5       5      [        U R                  R                  5       5      -   5      U l        g)zMerge another kubeconfig into self.

In case of overlapping keys, the value in self is kept and the value in
the other kubeconfig is lost.

Args:
  kubeconfig: a Kubeconfig instance
N)rY   r:   dictrH   r#   itemsr%   r&   )r+   ro   s     r   MergeKubeconfig.Merge   s     	4//M:3M3MNZ  &&()D1D1D1F,GGDM d:++1134tDJJ<L<L<N7OOPDJZ  &&()D1D1D1F,GGDMr   )r(   r'   r#   r&   r%   N)r   r   r   r   r   r3   propertyr:   r-   rD   rV   rY   classmethodr`   re   rp   rt   staticmethodrs   r   r   r   r   r   r    r    .   s    92 ) )  )K., > > 
 
  ( 6 6 5 5@r   r    c                     SU0nU(       a  U(       a  [        S5      eU(       a  X%S'   OUb  U(       d  X5S'   OU(       d  SUS'   XS.$ )z0Generate and return a cluster kubeconfig object.serverz'cannot specify both ca_path and ca_datazcertificate-authorityzcertificate-authority-dataTzinsecure-skip-tls-verify)r$   r/   )r   )r$   r   ca_pathca_datahas_dns_endpointr/   s         r   Clusterr      sX     ' 
9
::'.#$#3,3()*.G&'	++r   c                 ,   U(       d'  U(       a  U(       d  U(       a  U	(       d  [        S5      e0 n[        5       nU(       aB  U(       d  U(       d  U(       d  U(       d  U(       d  [        UUUUUS9US'   O[        U
5      US'   U(       a  U(       a  [        S5      eU(       a  XlS'   OU(       a  X|S'   U(       a  U	(       a  [        S5      eU(       a  XS	'   OU	(       a  XS
'   U(       a'  XS'   [        R
                  R                  SU  S35        XS.$ )ac  Generates and returns a user kubeconfig object.

Args:
  name: str, nickname for this user entry.
  auth_provider: str, authentication provider.
  auth_provider_cmd_path: str, authentication provider command path.
  auth_provider_cmd_args: str, authentication provider command args.
  auth_provider_expiry_key: str, authentication provider expiry key.
  auth_provider_token_key: str, authentication provider token key.
  cert_path: str, path to client certificate file.
  cert_data: str, base64 encoded client certificate data.
  key_path: str, path to client key file.
  key_data: str, base64 encoded client key data.
  impersonate_service_account: str, service account to impersonate.
  iam_token: str, IAM token to use for authentication.

Returns:
  dict, valid kubeconfig user entry.

Raises:
  Error: if no auth info is provided (auth_provider or cert AND key)
z3either auth_provider or cert & key must be provided)r$   cmd_pathcmd_args
expiry_key	token_keyzauth-providerexecz+cannot specify both cert_path and cert_datazclient-certificatezclient-certificate-dataz)cannot specify both key_path and key_dataz
client-keyzclient-key-datatokenz-Added IAM token to kubeconfig entry for user .)r$   r0   )r   _UseExecAuth_AuthProvider_ExecAuthPluginr   statusPrint)r$   auth_providerauth_provider_cmd_pathauth_provider_cmd_argsauth_provider_expiry_keyauth_provider_token_key	cert_path	cert_datakey_pathkey_dataimpersonate_service_account	iam_tokenr0   use_exec_auths                 r   Userr      s    L 	hI(
E
FF	$.- 	!#" ,))-+d? %%@Ad6l9
=
>>!*	&/	"#(
;
<<!&	MJJDTF!LM	%%r   c                      Sn [         R                  " [        R                  S5      nU(       a  UR	                  5       S:X  a  Sn U $ U(       a  UR	                  5       S:X  a  Sn U $ )zqReturns a bool noting if ExecAuth should be enabled.

Returns:
  bool, which notes if ExecAuth should be enabled
TUSE_GKE_GCLOUD_AUTH_PLUGINtruefalseF)r   r}   rM   r~   lower)r   use_gke_gcloud_auth_plugins     r   r   r   C  sh     -'77jj.  !
$
*
*
,
6M 
 !
$
*
*
,
7M	r   zPath to sdk installation not found. Please switch to application default
credentials using one of

$ gcloud config set container/use_application_default_credentials true
$ export CLOUDSDK_CONTAINER_USE_APPLICATION_DEFAULT_CREDENTIALS=truezInstall gke-gcloud-auth-plugin for use with kubectl by following https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl#install_pluginz{ACTION REQUIRED: gke-gcloud-auth-plugin, which is needed for continued use of kubectl, was not found or is not executable. c                    [         R                  R                  R                  R	                  5       n[        5       nUS[        SS.n/ nU(       a  UR                  S5        U (       a  UR                  SU -   5        U(       a  XCS'   U$ )a  Generate and return an exec auth plugin config.

Constructs an exec auth plugin config entry readable by kubectl.
This tells kubectl to call out to gke-gcloud-auth-plugin and
parse the output to retrieve access tokens to authenticate to
the kubernetes master.

Kubernetes GKE Auth Provider plugin is defined at
https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins

GKE GCloud Exec Auth Plugin code is at
https://github.com/kubernetes/cloud-provider-gcp/tree/master/cmd/gke-gcloud-auth-plugin

Args:
  impersonate_service_account: str, service account to impersonate.

Returns:
  dict, valid exec auth plugin config entry.
Raises:
  Error: Only one of --dns-endpoint or USE_APPLICATION_DEFAULT_CREDENTIALS
  should be set at a time.
z$client.authentication.k8s.io/v1beta1T)command
apiVersioninstallHintprovideClusterInfoz%--use_application_default_credentialsz--impersonate_service_account=args)r	   VALUES	containeruse_app_default_credentialsGetBool)_GetGkeGcloudPluginCommandAndPrintWarningGKE_GCLOUD_AUTH_INSTALL_HINTappend)r   #use_application_default_credentialsr   exec_cfgr   s        r   r   r   p  s    2 !!==EEG & 67' :1 	( 
$(KK78 KK03NNO	V	/r   c                 2   SU 0nU S:X  a  [         R                  R                  R                  R	                  5       (       d  Sn[
        R                  R                  5       (       a  SnUcu  [        R                  " 5       R                  nUc)  [        R                  " [        5        [        [        5      e[        R                   R#                  Xv5      n [%        5         UU(       a  UOSU(       a  UOSU(       a  UOSS.nXS	'   U$ ! [&         a     N4f = f)
a  Generates and returns an auth provider config.

Constructs an auth provider config entry readable by kubectl. This tells
kubectl to call out to a specific gcloud command and parse the output to
retrieve access tokens to authenticate to the kubernetes master.
Kubernetes gcp auth provider plugin at
https://github.com/kubernetes/kubernetes/tree/master/staging/src/k8s.io/client-go/plugin/pkg/client/auth/gcp

Args:
  name: auth provider name
  cmd_path: str, authentication provider command path.
  cmd_args: str, authentication provider command arguments.
  expiry_key: str, authentication provider expiry key.
  token_key: str, authentication provider token key.

Returns:
  dict, valid auth provider config entry.
Raises:
  Error: Path to sdk installation not found. Please switch to application
  default credentials using one of

  $ gcloud config set container/use_application_default_credentials true
  $ export CLOUDSDK_CONTAINER_USE_APPLICATION_DEFAULT_CREDENTIALS=true.
r$   gcpgcloudz
gcloud.cmdz"config config-helper --format=jsonz{.credential.access_token}z{.credential.token_expiry})zcmd-pathzcmd-argsz	token-keyz
expiry-keyr   )r	   r   r   r   r   r   r   r   r   Pathssdk_bin_pathr   r2   SDK_BIN_PATH_NOT_FOUNDr   rM   rN   rP   r   	Exception)	r$   r   r   r   r   providerbin_namer   cfgs	            r   r   r     s    6 d^(
em))EEMMOOH  **,,h\\^00l				()*++l5h13  !H&J #,Y1M %J*FC$ X	/1   	s   
D	 	
DDc            	      p   Sn [         R                  R                  5       (       a  Sn U n [        R                  " US/SS[        R
                  [        R
                  S9  U$ ! [         a     [        R                  " 5       R                  nUc  [        R                  " [        5        O[        R                  R                  X!5      n[        R                  " US/SS[        R
                  [        R
                  S9  Un U$ ! [         a    [        R                  " [        5          U$ f = f U$ f = f)zGet Gke Gcloud Plugin Command to be used.

Returns Gke Gcloud Plugin Command to be used. Also,
prints warning if plugin is not present or doesn't work correctly.

Returns:
  string, Gke Gcloud Plugin Command to be used.
zgke-gcloud-auth-pluginzgke-gcloud-auth-plugin.exez	--version   F)timeoutcheckstdoutstderr)r   r   r   
subprocessrunDEVNULLr   r   r   r   r   critical GKE_GCLOUD_AUTH_PLUGIN_NOT_FOUNDrM   rN   rP   )r   r   r   sdk_path_bin_names       r   r   r     s    &(((**+H'5NN	+!!!!< 
./ 
 55 \\^00l		56GGLL?,%%%%	
 $ 
.  5	ll34	.5 	7 
./5s<   6A# #
D5.<D*D5+AD$D.)D5-D..D54D5c                     U UUS.S.$ )z0Generate and return a context kubeconfig object.)r/   r0   )r$   r1   r   )r$   r/   r0   s      r   Contextr     s     
 r   c                      S/ / SS0 / S.$ )Nv1r@   Config)r   r&   r#   r7   kindpreferencesr%   r   r   r   r   rn   rn   %  s!    
 r   )NNF)NNNNNNNNNNNr=   )r   NNNN)#r   
__future__r   r   r   rM   r   googlecloudsdk.corer   r   core_exceptionsr   r	   r
   googlecloudsdk.core.utilr   r   rJ   r   r   r   rQ   objectr    r   r   r   r   r   r   r   r   r   r   rn   r   r   r   <module>r      s     4 &  ' 	  & = # * $ - 8 .9O!! 9M M *H &j jZ,$ !  $U&p8H  d $ #$#  -b JNEP/d	r   