Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[YUNIKORN-1977] E2E test for verifying user info with non kube-admin user #915

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 81 additions & 25 deletions test/e2e/framework/helpers/k8s/k8s_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,19 @@
package k8s

import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"

"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"

"go.uber.org/zap"
appsv1 "k8s.io/api/apps/v1"
Expand Down Expand Up @@ -1091,14 +1090,6 @@ func (k *KubeCtl) CreateSecret(secret *v1.Secret, namespace string) (*v1.Secret,
return k.clientSet.CoreV1().Secrets(namespace).Create(context.TODO(), secret, metav1.CreateOptions{})
}

func GetSecretObj(yamlPath string) (*v1.Secret, error) {
o, err := common.Yaml2Obj(yamlPath)
if err != nil {
return nil, err
}
return o.(*v1.Secret), err
}

func (k *KubeCtl) CreateServiceAccount(accountName string, namespace string) (*v1.ServiceAccount, error) {
return k.clientSet.CoreV1().ServiceAccounts(namespace).Create(context.TODO(), &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{Name: accountName},
Expand Down Expand Up @@ -1383,21 +1374,6 @@ func (k *KubeCtl) isNumJobPodsInDesiredState(jobName string, namespace string, n
}
}

func ApplyYamlWithKubectl(path, namespace string) error {
cmd := exec.Command("kubectl", "apply", "-f", path, "-n", namespace)
var stderr bytes.Buffer
cmd.Stderr = &stderr
// if err != nil, isn't represent yaml format error.
// it only represent the cmd.Run() fail.
err := cmd.Run()
// if yaml format error, errStr will show the detail
errStr := stderr.String()
if err != nil && errStr != "" {
return fmt.Errorf("apply fail with %s", errStr)
}
return nil
}

func (k *KubeCtl) GetNodes() (*v1.NodeList, error) {
return k.clientSet.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
}
Expand Down Expand Up @@ -1779,3 +1755,83 @@ func (k *KubeCtl) DeleteStorageClass(scName string) error {
}
return nil
}

func (k *KubeCtl) GetSecrets(namespace string) (*v1.SecretList, error) {
return k.clientSet.CoreV1().Secrets(namespace).List(context.TODO(), metav1.ListOptions{})
}

// GetSecretValue retrieves the value for a specific key from a Kubernetes secret.
func (k *KubeCtl) GetSecretValue(namespace, secretName, key string) (string, error) {
secret, err := k.getSecretWithRetry(namespace, secretName)
if err != nil {
return "", err
}
// Check if the key exists in the secret
value, ok := secret.Data[key]
if !ok {
return "", fmt.Errorf("key %s not found in secret %s", key, secretName)
}
return string(value), nil
}

// getSecretWithRetry retries getting the secret until it's populated with data, up to a limit.
func (k *KubeCtl) getSecretWithRetry(namespace, secretName string) (*v1.Secret, error) {
var secret *v1.Secret
var err error

for i := 0; i < 5; i++ {
secret, err = k.clientSet.CoreV1().Secrets(namespace).Get(context.TODO(), secretName, metav1.GetOptions{})
if err != nil {
return nil, err
}

// If secret contains data, return it
if len(secret.Data) > 0 {
return secret, nil
}

// Wait before retrying
time.Sleep(2 * time.Second)
Copy link
Contributor

@pbacsko pbacsko Oct 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This retry loop & sleep should definitely not be here. Normally, a getter function is only about retrieving something, whenever possible. If we have to wait for a value to show up, let's create a separate helper method for it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the code with requested changes.

Copy link
Contributor

@pbacsko pbacsko Oct 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to code the retry. We can take advantage of existing k8s functions.

To be consistent with existing code, let's use the following:

func (k *KubeCtl) GetSecretValue(namespace, secretName, key string) (string, error) {
	secret, err := k.GetSecret(namespace, secretName)
	if err != nil {
		return "", err
	}
	// Check if the key exists in the secret
	value, ok := secret.Data[key]
	if !ok {
		return "", fmt.Errorf("key %s not found in secret %s", key, secretName)
	}
	return string(value), nil
}

func (k *KubeCtl) GetSecret(namespace, secretName string) (*v1.Secret, error) {
	secret, err := k.clientSet.CoreV1().Secrets(namespace).Get(context.TODO(), secretName, metav1.GetOptions{})
	if err != nil {
		return nil, err
	}

	return secret, nil
}

func (k *KubeCtl) WaitForSecret(namespace, secretName string, timeout time.Duration) error {
	var cond wait.ConditionFunc
	cond = func() (done bool, err error) {
		secret, err := k.GetSecret(namespace, secretName)
		if err != nil {
			return false, err
		}
		if secret != nil {
			return false, nil
		}
		return true, nil
	}
	return wait.PollUntilContextTimeout(context.TODO(), time.Second, timeout, false, cond.WithContext())
}

First, you call kClient.WaitForSecret() to indicate that you're waiting for a secret to appear over the API. Then call kClient.GetSecretValue(). By having these 3 methods, all of them are usable indepdently of one another.

}

return nil, fmt.Errorf("secret %s has no data after retries", secretName)
}

func WriteConfigToFile(config *rest.Config, kubeconfigPath string) error {
rrajesh-cloudera marked this conversation as resolved.
Show resolved Hide resolved
// Build the kubeconfig API object from the rest.Config
kubeConfig := &clientcmdapi.Config{
Clusters: map[string]*clientcmdapi.Cluster{
"default-cluster": {
Server: config.Host,
CertificateAuthorityData: config.CAData,
InsecureSkipTLSVerify: config.Insecure,
},
},
AuthInfos: map[string]*clientcmdapi.AuthInfo{
"default-auth": {
Token: config.BearerToken,
},
},
Contexts: map[string]*clientcmdapi.Context{
"default-context": {
Cluster: "default-cluster",
AuthInfo: "default-auth",
},
},
CurrentContext: "default-context",
}

// Ensure the directory where the file is being written exists
err := os.MkdirAll(filepath.Dir(kubeconfigPath), os.ModePerm)
if err != nil {
return fmt.Errorf("failed to create directory for kubeconfig file: %v", err)
}

// Write the kubeconfig to the specified file
err = clientcmd.WriteToFile(*kubeConfig, kubeconfigPath)
if err != nil {
return fmt.Errorf("failed to write kubeconfig to file: %v", err)
}

return nil
}
Loading