func()

in clusterloader2/pkg/prometheus/prometheus.go [391:467]


func (pc *Controller) createToken(k8sClient kubernetes.Interface, testClusterClientSet kubernetes.Interface) error {
	klog.V(2).Info("Creating ServiceAccount in testing cluster")

	saObj := &corev1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name: monitoringServiceAccount,
		},
	}

	token := func() (string, error) {
		expirationSeconds := int64(86400) // 24h
		tokenReq := &authenticationv1.TokenRequest{
			Spec: authenticationv1.TokenRequestSpec{
				ExpirationSeconds: &expirationSeconds,
			},
		}
		tokenResp, err := testClusterClientSet.CoreV1().ServiceAccounts(corev1.NamespaceDefault).CreateToken(context.TODO(), saObj.Name, tokenReq, metav1.CreateOptions{})
		if err != nil {
			return "", fmt.Errorf("failed to create token: %v", err)
		}
		if len(tokenResp.Status.Token) == 0 {
			return "", fmt.Errorf("failed to create token: no token in server response")
		}
		return tokenResp.Status.Token, nil
	}

	secret := func(token string) *corev1.Secret {
		return &corev1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Name:      secretName,
				Namespace: namespace,
			},
			Data: map[string][]byte{
				"token": []byte(token),
			},
			Type: corev1.SecretTypeOpaque,
		}
	}

	serviceAccount := func() error {
		_, err := testClusterClientSet.CoreV1().ServiceAccounts(corev1.NamespaceDefault).Create(context.TODO(), saObj, metav1.CreateOptions{})
		return err
	}

	// Check if the service account already exists
	_, err := testClusterClientSet.CoreV1().ServiceAccounts(corev1.NamespaceDefault).Get(context.TODO(), saObj.Name, metav1.GetOptions{})
	if err == nil {
		// Service account exists already. This mean the test is run again in cluster created previously
		// Secret should be created OR should be updated if exists
		tokenResponse, err := retryCreateFunctionWithResponse(token)
		if err != nil {
			return err
		}
		secret := secret(tokenResponse)
		err = createPrometheusSecretForExistingServiceAccount(k8sClient, secret)
		if err != nil {
			return err
		}
		return nil
	}
	// If ServiceAccount could not be retrieved but the error is not "not found", return it
	if !apierrs.IsNotFound(err) {
		return err
	}
	if err := retryCreateFunction(serviceAccount); err != nil {
		return err
	}
	tokenResponse, err := retryCreateFunctionWithResponse(token)
	if err != nil {
		return err
	}
	_, err = k8sClient.CoreV1().Secrets(namespace).Create(context.TODO(), secret(tokenResponse), metav1.CreateOptions{})
	if err != nil {
		return err
	}
	return nil
}