
    p[                        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rSr " S S\R,                  5      r " S S\5      rS rS rS rS rS 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" r'S# r(S$\#-   r)S% r*S& r+S' r,g)+z,Utilities for generating kubeconfig entries.    )absolute_import)division)unicode_literalsN)config)
exceptions)log)yaml)encoding)files)	platformsa!  
Fetch credentials for a running {kind} cluster.
This command updates a kubeconfig file with appropriate credentials and
endpoint information to point kubectl at a specific {kind} cluster.
By default, credentials are written to ``HOME/.kube/config''.
You can provide an alternate path by setting the ``KUBECONFIG'' environment
variable. If ``KUBECONFIG'' contains multiple paths, the first one is used.
This command enables switching to a specific cluster, when working
with multiple clusters. It can also be used to access a previously created
cluster from a new workstation.
The command will configure kubectl to automatically refresh its
credentials using the same identity as the gcloud command-line tool.
See [](https://cloud.google.com/kubernetes-engine/docs/kubectl) for
kubectl documentation.
z
To get credentials of a cluster named ``my-cluster'' managed in location ``us-west1'',
run:
$ {command} my-cluster --location=us-west1
c                       \ rS rSrSrSrg)Error8   z>Class for errors raised by edgecontainer kubeconfig utilities. N__name__
__module____qualname____firstlineno____doc____static_attributes__r       Alib/googlecloudsdk/command_lib/edge_cloud/container/kubeconfig.pyr   r   8   s    Fr   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   c                 &    SnUR                  XUS9$ )a  Generates a kubeconfig context for a Edge Container cluster.

Args:
  project_id: str, project ID associated with the cluster.
  location: str, Google location of the cluster.
  cluster_id: str, ID of the cluster.

Returns:
  The context for the kubeconfig entry.
z2edgecontainer_{project_id}_{location}_{cluster_id})
project_idlocation
cluster_id)format)r   r   r    templates       r   GenerateContextr#   @   s'     B(	: 
 
G Gr   c                 b    SnUR                  U R                  c  SOU R                  S-   UUUS9$ )aL  Generates command arguments for kubeconfig's authorization provider.

Args:
  track: ReleaseTrack of gcloud command.
  cluster_id: str, ID of the cluster.
  project_id: str, ID of the project of the cluster.
  location: str, Google location of the cluster.

Returns:
  The command arguments for kubeconfig's authorization provider.
