-
Notifications
You must be signed in to change notification settings - Fork 2
/
kube.go
344 lines (312 loc) · 14 KB
/
kube.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright 2022 Tetrate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pkg
import (
"context"
"errors"
"fmt"
"istio.io/client-go/pkg/clientset/versioned"
v12 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
v13 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"strings"
)
var iopResource = schema.GroupVersionResource{Group: "install.istio.io", Version: "v1alpha1", Resource: "istiooperators"}
// KubeClient just wraps the kubernetes API.
// todo should we just do:
// ```
// type KubeClient kubernetes.ClientSet
// ```
// if we get no value from just wrapping?
type KubeClient struct {
clientSet *kubernetes.Clientset
dynamic dynamic.Interface
kubeconfig string
}
type Cloud string
const (
AWS Cloud = "AWS"
GCP Cloud = "GCP"
Unknown Cloud = "Unknown"
)
func (c Cloud) IsAWS() bool {
return c == AWS
}
func (c Cloud) IsGCP() bool {
return c == GCP
}
// NewAnalyzerKube creates a clientset using the kubeconfig found in the home directory.
// todo make kubeconfig a settable parameter in analyzer.go
func NewAnalyzerKube(kubeconfig string) *KubeClient {
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
dynamicClient := dynamic.NewForConfigOrDie(config)
return &KubeClient{
clientSet: clientset,
kubeconfig: kubeconfig,
dynamic: dynamicClient,
}
}
// CollapseLocalityCalls takes a raw list of type Call and collapses the data
// into a per-link basis (there might be multiple metrics for locality a->b)
// todo maybe do this directly in prom.go and make it O(n) instead of O(2n)
// sort of legacy?
func (k *KubeClient) CollapseLocalityCalls(rawCalls []*Call) ([]*Call, error) {
calls := make([]*Call, 0)
// serviceCallMap's keys are just workload/locality links, without any call size information,
// while the map value is the full, aggregated call value for that link. We do this because there may
// exist multiple pods that cause the same workload/locality link, and we don't want them to duplicate.
serviceCallMap := make(map[Call]*Call)
for i := 0; i < len(rawCalls); i++ {
serviceLocalityKey := Call{
FromWorkload: rawCalls[i].FromWorkload,
From: rawCalls[i].From,
ToWorkload: rawCalls[i].ToWorkload,
To: rawCalls[i].To,
}
// either create a new entry, or add to an existing one.
if _, ok := serviceCallMap[serviceLocalityKey]; !ok {
serviceCallMap[serviceLocalityKey] = &serviceLocalityKey
serviceLocalityKey.CallSize = rawCalls[i].CallSize
} else {
serviceCallMap[serviceLocalityKey].CallSize += rawCalls[i].CallSize
}
if i%10 == 0 {
for k, v := range serviceCallMap {
fmt.Printf("%v(%v) -> %v(%v): %v | link %v / %v\n", k.From, k.FromWorkload, k.To, k.ToWorkload, v.CallSize, i, len(rawCalls))
}
}
}
for _, v := range serviceCallMap {
calls = append(calls, v)
}
return calls, nil
}
// getPodNode gets the node associated with a given pod name in the default namespace.
// nolint
func (k *KubeClient) getPodNode(name, namespace string) (string, error) {
pod, err := k.clientSet.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
fmt.Printf("error in getting pod %v: %v\n", name, err)
return "", err
}
return pod.Spec.NodeName, nil
}
// getNodeLocality gets the locality given by topology.kubernetes.io.
// nolint
func (k *KubeClient) getNodeLocality(name, cloud string) (string, error) {
// if we are on AWS, we want to just get region, because availability zones
// are not supported yet.
if cloud == "aws" {
return k.getNodeLabel(name, "topology.kubernetes.io/region")
}
return k.getNodeLabel(name, "topology.kubernetes.io/zone")
}
// nolint
func (k *KubeClient) getNodeLabel(name, label string) (string, error) {
node, err := k.clientSet.CoreV1().Nodes().Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
fmt.Printf("error in getting node %v: %v\n", name, err)
return "", err
}
return node.Labels[label], nil
}
func (k *KubeClient) InferCloud() Cloud {
nodes, err := k.clientSet.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
fmt.Printf("error in getting nodes: %v\n", err)
return ""
}
if len(nodes.Items) == 0 {
return ""
}
node := nodes.Items[0]
if strings.Contains(node.Status.NodeInfo.KubeletVersion, "eks") {
return AWS
}
if strings.HasPrefix(node.Spec.ProviderID, "gce") && strings.Contains(node.Status.NodeInfo.KubeletVersion, "gke") {
return GCP
}
return Unknown
}
// CreateService creates a service in the given namespace. Returns the service, the error, and
// a boolean representing whether or not the service already exists.
func (k *KubeClient) CreateService(service *v1.Service, ns string) (*v1.Service, error, bool) {
svc, err := k.clientSet.CoreV1().Services(ns).Create(context.TODO(), service, metav1.CreateOptions{})
if err != nil && strings.Contains(err.Error(), "already exists") {
return service, nil, true
}
return svc, err, false
}
func (k *KubeClient) CreateDeployment(deployment *v12.Deployment, ns string) (*v12.Deployment, error, bool) {
dep, err := k.clientSet.AppsV1().Deployments(ns).Create(context.TODO(), deployment, metav1.CreateOptions{})
if err != nil && strings.Contains(err.Error(), "already exists") {
return deployment, nil, true
}
return dep, err, false
}
func (k *KubeClient) CreateServiceAccount(serviceAccount *v1.ServiceAccount, ns string) (*v1.ServiceAccount, error, bool) {
sa, err := k.clientSet.CoreV1().ServiceAccounts(ns).Create(context.TODO(), serviceAccount, metav1.CreateOptions{})
if err != nil && strings.Contains(err.Error(), "already exists") {
return serviceAccount, nil, true
}
return sa, err, false
}
func (k *KubeClient) CreateClusterRoleBinding(clusterRoleBinding *v13.ClusterRoleBinding) (*v13.ClusterRoleBinding, error, bool) {
crb, err := k.clientSet.RbacV1().ClusterRoleBindings().Create(context.TODO(), clusterRoleBinding, metav1.CreateOptions{})
if err != nil && strings.Contains(err.Error(), "already exists") {
return clusterRoleBinding, nil, true
}
return crb, err, false
}
func (k *KubeClient) CreateClusterRole(clusterRole *v13.ClusterRole) (*v13.ClusterRole, error, bool) {
cr, err := k.clientSet.RbacV1().ClusterRoles().Create(context.TODO(), clusterRole, metav1.CreateOptions{})
if err != nil && strings.Contains(err.Error(), "already exists") {
return clusterRole, nil, true
}
return cr, err, false
}
func (k *KubeClient) LabelNamespace(ns, key, value string) error {
_, err := k.clientSet.CoreV1().Namespaces().Patch(context.TODO(), ns, types.MergePatchType, []byte(fmt.Sprintf(`{"metadata":{"labels":{"%v":"%v"}}}`, key, value)), metav1.PatchOptions{})
return err
}
func (k *KubeClient) Client() kubernetes.Interface {
return k.clientSet
}
func (k *KubeClient) IstioClient() *versioned.Clientset {
config, err := clientcmd.BuildConfigFromFlags("", k.kubeconfig)
if err != nil {
panic(err.Error())
}
return versioned.NewForConfigOrDie(config)
}
func (k *KubeClient) GetDefaultOperator(ns string) (string, error) {
rl, err := k.dynamic.Resource(iopResource).Namespace(ns).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return "", err
}
for _, r := range rl.Items {
if _, ok := r.Object["status"]; ok {
if status, ok := r.Object["status"].(map[string]interface{})["status"]; ok && status != nil && status.(string) == "HEALTHY" {
return r.GetName(), nil
}
}
}
return "", errors.New("no default operator found, please specify a healthy istio operator")
}
func (k *KubeClient) EditIstioOperator(opName, opNamespace string) error {
res, err := k.dynamic.Resource(iopResource).Namespace(opNamespace).Get(context.TODO(), opName, metav1.GetOptions{})
res, neededUpdate := normalizeOperator(res)
if err != nil {
return err
}
if !neededUpdate {
return nil
}
_, err = k.dynamic.Resource(iopResource).Namespace(opNamespace).Update(context.TODO(), res, metav1.UpdateOptions{})
return err
}
func (k *KubeClient) DeleteOperatorConfig(opName, opNs string) error {
res, err := k.dynamic.Resource(iopResource).Namespace(opNs).Get(context.TODO(), opName, metav1.GetOptions{})
if err != nil {
return err
}
res = denormalizeOperator(res)
_, err = k.dynamic.Resource(iopResource).Namespace(opNs).Update(context.TODO(), res, metav1.UpdateOptions{})
return err
}
// literal trash but it works
func normalizeOperator(res *unstructured.Unstructured) (*unstructured.Unstructured, bool) {
// lord forgive me for I have sinned
// theres probably a better way to figure this out with JSONPatch but i'm lazy
if v := res.Object["spec"].(map[string]interface{})["values"]; v == nil {
res.Object["spec"].(map[string]interface{})["values"] = make(map[string]interface{})
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"]; v == nil {
res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"] = make(map[string]interface{})
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"]; v == nil {
res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"] = make(map[string]interface{})
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"]; v == nil {
res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"] = make(map[string]interface{})
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"].(map[string]interface{})["configOverride"]; v == nil {
res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"].(map[string]interface{})["configOverride"] = make(map[string]interface{})
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"].(map[string]interface{})["configOverride"].(map[string]interface{})["outboundSidecar"]; v == nil {
res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"].(map[string]interface{})["configOverride"].(map[string]interface{})["outboundSidecar"] = make(map[string]interface{})
}
outbound := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"].(map[string]interface{})["configOverride"].(map[string]interface{})["outboundSidecar"].(map[string]interface{})["metrics"]
if outbound == nil {
outbound = make([]interface{}, 0)
}
// check if we already wrote
for _, o := range outbound.([]interface{}) {
if o.(map[string]interface{})["dimensions"] != nil && o.(map[string]interface{})["dimensions"].(map[string]interface{})["destination_locality"] != nil {
return res, false
}
}
for i, out := range outbound.([]interface{}) {
if out.(map[string]interface{})["name"].(string) == "request_bytes" {
out.(map[string]interface{})["dimensions"].(map[string]interface{})["destination_locality"] = "upstream_peer.labels['locality'].value"
}
outbound.([]interface{})[i] = out
}
if len(outbound.([]interface{})) == 0 {
outbound = append(outbound.([]interface{}), map[string]interface{}{
"name": "request_bytes",
"dimensions": map[string]interface{}{
"destination_locality": "upstream_peer.labels['locality'].value",
},
})
}
res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"].(map[string]interface{})["configOverride"].(map[string]interface{})["outboundSidecar"].(map[string]interface{})["metrics"] = outbound
return res, true
}
// delete our config
func denormalizeOperator(res *unstructured.Unstructured) *unstructured.Unstructured {
if v := res.Object["spec"].(map[string]interface{})["values"]; v == nil {
return res
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"]; v == nil {
return res
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"]; v == nil {
return res
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"]; v == nil {
return res
}
if v := res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"].(map[string]interface{})["configOverride"]; v == nil {
return res
}
res.Object["spec"].(map[string]interface{})["values"].(map[string]interface{})["telemetry"].(map[string]interface{})["v2"].(map[string]interface{})["prometheus"].(map[string]interface{})["configOverride"] = make(map[string]interface{})
return res
}