
    9                     .   d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlm	Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dZdZdZdZd Zd Zd Z	 d#dZd#dZ d Z!d Z"d Z#d Z$d Z%d Z&d$dZ'd  Z(d! Z)d" Z*y)%z,Utilities for generating kubeconfig entries.    )absolute_import)division)unicode_literalsN)
kubeconfig)util)gateway)gwkubeconfig_util)errors)config)log)
properties)	platforms)semvera  
Fetch credentials for a running {cluster_type}.

This command updates a kubeconfig file with appropriate credentials and
endpoint information to point kubectl at a specific {cluster_type}.

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.

By default, the command will configure kubectl to automatically refresh its
credentials using the same identity as the gcloud command-line tool.
If you are running kubectl as part of an application, it is recommended to use
[application default credentials](https://cloud.google.com/docs/authentication/production).
To configure a kubeconfig file to use application default credentials, set
the ``container/use_application_default_credentials''
[Google Cloud CLI property](https://cloud.google.com/sdk/docs/properties) to
``true'' before running the command.

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
zyCluster {} is not RUNNING. The Kubernetes API may or may not be available. Check the cluster status for more information.zIs it still PROVISIONING?c                 0    d}|j                  | |||      S )aO  Generates a kubeconfig context for an Anthos Multi-Cloud cluster.

  Args:
    kind: str, kind of the cluster e.g. aws, azure.
    project_id: str, project ID accociated with the cluster.
    location: str, Google location of the cluster.
    cluster_id: str, ID of the cluster.

  Returns:
    The context for the kubeconfig entry.
  z/gke_{kind}_{project_id}_{location}_{cluster_id})kind
project_idlocation
cluster_idformat)r   r   r   r   templates        Dlib/googlecloudsdk/command_lib/container/gkemulticloud/kubeconfig.pyGenerateContextr   M   s(     ?(	Jj 
 
     c                 0    d}|j                  | |||      S )ae  Generates command arguments for kubeconfig's authorization provider.

  Args:
    kind: str, kind of the cluster e.g. aws, azure.
    cluster_id: str, ID of the cluster.
    location: str, Google location of the cluster.
    project: str, Google Cloud project of the cluster.

  Returns:
    The command arguments for kubeconfig's authorization provider.
  zcontainer {kind} clusters print-access-token {cluster_id} --project={project} --location={location} --format=json --exec-credential)r   r   r   projectr   )r   r   r   r   r   s        r   GenerateAuthProviderCmdArgsr   _   s-    ( 
 
J7 
 
 r   c                 X   t         j                  j                         }t        j                  |||      |j                  |<   t                t        || |||       |j                  |       |j                          t        j                  j                  dj                  |             y)a  Generates a kubeconfig entry for an Anthos Multi-cloud attached cluster.

  Args:
    cluster: object, Anthos Multi-cloud cluster.
    cluster_id: str, the cluster ID.
    context: str, context for the kubeconfig entry.
    cmd_path: str, authentication provider command path.
  NA new kubeconfig entry "{}" has been generated and set as the current context.N)kubeconfig_util
KubeconfigDefaultContextcontexts_CheckPreqs_ConnectGatewayKubeconfigSetCurrentContext
SaveToFiler   statusPrintr   )clusterr   contextcmd_pathr   s        r   GenerateAttachedKubeConfigr.   u   s     ))113*!0!8!8w"*g -JWhOw'**r   c                    t         j                  j                         }t        j                  |||      |j                  |<   t        | |      }|s|t        j                  d      k  rt        d       t        || ||||       nt                t        || |||       |j                  |       |j                          t        j                  j                  dj!                  |             y)a  Generates a kubeconfig entry for an Anthos Multi-cloud cluster.

  Args:
    cluster: object, Anthos Multi-cloud cluster.
    cluster_id: str, the cluster ID.
    context: str, context for the kubeconfig entry.
    cmd_path: str, authentication provider command path.
    cmd_args: str, authentication provider command arguments.
    private_ep: bool, whether to use private VPC for authentication.

  Raises:
      Error: don't have the permission to open kubeconfig file.
  z1.21.0T)private_endpointr   N)r    r!   r"   r#   r$   