zr{prefix}edge-cloud container clusters print-access-token {cluster_id} --project={project_id} --location={location}  )prefixr    r   r   )r!   r'   )trackr    r   r   r"   s        r   GenerateAuthProviderCmdArgsr)   P   sE    B  
<<'RU\\C-?	 
 
 r   c                     SSUSUSU /$ )z(Returns exec auth provider command args.z--use_edge_cloudz	--projectz
--locationz	--clusterr   )r    r   r   s      r   GenerateExecAuthCmdArgsr+   h   s#     
 r   c           	      t   [         R                  5       n[        5       n[        XU5      UR                  U'   US   R                  [        XU5      5        0 nUR                  c  [        R                  " S5        O[        UR                  5      US'   UR                  c  [        R                  " S5        O[        UR                  5      US'   [        U40 UD6nUS   S	 XcR                  U'   US	   R                  U5        [        U S
S5      nUc  Sn0 nU R                  c  [        R                  " S5        O[        U R                  5      US'   [!        USR#                  U R$                  U5      40 UD6UR&                  U'   US   R                  [!        USR#                  U R$                  U5      40 UD65        UR)                  U5        XS'   [*        R,                  " U[.        R0                  5        UR3                  5         [        R4                  R7                  SR#                  U5      5        g)a<  Generates a kubeconfig entry based on offline credential for a Edge Container cluster.

Args:
  cluster: object, Edge Container cluster.
  context: str, context for the kubeconfig entry.
  credential_resp: Response from GetOfflineCredential API.

Raises:
    Error: don't have the permission to open kubeconfig file
contextsNz)Offline credential is missing client key.key_dataz1Offline credential is missing client certificate.	cert_datauserexecusersporti  .Cluster is missing certificate authority data.ca_datahttps://{}:{}clusterscurrent-contextNA new kubeconfig entry "{}" has been generated and set as the current context.)
KubeconfigDefaultEmptyKubeconfigContextr-   append	clientKeyr   error_GetPemDataForKubeconfigclientCertificateUserr2   getattrclusterCaCertificatewarningClusterr!   endpointr7   SetCurrentContextr	   dumpsysstderr
SaveToFilestatusPrint)	clustercontextcredential_resp
kubeconfigkubeconfig_for_outputuser_kwargsr0   r3   cluster_kwargss	            r   &GenerateKubeconfigForOfflineCredentialrW   v   s    !!#*)+!(7!C*g
#**77W+MN+&II9:6!!K
 &&.IIAB7)) K 
g	%	%$
6l6"7 ''-	&#	&$	\D.!!)KK@A 8$$!N9 ")%%g&6&6="AO"*g 
#**


 
 !1!14
8  w'-4)*))!3::.**r   c                 J   [         R                  5       n[        XU5      UR                  U'   SUUSSUS.n[	        U40 UD6nXuR
                  U'   0 nU R                  c  [        R                  " S5        O[        U R                  5      US'   [        U SS	5      n	U	c  S	n	[        US
R                  U R                  U	5      40 UD6UR                  U'   UR                  U5        UR!                  5         [        R"                  R%                  SR                  U5      5        g)a  Generates a kubeconfig entry for a Edge Container cluster.

Args:
  cluster: object, Edge Container cluster.
  context: str, context for the kubeconfig entry.
  cmd_path: str, authentication provider command path.
  cmd_args: str, authentication provider command arguments.
  exec_args: str, exec auth command arguments.

Raises:
    Error: don't have the permission to open kubeconfig file
gcpz{.expireTime}z{.accessToken})auth_providerauth_provider_cmd_pathauth_provider_cmd_argsauth_provider_expiry_keyauth_provider_token_keyexec_auth_argsNr4   r5   r3   i+  r6   r9   )r:   r;   r=   r-   rC   r2   rE   r   rF   rA   rD   rG   r!   rH   r7   rI   rM   rN   rO   )
rP   rQ   cmd_pathcmd_args	exec_argsrS   rU   r0   rV   r3   s
             r   GenerateKubeconfigrc      s"    !!#*!(7!C*g ( ("1!1!+ 
g	%	%$"7.!!)KK@A 8$$!N9
 
&$	'$	\D!(%%g&6&6="QAO"Q*gw'***r   c                 j    [         R                  " U R                  S5      5      R                  S5      $ )Nzutf-8)base64	b64encodeencodedecode)pems    r   rA   rA      s)     
		#**W-	.	5	5g	>>r   c                       \ 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)r:      z1Interface for interacting with a kubeconfig file.c                 0   X l         Xl        0 U l        0 U l        0 U l        U R                  S    H  nX0R                  US   '   M     U R                  S    H  nX@R                  US   '   M     U R                  S    H  nXPR                  US   '   M     g )Nr7   namer2   r-   )	_filename_datar7   r2   r-   )selfraw_datafilenamerP   r0   rQ   s         r   __init__Kubeconfig.__init__   s    NJDMDJDM::j)'.mmGFO$ *

7#!%jjf $::j)'.mmGFO$ *r   c                      U R                   S   $ Nr8   ro   rp   s    r   current_contextKubeconfig.current_context   s    ::'((r   c                     U R                   $ N)rn   rx   s    r   rr   Kubeconfig.filename  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 )Nr8   r%   )r-   popr7   r2   ro   get)rp   keys     r   ClearKubeconfig.Clear  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        g! , (       d  f       g= f)z^Save kubeconfig to file.

Raises:
  Error: don't have the permission to open kubeconfig file.
r7   r2   r-   T)privateN)listr7   valuesro   r2   r-   
file_utils
FileWriterrn   r	   rJ   )rp   fps     r   rM   Kubeconfig.SaveToFile  s     "$--"6"6"89DJJztzz0023DJJw!$--"6"6"89DJJz			t~~t	<
ii

