forked from kubernetes/kops
/
kubectl.go
114 lines (94 loc) · 2.62 KB
/
kubectl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package kutil
import (
"encoding/json"
"fmt"
"github.com/golang/glog"
"os"
"os/exec"
"strings"
)
type Kubectl struct {
KubectlPath string
}
func (k *Kubectl) GetCurrentContext() (string, error) {
s, err := k.execKubectl("config", "current-context")
if err != nil {
return "", err
}
s = strings.TrimSpace(s)
return s, nil
}
func (k *Kubectl) GetConfig(minify bool) (*KubectlConfig, error) {
output := "json"
// TODO: --context doesn't seem to work
args := []string{"config", "view"}
if minify {
args = append(args, "--minify")
}
if output != "" {
args = append(args, "--output", output)
}
configString, err := k.execKubectl(args...)
if err != nil {
return nil, err
}
configString = strings.TrimSpace(configString)
glog.V(8).Infof("config = %q", configString)
config := &KubectlConfig{}
err = json.Unmarshal([]byte(configString), config)
if err != nil {
return nil, fmt.Errorf("cannot parse current config from kubectl: %v", err)
}
return config, nil
}
func (k *Kubectl) execKubectl(args ...string) (string, error) {
kubectlPath := k.KubectlPath
if kubectlPath == "" {
kubectlPath = "kubectl" // Assume in PATH
}
cmd := exec.Command(kubectlPath, args...)
env := os.Environ()
cmd.Env = env
human := strings.Join(cmd.Args, " ")
glog.V(2).Infof("Running command: %s", human)
output, err := cmd.CombinedOutput()
if err != nil {
glog.Infof("error running %s:", human)
glog.Info(string(output))
return string(output), fmt.Errorf("error running kubectl")
}
return string(output), err
}
type KubectlConfig struct {
Kind string `json:"kind"`
ApiVersion string `json:"apiVersion"`
CurrentContext string `json:"current-context"`
Clusters []*KubectlClusterWithName `json:"clusters"`
Contexts []*KubectlContextWithName `json:"contexts"`
Users []*KubectlUserWithName `json:"users"`
}
type KubectlClusterWithName struct {
Name string `json:"name"`
Cluster KubectlCluster `json:"cluster"`
}
type KubectlCluster struct {
Server string `json:"server"`
}
type KubectlContextWithName struct {
Name string `json:"name"`
Context KubectlContext `json:"context"`
}
type KubectlContext struct {
Cluster string `json:"cluster"`
User string `json:"user"`
}
type KubectlUserWithName struct {
Name string `json:"name"`
User KubectlUser `json:"user"`
}
type KubectlUser struct {
ClientCertificateData string `json:"client-certificate-data"`
ClientKeyData string `json:"client-key-data"`
Password string `json:"password"`
Username string `json:"username"`
}