_GetSemverr   SemVerr%   _PrivateVPCKubeconfigr&   r'   r(   r   r)   r*   r   )r+   r   r,   r-   cmd_args
private_epr   versions           r   GenerateKubeconfigr7      s      ))113*!0!8!8w"*g
 w
+'7V]]844&GZ(H MGZ( w'**r   c                     t        j                          | sQt        j                  j                  j
                  j                         }t        j                  |t                      yy)z9Checks the prerequisites to run get-credentials commands.N)
r   CheckKubectlInstalledr   VALUEScorer   	GetOrFailr   CheckGatewayApiEnablement_GetConnectGatewayEndpoint)r0   r   s     r   r%   r%      sM    	""''//99;J%%.0 
r   c                 p   |j                   |j                   j                  t        j                  |dt              dj                  t               |j                   j                        }d|d}t        j                  |fi || j                  |<   t        j                  ||      | j                  |<   y)az  Generates the Connect Gateway kubeconfig entry.

  Args:
    kubeconfig: object, Kubeconfig object.
    cluster: object, Anthos Multi-cloud cluster.
    cluster_id: str, the cluster ID.
    context: str, context for the kubeconfig entry.
    cmd_path: str, authentication provider command path.

  Raises:
      errors.MissingClusterField: cluster is missing required fields.
  NzFleet membershipzhttps://{}/v1/{}gcp)auth_providerauth_provider_cmd_path)fleet
membershipr
   MissingClusterFieldSTILL_PROVISIONING_MSGr   r>   r    Userusersr	   Clusterclusters)r   r+   r   r,   r-   serveruser_kwargss          r   r&   r&      s     ]]gmm66>

$
$&(>  $$ "GMM$<$<& #(8L+-227JkJ*7!2!:!:7F!K*gr   c                    i }t        ||      |d<   ||d| j                  |<   i }|j                  t        j                  d       nt        |j                        |d<   |j                  t        j                  |dt              t        j                  |dj                  |j                        fi || j                  |<   y)at  Generates the kubeconfig entry to connect using private VPC.

  Args:
    kubeconfig: object, Kubeconfig object.
    cluster: object, Anthos Multi-cloud cluster.
    cluster_id: str, the cluster ID.
    context: str, context for the kubeconfig entry.
    cmd_path: str, authentication provider command path.
    cmd_args: str, authentication provider command arguments.
  exec)nameuserNz.Cluster is missing certificate authority data.ca_dataendpointz
https://{})_ExecAuthPluginrH   clusterCaCertificater   warning
_GetCaDatarR   r
   rE   rF   r    rI   r   rJ   )r   r+   r   r,   r-   r4   rP   cluster_kwargss           r   r3   r3      s     
$ 84$v,'.=*7.!!)KK@A *7+G+G HN9

$
$J 6  "1!8!8|""7#3#34"8F"*gr   c                 v    t        | |      }|t        j                  d      k  rt        j                  d      y)a  Validates the cluster version.

  Args:
    cluster: object, Anthos Multi-cloud cluster.
    cluster_id: str, the cluster ID.

  Raises:
      UnsupportedClusterVersion: cluster version is not supported.
      MissingClusterField: expected cluster field is missing.
  z1.20.0zsThe command get-credentials is supported in cluster version 1.20 and newer. For older versions, use get-kubeconfig.N)r1   r   r2   r
   UnsupportedClusterVersionr+   r   r6   s      r   ValidateClusterVersionr[      s>     w
+'v}}X&&

*
*	=  'r   c                 h    t        j                  | j                  d            j                  d      S )Nzutf-8)base64	b64encodeencodedecode)pems    r   rV   rV     s)     
		#**W-	.	5	5g	>>r   c                 :   | j                   | j                   j                  t        j                  |d      | j                   j                  }|j	                  d      r(|j                  ddd      }t        j                  |      S t        j                  |      S )Nr6   z-nextz.0   )controlPlaner6   r
   rE   endswithreplacer   r2   )r+   r   r6   vs       r   r1   r1     s    !W%9%9%A%A%I

