-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
287 lines (255 loc) · 8.21 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
package main
import (
"context"
"fmt"
"github.com/dustin/go-humanize"
"github.com/olekukonko/tablewriter"
"os"
"sync"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/fields"
flag "github.com/spf13/pflag"
log "github.com/sirupsen/logrus"
"github.com/vbauerster/mpb/v7"
"github.com/vbauerster/mpb/v7/decor"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
var logger = log.New()
var summaryOnly, includePods bool
var kubeconfig, kubecontext, nodeLabelSelector, podLabelSelector, nodeFieldSelector, podFieldSelector *string
var clusterStats = clusterResourceUsage{}
func init() {
// handle flags
debug := flag.BoolP("debug", "d", false, "Enable debug logging")
//colorAlways := flag.BoolP("color-always", "C", false, "Force color output in all cases")
//colorNever := flag.Bool("color-never", false, "Disable color completely")
kubeconfig = flag.String("kubeconfig", "", "Absolute path to a kubeconfig file. Uses ~/.kube/config by default.")
kubecontext = flag.String("context", "", "The name of the kubeconfig context to use")
nodeLabelSelector = flag.StringP("node-selector", "N", "", "Label selector for nodes to include")
nodeFieldSelector = flag.StringP("node-field-selector", "", "", "Node FieldSelector - only supports 'spec.unschedulable'. See: https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/")
podLabelSelector = flag.StringP("pod-selector", "P", "", "Label selector for pods to include")
podFieldSelector = flag.StringP("pod-field-selector", "", "", "Pod FieldSelector - useful for Namespace selection. See: https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/")
flag.BoolVarP(&includePods, "include-pods", "p", false, "Include Pod resource data in output")
flag.BoolVarP(&summaryOnly, "summary", "s", false, "Show only the cumulative cluster summary")
help := flag.BoolP("help", "h", false, "Show help")
flag.Parse()
if *help {
println("Usage: tonnage [options]")
flag.PrintDefaults()
os.Exit(0)
}
if summaryOnly && includePods {
flag.PrintDefaults()
log.Fatal("Invalid flags: --summary (-s) and --include-pods (-p) are mutually exclusive. Choose only one.")
}
if *debug {
logger.SetLevel(log.DebugLevel)
}
}
func main() {
client, err := getClient()
if err != nil {
logger.WithFields(log.Fields{
"error": err.Error(),
}).Fatal("Error creating kube client.")
}
ctx := context.Background()
nodeList, err := client.CoreV1().Nodes().List(ctx, metav1.ListOptions{
LabelSelector: *nodeLabelSelector,
FieldSelector: *nodeFieldSelector,
})
if err != nil {
logger.WithFields(log.Fields{
"error": err.Error(),
}).Fatal("Error listing nodes.")
}
logger.WithFields(log.Fields{
"numNodes": len(nodeList.Items),
"nodeLabelSelector": *nodeLabelSelector,
"podLabelSelector": *podLabelSelector,
"nodeFieldSelector": *nodeFieldSelector,
"podFieldSelector": *podFieldSelector,
}).Info("Found nodes")
wg := sync.WaitGroup{}
wg.Add(len(nodeList.Items))
progress := mpb.New(mpb.WithWaitGroup(&wg), mpb.WithWidth(64))
barName := "Nodes: "
bar := progress.AddBar(
int64(len(nodeList.Items)),
mpb.PrependDecorators(decor.Name(barName), decor.CountersNoUnit("%d / %d", decor.WCSyncWidth)),
mpb.AppendDecorators(decor.Percentage()),
)
for _, n := range nodeList.Items {
go func(node v1.Node) {
defer wg.Done()
processNode(client, node, progress)
bar.Increment()
}(n)
}
if len(nodeList.Items) == 0 {
// must proceed the progress bar to 100%
bar.SetTotal(0, true)
}
progress.Wait()
printTable(clusterStats)
}
func printTable(clusterStats clusterResourceUsage) {
table := tablewriter.NewWriter(os.Stdout)
var header []string
if includePods {
header = []string{
"Node Name",
"Pod Name",
"Allocatable CPU (milli)",
"Allocatable Memory (Mi)",
"Requested CPU (milli)",
"Requested Memory (Mi)",
"Limits CPU (milli)",
"Limits Memory (Mi)",
"# Pods",
"# Containers",
}
} else {
header = []string{
"Node Name",
"Allocatable CPU (milli)",
"Allocatable Memory (Mi)",
"Requested CPU (milli)",
"Requested Memory (Mi)",
"Limits CPU (milli)",
"Limits Memory (Mi)",
"# Pods",
"# Containers",
}
}
table.SetHeader(header)
table.SetAutoFormatHeaders(false)
var data [][]string
if !summaryOnly {
for _, n := range clusterStats.Nodes {
data = append(data, n.asTableRow(includePods))
if includePods {
table.SetRowLine(true)
table.SetAutoMergeCellsByColumnIndex([]int{0, 1})
for _, p := range n.Pods {
var pData []string
pData = append(pData, n.NodeName)
pData = append(pData, p.asTableRow()...)
data = append(data, pData)
}
}
}
table.AppendBulk(data)
}
footer := []string{"Cluster Total"}
if includePods {
footer = append(footer, "") // empty Pod Name for table formatting
}
footer = append(footer, []string{
humanize.Comma(clusterStats.Allocatable.CPU.MilliValue()),
humanize.Comma(clusterStats.Allocatable.Memory.ScaledValue(resource.Mega)),
humanize.Comma(clusterStats.Requests.CPU.MilliValue()),
humanize.Comma(clusterStats.Requests.Memory.ScaledValue(resource.Mega)),
humanize.Comma(clusterStats.Limits.CPU.MilliValue()),
humanize.Comma(clusterStats.Limits.Memory.ScaledValue(resource.Mega)),
humanize.Comma(clusterStats.NumPods),
humanize.Comma(clusterStats.NumContainers),
}...)
table.SetFooter(footer)
table.Render()
}
func processNode(client *kubernetes.Clientset, node v1.Node, progress *mpb.Progress) {
nodeStats := nodeResources{}
nodeStats.NodeName = node.Name
nodeStats.Allocatable.CPU = *node.Status.Allocatable.Cpu()
nodeStats.Allocatable.Memory = *node.Status.Allocatable.Memory()
fieldSelector := fmt.Sprintf("%s,%s", fields.OneTermEqualSelector("spec.nodeName", node.GetName()).String(), *podFieldSelector)
ctx := context.Background()
podsList, err := client.CoreV1().Pods("").List(ctx, metav1.ListOptions{
// Apply label selector from cli args
LabelSelector: *podLabelSelector,
// Limit to Pods on the current Node
FieldSelector: fieldSelector,
})
if err != nil {
logger.WithFields(log.Fields{
"node": node.Name,
"error": err.Error(),
}).Fatal("Error listing pods for Node.")
}
barName := fmt.Sprintf("Pods/Containers for %s: ", node.GetName())
bar := progress.AddBar(
int64(len(podsList.Items)),
mpb.BarRemoveOnComplete(),
mpb.PrependDecorators(decor.Name(barName), decor.CountersNoUnit("%d / %d", decor.WCSyncWidth)),
mpb.AppendDecorators(decor.Percentage()),
)
for _, p := range podsList.Items {
if p.Status.Phase != "Running" {
bar.Increment()
continue
}
pr := podResources{
PodName: p.Name,
Requests: resources{},
Limits: resources{},
Containers: nil,
}
for _, c := range p.Spec.Containers {
cr := containerResources{
Requests: resources{
CPU: c.Resources.Requests["cpu"],
Memory: c.Resources.Requests["memory"],
},
Limits: resources{
CPU: c.Resources.Limits["cpu"],
Memory: c.Resources.Limits["memory"],
},
}
pr.add(cr)
bar.Increment()
}
nodeStats.add(pr)
}
if len(podsList.Items) == 0 {
// must proceed the progress bar to 100%
bar.SetTotal(0, true)
}
clusterStats.add(nodeStats)
}
func getClient() (*kubernetes.Clientset, error) {
// create a client config with proper kubeconfig and context
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
configOverrides := &clientcmd.ConfigOverrides{}
if *kubeconfig != "" {
loadingRules.ExplicitPath = *kubeconfig
}
if *kubecontext != "" {
configOverrides.CurrentContext = *kubecontext
}
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
loadingRules, configOverrides).ClientConfig()
if err != nil {
return nil, err
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
serverInfo, err := clientset.Discovery().ServerVersion()
if err != nil {
logger.WithFields(log.Fields{
"server": "unknown",
"err": err.Error(),
}).Info("Connected to Kubernetes API - unable to determine version")
} else {
logger.WithFields(log.Fields{
"server": serverInfo.String(),
}).Info("Connected to Kubernetes API")
}
return clientset, nil
}