move KubectlCmd out of utils into its own package

This commit is contained in:
MorrisLaw
2019-10-31 18:27:44 +00:00
parent de63e573ca
commit cd8da67b03
11 changed files with 80 additions and 40 deletions

View File

@@ -17,16 +17,74 @@ limitations under the License.
package kubectl
import (
"fmt"
"os/exec"
"path/filepath"
"strings"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/kubernetes/test/e2e/framework"
e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
testutils "k8s.io/kubernetes/test/utils"
)
// TestKubeconfig is a struct containing the minimum attributes needed to run KubectlCmd.
type TestKubeconfig struct {
CertDir string
Host string
KubeConfig string
KubeContext string
KubectlPath string
}
// NewTestKubeconfig returns a new Kubeconfig struct instance.
func NewTestKubeconfig(certdir string, host string, kubeconfig string, kubecontext string, kubectlpath string) *TestKubeconfig {
return &TestKubeconfig{
CertDir: certdir,
Host: host,
KubeConfig: kubeconfig,
KubeContext: kubecontext,
KubectlPath: kubectlpath,
}
}
// KubectlCmd runs the kubectl executable through the wrapper script.
func (tk *TestKubeconfig) KubectlCmd(args ...string) *exec.Cmd {
defaultArgs := []string{}
// Reference a --server option so tests can run anywhere.
if tk.Host != "" {
defaultArgs = append(defaultArgs, "--"+clientcmd.FlagAPIServer+"="+tk.Host)
}
if tk.KubeConfig != "" {
defaultArgs = append(defaultArgs, "--"+clientcmd.RecommendedConfigPathFlag+"="+tk.KubeConfig)
// Reference the KubeContext
if tk.KubeContext != "" {
defaultArgs = append(defaultArgs, "--"+clientcmd.FlagContext+"="+tk.KubeContext)
}
} else {
if tk.CertDir != "" {
defaultArgs = append(defaultArgs,
fmt.Sprintf("--certificate-authority=%s", filepath.Join(tk.CertDir, "ca.crt")),
fmt.Sprintf("--client-certificate=%s", filepath.Join(tk.CertDir, "kubecfg.crt")),
fmt.Sprintf("--client-key=%s", filepath.Join(tk.CertDir, "kubecfg.key")))
}
}
kubectlArgs := append(defaultArgs, args...)
//We allow users to specify path to kubectl, so you can test either "kubectl" or "cluster/kubectl.sh"
//and so on.
cmd := exec.Command(tk.KubectlPath, kubectlArgs...)
//caller will invoke this and wait on it.
return cmd
}
// LogFailedContainers runs `kubectl logs` on a failed containers.
func LogFailedContainers(c clientset.Interface, ns string, logFunc func(ftm string, args ...interface{})) {
podList, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{})