From a8f1b6e02d5a3c3b77dcf941b5c2a5d7f6e836ce Mon Sep 17 00:00:00 2001 From: Rokibul Hasan Date: Thu, 19 Dec 2024 16:23:56 +0600 Subject: [PATCH] fix: avoid unnecessary proxy container creation for already connected vCluster (#2341) * fix: avoid unnecessary proxy container creation for already connected vCluster Signed-off-by: Rokibul Hasan * Log info instead of returning an error when already connected to vcluster Signed-off-by: Rokibul Hasan * Check if vCluster is ready Signed-off-by: Rokibul Hasan * Use timeout ctx to get the serviceaccount Signed-off-by: Rokibul Hasan --------- Signed-off-by: Rokibul Hasan --- pkg/cli/connect_helm.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/pkg/cli/connect_helm.go b/pkg/cli/connect_helm.go index fe128629e..873bb9ec7 100644 --- a/pkg/cli/connect_helm.go +++ b/pkg/cli/connect_helm.go @@ -88,6 +88,11 @@ func ConnectHelm(ctx context.Context, options *ConnectOptions, globalFlags *flag } func (cmd *connectHelm) connect(ctx context.Context, vCluster *find.VCluster, command []string) error { + if connected, _ := checkIfAlreadyConnected(ctx, vCluster); connected { + cmd.Log.Infof("already connected to vcluster %q", vCluster.Name) + return nil + } + // prepare clients and find vcluster err := cmd.prepare(ctx, vCluster) if err != nil { @@ -693,3 +698,32 @@ func (cmd *connectHelm) waitForVCluster(ctx context.Context, vKubeConfig clientc return nil } + +func checkIfAlreadyConnected(ctx context.Context, vCluster *find.VCluster) (bool, error) { + currentContext, _, err := find.CurrentContext() + if err != nil { + return false, err + } + if currentContext == find.VClusterContextName(vCluster.Name, vCluster.Namespace, vCluster.Context) { + kubeConfig, err := vCluster.ClientFactory.ClientConfig() + if err != nil { + return false, err + } + + vKubeClient, err := kubernetes.NewForConfig(kubeConfig) + if err != nil { + return false, err + } + + timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + // Use the timeout context in the Get call + _, err = vKubeClient.CoreV1().ServiceAccounts("default").Get(timeoutCtx, "default", metav1.GetOptions{}) + if err != nil { + return false, err + } + return true, nil + } + return false, nil +}