/
kubeutil.go
460 lines (418 loc) · 13.2 KB
/
kubeutil.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//
// Copyright 2020 IBM Corporation
//
// 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 kubeutil
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
const InClusterObjectPrefix = "k8s://"
var cfg *rest.Config
type podGetterFunc func(obj *unstructured.Unstructured) ([]*corev1.Pod, error)
var podGetterMapper map[string]podGetterFunc = map[string]podGetterFunc{
"Deployment": getPodsFromDeployment,
// TODO: implement below
"ReplicaSet": getPodsNotImplemented,
"Pod": getPodsNotImplemented,
"DaemonSet": getPodsNotImplemented,
"StatefulSet": getPodsNotImplemented,
}
func GetInClusterConfig() (*rest.Config, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
return config, nil
}
func IsInCluster() bool {
_, err := rest.InClusterConfig()
if err == nil {
return true
} else {
return false
}
}
func GetOutOfClusterConfig() (*rest.Config, error) {
kubeconfigPath := os.Getenv("KUBECONFIG")
if kubeconfigPath == "" {
home := os.Getenv("HOME")
if home == "" {
home = os.Getenv("USERPROFILE")
}
kubeconfigPath = filepath.Join(home, ".kube", "config")
}
config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
if err != nil {
return nil, err
}
return config, nil
}
func GetKubeConfig() (*rest.Config, error) {
if cfg != nil {
return cfg, nil
}
config, err := GetInClusterConfig()
if err != nil || config == nil {
config, err = GetOutOfClusterConfig()
}
if err != nil || config == nil {
return nil, err
}
return config, nil
}
func SetKubeConfig(conf *rest.Config) {
if conf != nil {
cfg = conf
}
}
func MatchLabels(obj metav1.Object, labelSelector *metav1.LabelSelector) (bool, error) {
selector, err := metav1.LabelSelectorAsSelector(labelSelector)
if err != nil {
return false, err
}
labelsMap := obj.GetLabels()
labelsSet := labels.Set(labelsMap)
matched := selector.Matches(labelsSet)
return matched, nil
}
func GetAPIResources() ([]metav1.APIResource, error) {
config, err := GetKubeConfig()
if err != nil {
return nil, fmt.Errorf("Error in getting k8s config; %s", err.Error())
}
discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)
if err != nil {
return nil, fmt.Errorf("Error in creating discovery client; %s", err.Error())
}
apiResourceLists, err := discoveryClient.ServerPreferredResources()
if err != nil {
return nil, fmt.Errorf("Error in getting server preferred resources; %s", err.Error())
}
resources := []metav1.APIResource{}
for _, apiResourceList := range apiResourceLists {
if len(apiResourceList.APIResources) == 0 {
continue
}
gv, err := schema.ParseGroupVersion(apiResourceList.GroupVersion)
if err != nil {
continue
}
for _, resource := range apiResourceList.APIResources {
if len(resource.Verbs) == 0 {
continue
}
resource.Group = gv.Group
resource.Version = gv.Version
resources = append(resources, resource)
}
}
return resources, nil
}
func GetNamespaces() ([]*corev1.Namespace, error) {
config, err := GetKubeConfig()
if err != nil {
return nil, fmt.Errorf("error in getting k8s config; %s", err.Error())
}
client, err := corev1client.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("error in creating Core V1 Client; %s", err.Error())
}
nsList, err := client.Namespaces().List(context.Background(), metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("error in listing namespaces; %s", err.Error())
}
namespaces := []*corev1.Namespace{}
for i := range nsList.Items {
ns := nsList.Items[i]
namespaces = append(namespaces, &ns)
}
return namespaces, nil
}
func ParseObjectRefInCluster(objRef string) (string, string, error) {
parts := strings.Split(strings.TrimPrefix(objRef, InClusterObjectPrefix), "/")
if len(parts) != 1 && len(parts) != 2 {
return "", "", fmt.Errorf("object in cluster must be in format like %s[NAMESPACE]/[NAME] or %s[NAME]", InClusterObjectPrefix, InClusterObjectPrefix)
}
var ns, name string
if len(parts) == 1 {
name = parts[0]
} else if len(parts) == 2 {
ns = parts[0]
name = parts[1]
}
return ns, name, nil
}
func ParseObjectRefInClusterWithKind(objRef string) (string, string, string, error) {
parts := strings.Split(strings.TrimPrefix(objRef, InClusterObjectPrefix), "/")
if len(parts) != 2 && len(parts) != 3 {
return "", "", "", fmt.Errorf("kind and object in cluster must be in format like %s[KIND]/[NAMESPACE]/[NAME] or %s[KIND]/[NAME]", InClusterObjectPrefix, InClusterObjectPrefix)
}
var kind, ns, name string
if len(parts) == 2 {
kind = parts[0]
name = parts[1]
} else if len(parts) == 3 {
kind = parts[0]
ns = parts[1]
name = parts[2]
}
return kind, ns, name, nil
}
func GetSecret(namespace, name string) (*corev1.Secret, error) {
config, err := GetKubeConfig()
if err != nil {
return nil, fmt.Errorf("Error in getting k8s config; %s", err.Error())
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("failed to initialize kubernetes client; %s", err.Error())
}
obj, err := client.CoreV1().Secrets(namespace).Get(context.Background(), name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("failed to get secret `%s` in `%s` namespace; %s", name, namespace, err.Error())
}
return obj, nil
}
func GetResource(apiVersion, kind, namespace, name string) (*unstructured.Unstructured, error) {
var gv schema.GroupVersion
var err error
skipGV := false
if apiVersion == "" {
// if apiVersion is not specified, just use kind to identify resource kind
skipGV = true
} else {
gv, err = schema.ParseGroupVersion(apiVersion)
if err != nil {
return nil, fmt.Errorf("Error in parsing apiVersion; %s", err.Error())
}
}
apiResources, err := GetAPIResources()
if err != nil {
return nil, fmt.Errorf("Error in getting API Resources; %s", err.Error())
}
namespaced := true
gvr := schema.GroupVersionResource{}
for _, r := range apiResources {
gOk := (r.Group == gv.Group) || skipGV
vOk := (r.Version == gv.Version) || skipGV
kOk := (r.Kind == kind) || (r.Name == kind) || (r.SingularName == kind) || contains(r.ShortNames, kind)
if gOk && vOk && kOk {
gvr = schema.GroupVersionResource{
Group: r.Group,
Version: r.Version,
Resource: r.Name,
}
namespaced = r.Namespaced
}
}
if gvr.Resource == "" {
return nil, fmt.Errorf("Failed to find GroupVersionKind matches apiVerions: %s, kind: %s", apiVersion, kind)
}
config, err := GetKubeConfig()
if err != nil {
return nil, fmt.Errorf("Error in getting k8s config; %s", err.Error())
}
dyClient, err := dynamic.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("Error in creating DynamicClient; %s", err.Error())
}
var resource *unstructured.Unstructured
if namespaced {
resource, err = dyClient.Resource(gvr).Namespace(namespace).Get(context.Background(), name, metav1.GetOptions{})
} else {
resource, err = dyClient.Resource(gvr).Get(context.Background(), name, metav1.GetOptions{})
}
if err != nil {
return nil, fmt.Errorf("Error in getting resource; %s", err.Error())
}
return resource, nil
}
func ListResources(apiVersion, kind, namespace string) ([]*unstructured.Unstructured, error) {
var gv schema.GroupVersion
var err error
skipGV := false
if apiVersion == "" {
// if apiVersion is not specified, just use kind to identify resource kind
skipGV = true
} else {
gv, err = schema.ParseGroupVersion(apiVersion)
if err != nil {
return nil, fmt.Errorf("Error in parsing apiVersion; %s", err.Error())
}
}
gv, err = schema.ParseGroupVersion(apiVersion)
if err != nil {
return nil, fmt.Errorf("Error in parsing apiVersion; %s", err.Error())
}
apiResources, err := GetAPIResources()
if err != nil {
return nil, fmt.Errorf("Error in getting API Resources; %s", err.Error())
}
namespaced := true
gvr := schema.GroupVersionResource{}
for _, r := range apiResources {
gOk := (r.Group == gv.Group) || skipGV
vOk := (r.Version == gv.Version) || skipGV
kOk := (r.Kind == kind) || (r.Name == kind) || (r.SingularName == kind) || contains(r.ShortNames, kind)
if gOk && vOk && kOk {
gvr = schema.GroupVersionResource{
Group: r.Group,
Version: r.Version,
Resource: r.Name,
}
namespaced = r.Namespaced
}
}
if gvr.Resource == "" {
return nil, fmt.Errorf("Failed to find GroupVersionKind matches apiVerions: %s, kind: %s", apiVersion, kind)
}
config, err := GetKubeConfig()
if err != nil {
return nil, fmt.Errorf("Error in getting k8s config; %s", err.Error())
}
dyClient, err := dynamic.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("Error in creating DynamicClient; %s", err.Error())
}
var resourceList *unstructured.UnstructuredList
if namespaced {
resourceList, err = dyClient.Resource(gvr).Namespace(namespace).List(context.Background(), metav1.ListOptions{})
} else {
resourceList, err = dyClient.Resource(gvr).List(context.Background(), metav1.ListOptions{})
}
if err != nil {
return nil, fmt.Errorf("Error in getting resource; %s", err.Error())
}
resources := []*unstructured.Unstructured{}
for i := range resourceList.Items {
res := resourceList.Items[i]
resources = append(resources, &res)
}
return resources, nil
}
func contains(all []string, one string) bool {
for _, sub := range all {
if sub == one {
return true
}
}
return false
}
type ImageObject struct {
PodName string
ContainerName string
ImageID string
ResourceBundleRef string
Digest string
}
func GetAllImagesFromObject(obj *unstructured.Unstructured) ([]ImageObject, error) {
pods, err := GetAllPodsFromObject(obj)
if err != nil {
return nil, err
}
images := []ImageObject{}
for _, p := range pods {
podName := p.GetName()
for _, cstatus := range p.Status.InitContainerStatuses {
containerName := cstatus.Name
resBundleRef := cstatus.Image
imageID := cstatus.ImageID
if resBundleRef == "" || imageID == "" {
continue
}
parts := strings.Split(imageID, "@")
imageDigest := parts[len(parts)-1]
images = append(images, ImageObject{PodName: podName, ContainerName: containerName, ImageID: imageID, ResourceBundleRef: resBundleRef, Digest: imageDigest})
}
for _, cstatus := range p.Status.ContainerStatuses {
containerName := cstatus.Name
resBundleRef := cstatus.Image
imageID := cstatus.ImageID
if resBundleRef == "" || imageID == "" {
continue
}
parts := strings.Split(imageID, "@")
imageDigest := parts[len(parts)-1]
images = append(images, ImageObject{PodName: podName, ContainerName: containerName, ImageID: imageID, ResourceBundleRef: resBundleRef, Digest: imageDigest})
}
}
return images, nil
}
func GetAllPodsFromObject(obj *unstructured.Unstructured) ([]*corev1.Pod, error) {
kind := obj.GetKind()
name := obj.GetName()
podGetterFunc, ok := podGetterMapper[kind]
if !ok {
return nil, nil
}
pods, err := podGetterFunc(obj)
if err != nil {
return nil, errors.Wrapf(err, "failed to get pods for kind: %s, name: %s", kind, name)
}
return pods, nil
}
func getPodsNotImplemented(obj *unstructured.Unstructured) ([]*corev1.Pod, error) {
kind := obj.GetKind()
return nil, fmt.Errorf("pod getter is not implemented yet for kind: %s", kind)
}
func getPodsFromDeployment(obj *unstructured.Unstructured) ([]*corev1.Pod, error) {
var deploy appsv1.Deployment
objBytes, _ := json.Marshal(obj.Object)
err := json.Unmarshal(objBytes, &deploy)
if err != nil {
return nil, fmt.Errorf("error in converting object to Deployment; %s", err.Error())
}
namespace := deploy.GetNamespace()
selector, err := metav1.LabelSelectorAsSelector(deploy.Spec.Selector)
if err != nil {
return nil, fmt.Errorf("error in converting *metav1.LabelSelector to labels.Selector; %s", err.Error())
}
selectorStr := selector.String()
config, err := GetKubeConfig()
if err != nil {
return nil, fmt.Errorf("error in getting k8s config; %s", err.Error())
}
client, err := corev1client.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("error in creating Core V1 Client; %s", err.Error())
}
podList, err := client.Pods(namespace).List(context.Background(), metav1.ListOptions{LabelSelector: selectorStr})
if err != nil {
return nil, fmt.Errorf("error in listing pods; %s", err.Error())
}
pods := []*corev1.Pod{}
for i := range podList.Items {
p := podList.Items[i]
pods = append(pods, &p)
}
return pods, nil
}