B 
=	<	<s   0"C
C)c                      XR                   S'   g rv   rw   )rp   rQ   s     r   rI   Kubeconfig.SetCurrentContext  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)r7   r2   r-   zinvalid type for {0}: {1}zexpected key {0} not foundN)r   
isinstancer   r!   typeKeyError)clsdatar   r@   s       r   	_ValidateKubeconfig._Validate  s     ,>2#$)T**188idi* + + 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   rr   r   r@   s       r   LoadFromFileKubeconfig.LoadFromFile(  sh    (^^H%d MM$t	 :: (:AA
%%' ( ((s   1 A.$A))A.c                 V    U R                  U5      $ ! [        [        4 a  n[        R                  " SR                  X!5      5        [        R                  " [        R                  R                  U5      5        U " [        5       U5      nUR                  5         Us SnA$ SnAff = f)zARead in the kubeconfig, and if it doesn't exist create one there.z6unable to load default kubeconfig: {0}; recreating {1}N)r   r   IOErrorr   debugr!   r   MakeDirospathdirnamer<   rM   )r   rr   r@   rS   s       r   LoadOrCreateKubeconfig.LoadOrCreate2  s    h''7 	iiHOO
 23((3js    B(A:B#B(#B(c                 H    U R                  [        R                  5       5      $ r|   )r   r:   DefaultPath)r   s    r   r;   Kubeconfig.Default?  s    J22455r   c                     [         R                  " [        R                  S5      n U (       aA  U R	                  [        R
                  5      S   n [        R                  R                  U 5      $ [         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                  X#5      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.
KUBECONFIGr   HOME	HOMEDRIVEHOMEPATHUSERPROFILEzVenvironment variable {vars} or KUBECONFIG must be set to store credentials for kubectlz&HOMEDRIVE/HOMEPATH, USERPROFILE, HOME,)varsz.kuber   )r
   GetEncodedValuer   environsplitpathsepr   abspathr   OperatingSystem	IsWindowsjoinr   r!   )rS   home_dir
home_drive	home_paths       r   r   Kubeconfig.DefaultPathC  sA    ))"**lCJ##BJJ/2jWW__Z(( ''

F;H	11;;==++BJJDj**2::zBi		77<<
6++BJJF$$*F?Hyy{@+; %+ %89 9 17 %+ %89 9
 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)rI   ry   dictr   r7   itemsr2   r-   )rp   rS   s     r   MergeKubeconfig.Merge^  s     	4//M:3M3MNZ  &&()D1D1D1F,GGIDMd:++1134tDJJ<L<L<N7OOPDJZ  &&()D1D1D1F,GGIDMr   )ro   rn   r7   r-   r2   N)r   r   r   r   r   rs   propertyry   rr   r   rM   rI   classmethodr   r   r   r;   staticmethodr   r   r   r   r   r   r:   r:      s    9/ ) )  )
 , 
