...
1
16
17 package controlplane
18
19 import (
20 "bytes"
21 "fmt"
22 "io"
23 "net/url"
24 "os/exec"
25
26 "k8s.io/client-go/rest"
27 "k8s.io/client-go/tools/clientcmd"
28 kcapi "k8s.io/client-go/tools/clientcmd/api"
29
30 "sigs.k8s.io/controller-runtime/pkg/internal/testing/process"
31 )
32
33 const (
34 envtestName = "envtest"
35 )
36
37
38
39
40
41
42 func KubeConfigFromREST(cfg *rest.Config) ([]byte, error) {
43 kubeConfig := kcapi.NewConfig()
44 protocol := "https"
45 if !rest.IsConfigTransportTLS(*cfg) {
46 protocol = "http"
47 }
48
49
50 baseURL, err := url.Parse(cfg.Host)
51 if err != nil {
52 return nil, fmt.Errorf("unable to interpret config's host value as a URL: %w", err)
53 }
54
55 kubeConfig.Clusters[envtestName] = &kcapi.Cluster{
56
57
58
59 Server: (&url.URL{Scheme: protocol, Host: baseURL.Host, Path: cfg.APIPath}).String(),
60 CertificateAuthorityData: cfg.CAData,
61 }
62 kubeConfig.AuthInfos[envtestName] = &kcapi.AuthInfo{
63
64 ClientCertificateData: cfg.CertData,
65 ClientKeyData: cfg.KeyData,
66 Token: cfg.BearerToken,
67 Username: cfg.Username,
68 Password: cfg.Password,
69 }
70 kcCtx := kcapi.NewContext()
71 kcCtx.Cluster = envtestName
72 kcCtx.AuthInfo = envtestName
73 kubeConfig.Contexts[envtestName] = kcCtx
74 kubeConfig.CurrentContext = envtestName
75
76 contents, err := clientcmd.Write(*kubeConfig)
77 if err != nil {
78 return nil, fmt.Errorf("unable to serialize kubeconfig file: %w", err)
79 }
80 return contents, nil
81 }
82
83
84 type KubeCtl struct {
85
86
87
88
89
90 Path string
91
92
93
94
95
96
97 Opts []string
98 }
99
100
101
102
103 func (k *KubeCtl) Run(args ...string) (stdout, stderr io.Reader, err error) {
104 if k.Path == "" {
105 k.Path = process.BinPathFinder("kubectl", "")
106 }
107
108 stdoutBuffer := &bytes.Buffer{}
109 stderrBuffer := &bytes.Buffer{}
110 allArgs := append(k.Opts, args...)
111
112 cmd := exec.Command(k.Path, allArgs...)
113 cmd.Stdout = stdoutBuffer
114 cmd.Stderr = stderrBuffer
115 cmd.SysProcAttr = process.GetSysProcAttr()
116
117 err = cmd.Run()
118
119 return stdoutBuffer, stderrBuffer, err
120 }
121
View as plain text