github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/dataprotection/utils/envvar.go (about)

     1  /*
     2  Copyright (C) 2022-2023 ApeCloud Co., Ltd
     3  
     4  This file is part of KubeBlocks project
     5  
     6  This program is free software: you can redistribute it and/or modify
     7  it under the terms of the GNU Affero General Public License as published by
     8  the Free Software Foundation, either version 3 of the License, or
     9  (at your option) any later version.
    10  
    11  This program is distributed in the hope that it will be useful
    12  but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  GNU Affero General Public License for more details.
    15  
    16  You should have received a copy of the GNU Affero General Public License
    17  along with this program.  If not, see <http://www.gnu.org/licenses/>.
    18  */
    19  
    20  package utils
    21  
    22  import (
    23  	corev1 "k8s.io/api/core/v1"
    24  
    25  	dpv1alpha1 "github.com/1aal/kubeblocks/apis/dataprotection/v1alpha1"
    26  	intctrlutil "github.com/1aal/kubeblocks/pkg/controllerutil"
    27  	dptypes "github.com/1aal/kubeblocks/pkg/dataprotection/types"
    28  )
    29  
    30  func BuildEnvByCredential(pod *corev1.Pod, credential *dpv1alpha1.ConnectionCredential) []corev1.EnvVar {
    31  	var envVars []corev1.EnvVar
    32  	if credential == nil {
    33  		return nil
    34  	}
    35  	var hostEnv corev1.EnvVar
    36  	if credential.HostKey == "" {
    37  		hostEnv = corev1.EnvVar{Name: dptypes.DPDBHost, Value: intctrlutil.BuildPodHostDNS(pod)}
    38  	} else {
    39  		hostEnv = buildEnvBySecretKey(dptypes.DPDBHost, credential.SecretName, credential.HostKey)
    40  	}
    41  	envVars = append(envVars, hostEnv)
    42  	if credential.PasswordKey != "" {
    43  		envVars = append(envVars, buildEnvBySecretKey(dptypes.DPDBPassword, credential.SecretName, credential.PasswordKey))
    44  	}
    45  	if credential.UsernameKey != "" {
    46  		envVars = append(envVars, buildEnvBySecretKey(dptypes.DPDBUser, credential.SecretName, credential.UsernameKey))
    47  	}
    48  	if credential.PortKey != "" {
    49  		envVars = append(envVars, buildEnvBySecretKey(dptypes.DPDBPort, credential.SecretName, credential.PortKey))
    50  	}
    51  	return envVars
    52  }
    53  
    54  func buildEnvBySecretKey(name, secretName, key string) corev1.EnvVar {
    55  	return corev1.EnvVar{
    56  		Name: name,
    57  		ValueFrom: &corev1.EnvVarSource{
    58  			SecretKeyRef: &corev1.SecretKeySelector{
    59  				LocalObjectReference: corev1.LocalObjectReference{
    60  					Name: secretName,
    61  				},
    62  				Key: key,
    63  			},
    64  		},
    65  	}
    66  }