> 
>   
 
 6 6 5 54Ir   r:   c                 ~    SU0nU(       a  U(       a  [        S5      eU(       a  X$S'   OU(       a  X4S'   O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)rm   rP   )r   )rm   r   ca_pathr5   rP   s        r   rG   rG   o  sO     ' 
9
::'.#$,3()*.G&'	++r   c                    U(       d'  U(       a  U(       d  U(       a  U	(       d  [        S5      e0 n[        5       (       a  [        U
5      US'   O3U(       a,  U(       d  U(       d  U(       d  U(       a  [        UUUUUS9US'   U(       a  U(       a  [        S5      eU(       a  XkS'   OU(       a  X{S'   U(       a  U	(       a  [        S5      eU(       a  XS	'   OU	(       a  XS
'   XS.$ )a&  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.
  exec_auth_args: list, exec auth provider command arguments.

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 providedr1   )rm   r`   ra   
expiry_key	token_keyzauth-providerz+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)rm   r0   )r   _UseExecAuth_ExecAuthPlugin_AuthProvider)rm   rZ   r[   r\   r]   r^   	cert_pathr/   key_pathr.   r_   r0   s               r   rC   rC     s    B I(
E
FF	$^^">2DL 	!#" ,))-+d? 9
=
>>!*	&/	"#(
;
<<!&		%%r   zPath to sdk installation not found. Please check your installation or use the `--auth-provider-cmd-path` flag to provide the path to gcloud manually.zInstall gke-gcloud-auth-plugin for use with kubectl by following https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke z{ACTION REQUIRED: gke-gcloud-auth-plugin, which is needed for continued use of kubectl, was not found or is not executable. c                 2    [        5       nUU S[        SS.nU$ )a  Generate and return an exec auth plugin config.

Args:
  exec_auth_args: list, exec auth provider command arguments.

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

Returns:
  dict, valid exec auth plugin config entry.
z$client.authentication.k8s.io/v1beta1T)commandargs
apiVersioninstallHintprovideClusterInfo))_GetGkeGcloudPluginCommandAndPrintWarningGKE_GCLOUD_AUTH_INSTALL_HINT)r_   r   exec_cfgs      r   r   r     s+    ( 67' :1 ( 
/r   c                 Z   SU 0nU S:X  a  Sn[         R                  R                  5       (       a  SnUcP  [        R                  " 5       R
                  nUc  [        [        5      e[        R                  R                  Xv5      nUU(       a  UOSU(       a  UOSU(       a  UOSS.nXS	'   U$ )
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.
rm   rY   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   Pathssdk_bin_pathr   SDK_BIN_PATH_NOT_FOUNDr   r   r   )	rm   r`   ra   r   r   providerbin_namer   cfgs	            r   r   r     s    : d^(	U]H  **,,h\\^00l		*++l5h
  !H&J #I(D %J*FC$ X	/r   c                     Sn [         R                  " [        R                  U 5      nUb\  UR	                  5       S:X  a  gUR	                  5       S:w  a3  [
        R                  " SR                  XR	                  5       5      5        g)z4Returns a bool noting if ExecAuth should be enabled.USE_GKE_GCLOUD_AUTH_PLUGINfalseFtruez.Ignoring unsupported env value found for {}={}T)r
   r   r   r   lowerr   rF   r!   )env_flaguse_gke_gcloud_auth_plugins     r   r   r   9  sv    )('77

HM  +!'')W4	#	)	)	+v	5	kk
:
A
A88: 
r   c            	         Sn [         R                  R                  5       (       a  Sn U n [        R                  " US/SS[        R
                  [        R
                  S9  [        U5        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)zGets 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stdoutrL   )r   r   r   
subprocessrunDEVNULL_ValidateGkeGcloudPluginVersion	Exceptionr   r   r   r   critical GKE_GCLOUD_AUTH_PLUGIN_NOT_FOUNDr   r   r   )r   r   r   sdk_path_bin_names       r   r   r   L  s!    &(((**+H'5NNG[)$,,$,,	.
 $G,, 
.+ 
 55 \\^00l		56GGLL?);7 "(00(00		2
 $ 
.  5	ll34	.5 	7 
.+5s=   AA. .
E 9<D5E 6AD$D94E 8D99E ?E zkACTION REQUIRED: gke-gcloud-auth-plugin, which is needed for continued use of kubectl needs to be updated. c                     [         R                  " U S/SSSSS9nSUR                  ;  a,  SUR                  ;  a  [        R
                  " [        5        ggg)zValidate Gke Gcloud Plugin Command to be used.

GDCE will depend on the newest available version, so warn customers if they
have an older version installed.

Args:
  command: Gke Gcloud Plugin Command to be used.
z--helpr   FT)r   r   capture_outputtextz--project stringN)r   r   rL   r   r   r   %GKE_GCLOUD_AUTH_PLUGIN_NOT_UP_TO_DATE)r   results     r   r   r     sW     >>& --LL67 . .r   c                     U UUS.S.$ )z0Generate and return a context kubeconfig object.)rP   r0   )rm   rQ   r   )rm   rP   r0   s      r   r=   r=     s     
 r   c                      S/ / SS0 / S.$ )Nv1r%   Config)r   r-   r7   r8   kindpreferencesr2   r   r   r   r   r<   r<     s!    
 r   )NN)
NNNNNNNNNN)rY   NNNN)-r   
__future__r   r   r   re   r   r   rK   googlecloudsdk.corer   r   core_exceptionsr   r	   googlecloudsdk.core.utilr
   r   r   r   COMMAND_DESCRIPTIONCOMMAND_EXAMPLEr   r   r#   r)   r+   rW   rc   rA   objectr:   rG   rC   r   r   r   r   r   r   r   r   r   r=   r<   r   r   r   <module>r     s3   3 &  '  	  
 & = # $ - 8 .  GO!! GM MG 0=@,*^?I ID,"  $ $"&!%G&V # ; ! !B ! 	<~&,^+-IJ &
80	r   