/
context.go
231 lines (196 loc) · 5.62 KB
/
context.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
"strings"
"github.com/stretchr/objx"
funk "github.com/thoas/go-funk"
)
// findContextFromEndpoint returns a valid context from $KUBECONFIG that uses the given
// apiServer endpoint.
func findContextFromEndpoint(endpoint string) (Config, error) {
cluster, context, err := ContextFromIP(endpoint)
if err != nil {
return Config{}, err
}
return Config{
Context: *context,
Cluster: *cluster,
}, nil
}
// findContextFromNames will try to match a context name from names
func findContextFromNames(names []string) (Config, error) {
for _, name := range names {
cluster, context, err := ContextFromName(name)
if _, ok := err.(ErrorNoContext); ok {
continue
} else if err != nil {
return Config{}, err
}
return Config{
Context: *context,
Cluster: *cluster,
}, nil
}
return Config{}, ErrorNoContext(fmt.Sprintf("%v", names))
}
func ContextFromName(contextName string) (*Cluster, *Context, error) {
cfg, err := Kubeconfig()
if err != nil {
return nil, nil, err
}
// find the context by name
var context Context
contexts, err := tryMSISlice(cfg.Get("contexts"), "contexts")
if err != nil {
return nil, nil, err
}
err = find(contexts, "name", contextName, &context)
if err == ErrorNoMatch {
return nil, nil, ErrorNoContext(contextName)
} else if err != nil {
return nil, nil, err
}
var cluster Cluster
clusters, err := tryMSISlice(cfg.Get("clusters"), "clusters")
if err != nil {
return nil, nil, err
}
err = find(clusters, "name", context.Context.Cluster, &cluster)
if err == ErrorNoMatch {
return nil, nil, ErrorNoCluster(contextName)
} else if err != nil {
return nil, nil, err
}
return &cluster, &context, nil
}
// Kubeconfig returns the merged $KUBECONFIG of the host
func Kubeconfig() (objx.Map, error) {
cmd := kubectlCmd("config", "view", "-o", "json")
cfgJSON := bytes.Buffer{}
cmd.Stdout = &cfgJSON
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, err
}
return objx.FromJSON(cfgJSON.String())
}
// Contexts returns a list of context names
func Contexts() ([]string, error) {
cmd := kubectlCmd("config", "get-contexts", "-o=name")
buf := bytes.Buffer{}
cmd.Stdout = &buf
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, err
}
return strings.Split(buf.String(), "\n"), nil
}
// ContextFromIP searches the $KUBECONFIG for a context using a cluster that matches the apiServer
func ContextFromIP(apiServer string) (*Cluster, *Context, error) {
cfg, err := Kubeconfig()
if err != nil {
return nil, nil, err
}
// find the correct cluster
var cluster Cluster
clusters, err := tryMSISlice(cfg.Get("clusters"), "clusters")
if err != nil {
return nil, nil, err
}
err = find(clusters, "cluster.server", apiServer, &cluster)
if err == ErrorNoMatch {
return nil, nil, ErrorNoCluster(apiServer)
} else if err != nil {
return nil, nil, err
}
// find a context that uses the cluster
var context Context
contexts, err := tryMSISlice(cfg.Get("contexts"), "contexts")
if err != nil {
return nil, nil, err
}
// find the context that uses the cluster, it should be an exact match
err = find(contexts, "context.cluster", fmt.Sprintf("^%s$", cluster.Name), &context)
if err == ErrorNoMatch {
return nil, nil, ErrorNoContext(cluster.Name)
} else if err != nil {
return nil, nil, err
}
return &cluster, &context, nil
}
// IPFromContext parses $KUBECONFIG, finds the cluster with the given name and
// returns the cluster's endpoint
func IPFromContext(name string) (ip string, err error) {
cfg, err := Kubeconfig()
if err != nil {
return "", err
}
// find a context with the given name
var context Context
contexts, err := tryMSISlice(cfg.Get("contexts"), "contexts")
if err != nil {
return "", err
}
err = find(contexts, "name", name, &context)
if err == ErrorNoMatch {
return "", ErrorNoContext(name)
} else if err != nil {
return "", err
}
// find the cluster of the context
var cluster Cluster
clusters, err := tryMSISlice(cfg.Get("clusters"), "clusters")
if err != nil {
return "", err
}
clusterName := context.Context.Cluster
err = find(clusters, "name", clusterName, &cluster)
if err == ErrorNoMatch {
return "", fmt.Errorf("no cluster named `%s` as required by context `%s` was found. Please check your $KUBECONFIG", clusterName, name)
} else if err != nil {
return "", err
}
return cluster.Cluster.Server, nil
}
func tryMSISlice(v *objx.Value, what string) ([]map[string]interface{}, error) {
if s := v.MSISlice(); s != nil {
return s, nil
}
data, ok := v.Data().([]map[string]interface{})
if !ok {
return nil, fmt.Errorf("expected %s to be of type `[]map[string]interface{}`, but got `%T` instead", what, v.Data())
}
return data, nil
}
// ErrorNoMatch occurs when no item matched had the expected value
var ErrorNoMatch = errors.New("no matches found")
// find attempts to find an object in list whose prop equals expected.
// If found, the value is unmarshalled to ptr, otherwise errNotFound is returned.
func find(list []map[string]interface{}, prop string, expected string, ptr interface{}) error {
var findErr error
i := funk.Find(list, func(x map[string]interface{}) bool {
if findErr != nil {
return false
}
got := objx.New(x).Get(prop).Data()
str, ok := got.(string)
if !ok {
findErr = fmt.Errorf("testing whether `%s` is `%s`: unable to parse `%v` as string", prop, expected, got)
return false
}
return regexp.MustCompile(expected).MatchString(str)
})
if findErr != nil {
return findErr
}
if i == nil {
return ErrorNoMatch
}
o := objx.New(i).MustJSON()
return json.Unmarshal([]byte(o), ptr)
}