-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
300 lines (242 loc) · 6.54 KB
/
main.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
package main
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"sort"
"strings"
"syscall"
"text/tabwriter"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
const (
karpenterNodeFmtStr string = "(Karpenter) %s"
customLabelEnvVar string = "KUBE_NODEPOOLS_LABEL"
)
var karpenterLabels = []string{"karpenter.sh/provisioner-name", "karpenter.sh/nodepool"}
var (
noHeaders bool
onlyName bool
output string
label string
)
func main() {
cmd := rootCmd()
cmd.AddCommand(listCmd())
cmd.AddCommand(nodesCmd())
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
err := cmd.ExecuteContext(ctx)
cancel()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
type ctxKey string
var kubeClientKey = ctxKey("klient")
func rootCmd() *cobra.Command {
kflags := genericclioptions.NewConfigFlags(true)
cmd := &cobra.Command{
Use: "nodepools",
Short: "Read-only interaction with nodepools",
Long: `Read-only interaction with nodepools.
List node pools/groups in the current cluster, alongside a count of
how many nodes there are in each pool/group and their type.
You can also list nodes for a given node pool/group by name.`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
cfg, err := kflags.ToRESTConfig()
if err != nil {
return err
}
klient, err := kubernetes.NewForConfig(cfg)
if err != nil {
return err
}
ctx = context.WithValue(ctx, kubeClientKey, klient)
cmd.SetContext(ctx)
if output != "" && output != "name" {
return fmt.Errorf("unrecognized --output type %s, only name is valid", output)
}
onlyName = output == "name"
return nil
},
SilenceErrors: true,
}
flags := cmd.PersistentFlags()
flags.BoolVar(&noHeaders, "no-headers", false, "Don't print headers (default print headers)")
flags.StringVarP(&output, "output", "o", "", "Output format. Only name.")
labelHelp := fmt.Sprintf("Label to group nodes into pools with; can be set via %s environment variable", customLabelEnvVar)
flags.StringVarP(&label, "label", "l", os.Getenv(customLabelEnvVar), labelHelp)
kflags.AddFlags(flags)
return cmd
}
var providerNodepoolLabels = map[string]string{
"AWS": "eks.amazonaws.com/nodegroup",
"GCP": "cloud.google.com/gke-nodepool",
"AKS": "kubernetes.azure.com/agentpool",
"DOKS": "doks.digitalocean.com/node-pool-id",
}
func findNodepool(node corev1.Node, label string) string {
// Check the custom label first
if np, ok := node.Labels[label]; ok {
return np
}
// check for karpenter nodes
for _, label := range karpenterLabels {
if np, ok := node.Labels[label]; ok {
return fmt.Sprintf(karpenterNodeFmtStr, np)
}
}
for _, lbl := range providerNodepoolLabels {
if np, ok := node.Labels[lbl]; ok {
return np
}
}
return "-"
}
func instanceType(node corev1.Node) string {
t, ok := node.Labels["node.kubernetes.io/instance-type"]
if ok {
return t
}
t, ok = node.Labels["beta.kubernetes.io/instance-type"]
if ok {
return t
}
return "-"
}
type nodepool struct {
Name string
Types map[string]int
Nodes uint
}
func listCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List node pools/groups in current cluster",
Long: `List node pools/groups in the current cluster, alongside a count of nodes and their type.`,
RunE: func(cmd *cobra.Command, args []string) error {
warnEnvLabelUsage(cmd)
ctx := cmd.Context()
klient := ctx.Value(kubeClientKey).(kubernetes.Interface)
res, err := klient.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
return err
}
nps := make(map[string]*nodepool)
names := make([]string, 0, len(nps))
for _, n := range res.Items {
npName := findNodepool(n, label)
np, ok := nps[npName]
if !ok {
names = append(names, npName)
np = &nodepool{
Name: npName,
Types: map[string]int{
instanceType(n): 1,
},
}
nps[npName] = np
} else {
np.Types[instanceType(n)]++
}
np.Nodes += 1
}
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
if !noHeaders {
if onlyName {
fmt.Fprintln(w, "NAME")
} else {
fmt.Fprintln(w, "NAME\tNODES\tTYPE")
}
}
sort.Strings(names)
for _, n := range names {
np := nps[n]
if onlyName {
fmt.Fprintln(w, np.Name)
} else {
typeList := make([]string, 0, len(np.Types))
for k, v := range np.Types {
typeWithCount := fmt.Sprintf("%s (%d)", k, v)
typeList = append(typeList, typeWithCount)
}
sort.Strings(typeList)
fmt.Fprintf(w, "%s\t%5d\t%s\n", np.Name, np.Nodes, strings.Join(typeList, ", "))
}
}
return w.Flush()
},
Aliases: []string{"ls"},
}
return cmd
}
func nodesCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "nodes <name>",
Short: "List nodes in node pool/group",
Long: `List nodes in the given node pool/group, alongside their status.`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("need to pass a single nodepool name")
}
warnEnvLabelUsage(cmd)
ctx := cmd.Context()
klient := ctx.Value(kubeClientKey).(kubernetes.Interface)
res, err := klient.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
return err
}
var ns []corev1.Node
for _, n := range res.Items {
if np := findNodepool(n, label); np == args[0] {
ns = append(ns, n)
}
}
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
if !noHeaders {
if onlyName {
fmt.Fprintln(w, "NODE")
} else {
fmt.Fprintln(w, "NODE\tSTATUS")
}
}
sort.Slice(ns, func(i, j int) bool { return ns[i].Name < ns[j].Name })
for _, n := range ns {
if onlyName {
fmt.Fprintln(w, n.Name)
} else {
fmt.Fprintf(w, "%s\t%v\n", n.Name, nodeCondition(n))
}
}
return w.Flush()
},
Aliases: []string{"ns"},
}
return cmd
}
func nodeCondition(n corev1.Node) string {
var s strings.Builder
for _, c := range n.Status.Conditions {
if c.Status == corev1.ConditionTrue {
if s.Len() > 0 {
s.WriteRune(',')
}
s.WriteString(string(c.Type))
}
}
return s.String()
}
func warnEnvLabelUsage(cmd *cobra.Command) {
if label != "" && !cmd.Parent().PersistentFlags().Changed("label") {
fmt.Fprintf(os.Stderr, "Using custom label %q set by environment variable %s\n", label, customLabelEnvVar)
}
}