-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathk8s.go
83 lines (69 loc) · 1.98 KB
/
k8s.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
package dkl
import (
"fmt"
"log"
"strings"
"time"
"github.com/manifoldco/promptui"
v1 "k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func getPods() (*v1.Pod, error) {
client, err := newClient()
if err != nil {
log.Fatal(err)
}
pods, err := client.CoreV1().Pods("").List(meta_v1.ListOptions{})
if err != nil {
log.Fatal(err)
}
templates := &promptui.SelectTemplates{
Label: "{{ . }}?",
Active: "\u2388 {{ .Name | cyan }} ({{ .Namespace | red }} {{ .Status.Phase }})",
Inactive: " {{ .Name | cyan }} ({{ .Namespace | red }} {{ .Status.Phase }})",
Selected: "\u2388 executed {{ .Name | red }}",
Details: `
--------- Pod ----------
{{ "Name:" | faint }} {{ printf "%q" .Name }}
{{ "Namespacege:" | faint }} {{ .Namespace }}
{{ "Status:" | faint }} {{ .Status.Phase }}
{{ "Age:" | faint }} {{ .CreationTimestamp.Time | since | print }}`,
FuncMap: promptui.FuncMap,
}
templates.FuncMap["since"] = time.Since
searcher := func(input string, index int) bool {
pod := pods.Items[index]
ns := pod.Name + pod.Namespace
lni := strings.ReplaceAll(strings.ToLower(ns), " ", "")
input = strings.ReplaceAll(strings.ToLower(input), " ", "")
return strings.Contains(lni, input)
}
prompt := promptui.Select{
Label: "Kubernetes pod running...",
Items: pods.Items,
Templates: templates,
Size: 10,
Searcher: searcher,
}
i, _, err := prompt.Run()
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return nil, err
}
return &pods.Items[i], nil
}
func newClient() (kubernetes.Interface, error) {
kubeConfig, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(kubeConfig)
}
func buildKubernetesCmd(pod *v1.Pod, cmd []string) []string {
res := []string{"kubectl", "exec", "-it", pod.Name}
res = append(res, cmd...)
res = append(res, "-n", pod.Namespace)
return res
}