$
$Z
;;  ((' gq)A==	w	r   c                  *   t         j                  j                  j                  j	                         } | "| j                  d      s| j                  d      ryd| v ry| j                  d      s| j                  d      ryt        j                  d	      )
zGets the corresponding Connect Gateway endpoint for Multicloud environment.

  http://g3doc/cloud/kubernetes/multicloud/g3doc/oneplatform/team/how-to/hub

  Returns:
    The Connect Gateway endpoint.

  Raises:
    Error: Unknown API override.
  zgkemulticloud.googleapis.com/z-preprod-gkemulticloud.sandbox.googleapis.com/zconnectgateway.googleapis.comzstaging-gkemulticloudz-staging-connectgateway.sandbox.googleapis.comzhttp://localhostz%gkemulticloud.sandbox.googleapis.com/z.autopush-connectgateway.sandbox.googleapis.comgkemulticloud)	r   r:   api_endpoint_overridesri   Getre   
startswithr
   UnknownApiEndpointOverrideError)rR   s    r   r>   r>   #  s     55CCGGI( 			:	;			J	K*(:+,0A0A-1 <..??r   c                     dd| |ddS )z-Generates a Kubernetes execCredential object.ExecCredentialclient.authentication.k8s.io/v1)expirationTimestamptoken)r   
apiVersionr)    )expiration_timestampaccess_tokens     r   ro   ro   B  s     5!5
 r   c                    | _d}t         j                  j                         rd}|}	 t        j                  |dgddt        j
                  t        j
                         |} | dd|j%                  d	      d
d}t&        j(                  j*                  j,                  j/                         }|r9t&        j(                  j*                  j,                  j1                         |dg|d<   |S # t        $ r 	 t        j                         j                  }|Ft        j                  t        j                         t        j                  t        j                        t        j                   j#                  ||      }t        j                  |dgddt        j
                  t        j
                         |} n2# t        $ r& t        j                  t        j                         Y nw xY wY w xY w)zGenerates and returns an exec auth plugin config.

  Args:
    cmd_path: str, exec command path.
    cmd_args: str, exec command arguments.

  Returns:
    dict, valid exec auth plugin config entry.
  gcloudz
gcloud.cmdz	--version   F)timeoutcheckstdoutstderrrp   T Never)commandrs   provideClusterInfoargsinteractiveMode)rO   valueenv)r   OperatingSystem	IsWindows
subprocessrunDEVNULL	Exceptionr   Pathssdk_bin_pathr   criticalr    SDK_BIN_PATH_NOT_FOUNDErrorospathjoinsplitr   r:   rj   ri   rk   EnvironmentName)r-   r4   bin_namer   r   sdk_path_bin_namecfgrR   s           r   rS   rS   N  s    H  **,hG =nnK
 #### h6 5 nnS! 	# 55CCGGI( 44BBRRT	 CJ 
*S  == ||~22
,,==
>%%o&L&LM
M ggll<A

.. +.'''' '( =_;;<=-=s6   :C( (	G)2C F32G)3,G"G)!G""G)(G)c                 b    	 | j                  |      st        j                  d       yy#  Y yxY w)zDChecks and gives a warning if the cluster does not have a node pool.zpCluster does not have a node pool. To use Connect Gateway, ensure you have at least one Linux node pool running.N)HasNodePoolsr   rU   )cluster_clientcluster_refs     r   CheckClusterHasNodePoolsr     s6    		&&{3	kkB 4	s   &* .c                 J    t        | |      }|t        j                  d      k  S )Nz1.25.0)r1   r   r2   rZ   s      r   ConnectGatewayInNodePoolsr     s"    w
+'	6==*	**r   )F)NN)+__doc__
__future__r   r   r   r]   r   r    googlecloudsdk.api_lib.containerr   r    r   *googlecloudsdk.command_lib.container.fleetr   r	   2googlecloudsdk.command_lib.container.gkemulticloudr
   googlecloudsdk.corer   r   r   googlecloudsdk.core.utilr   r   COMMAND_DESCRIPTIONCOMMAND_EXAMPLENOT_RUNNING_MSGrF   r   r   r.   r7   r%   r&   r3   r[   rV   r1   r>   ro   rS   r   r   rt   r   r   <module>r      s    3 &  '  	  J 1 > H E & # * . + 62 5 $,6 BG(VL6>&?	 @>	DN	+r   