-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathuimodel.go
More file actions
328 lines (288 loc) · 9.02 KB
/
uimodel.go
File metadata and controls
328 lines (288 loc) · 9.02 KB
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
/*
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 model
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
"time"
"github.com/charmbracelet/bubbles/paginator"
"github.com/charmbracelet/bubbles/progress"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/facette/natsort"
"golang.org/x/text/language"
"golang.org/x/text/message"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/duration"
"github.com/awslabs/eks-node-viewer/pkg/text"
)
var (
helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render
// white / black
activeDot = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "235", Dark: "252"}).Render("•")
// black / white
inactiveDot = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "250", Dark: "238"}).Render("•")
)
type UIModel struct {
progress progress.Model
cluster *Cluster
extraLabels []string
paginator paginator.Model
height int
nodeSorter func(lhs, rhs *Node) bool
style *Style
DisablePricing bool
}
func NewUIModel(extraLabels []string, nodeSort string, style *Style, context string) *UIModel {
pager := paginator.New()
pager.Type = paginator.Dots
pager.ActiveDot = activeDot
pager.InactiveDot = inactiveDot
return &UIModel{
// red to green
progress: progress.New(style.gradient),
cluster: NewCluster(context),
extraLabels: extraLabels,
paginator: pager,
nodeSorter: makeNodeSorter(nodeSort),
style: style,
}
}
func (u *UIModel) Cluster() *Cluster {
return u.cluster
}
func (u *UIModel) Init() tea.Cmd {
return nil
}
func (u *UIModel) View() string {
b := strings.Builder{}
stats := u.cluster.Stats()
sort.Slice(stats.Nodes, func(a, b int) bool {
return u.nodeSorter(stats.Nodes[a], stats.Nodes[b])
})
ctw := text.NewColorTabWriter(&b, 0, 8, 1)
fmt.Fprintln(&b, "Viewing cluster: ", u.cluster.name)
fmt.Fprintln(&b)
u.writeClusterSummary(u.cluster.resources, stats, ctw)
ctw.Flush()
u.progress.ShowPercentage = true
// message printer formats numbers nicely with commas
enPrinter := message.NewPrinter(language.English)
enPrinter.Fprintf(&b, "%d pods (%d pending %d running %d bound)\n", stats.TotalPods,
stats.PodsByPhase[v1.PodPending], stats.PodsByPhase[v1.PodRunning], stats.BoundPodCount)
if stats.NumNodes == 0 {
fmt.Fprintln(&b)
fmt.Fprintln(&b, "Waiting for update or no nodes found...")
fmt.Fprintln(&b, u.paginator.View())
fmt.Fprintln(&b, helpStyle("←/→ page • q: quit"))
return b.String()
}
fmt.Fprintln(&b)
u.paginator.PerPage = u.computeItemsPerPage(stats.Nodes, &b)
u.paginator.SetTotalPages(stats.NumNodes)
// check if we're on a page that is outside of the NumNode upper bound
if u.paginator.Page*u.paginator.PerPage > stats.NumNodes {
// set the page to the last page
u.paginator.Page = u.paginator.TotalPages - 1
}
start, end := u.paginator.GetSliceBounds(stats.NumNodes)
if start >= 0 && end >= start {
for _, n := range stats.Nodes[start:end] {
u.writeNodeInfo(n, ctw, u.cluster.resources)
}
}
ctw.Flush()
fmt.Fprintln(&b, u.paginator.View())
fmt.Fprintln(&b, helpStyle("←/→ page • q: quit"))
return b.String()
}
func (u *UIModel) writeNodeInfo(n *Node, w io.Writer, resources []v1.ResourceName) {
allocatable := n.Allocatable()
used := n.Used()
firstLine := true
resNameLen := 0
for _, res := range resources {
if len(res) > resNameLen {
resNameLen = len(res)
}
}
for _, res := range resources {
usedRes := used[res]
allocatableRes := allocatable[res]
pct := usedRes.AsApproximateFloat64() / allocatableRes.AsApproximateFloat64()
if allocatableRes.AsApproximateFloat64() == 0 {
pct = 0
}
if firstLine {
priceLabel := fmt.Sprintf("/$%0.4f", n.Price)
if !n.HasPrice() || u.DisablePricing {
priceLabel = ""
}
fmt.Fprintf(w, "%s\t%s\t%s\t(%d pods)\t%s%s", n.Name(), res, u.progress.ViewAs(pct), n.NumPods(), n.InstanceType(), priceLabel)
// node compute type
if n.IsOnDemand() {
fmt.Fprintf(w, "\tOn-Demand")
} else if n.IsSpot() {
fmt.Fprintf(w, "\tSpot")
} else if n.IsFargate() {
fmt.Fprintf(w, "\tFargate")
} else {
fmt.Fprintf(w, "\t-")
}
if n.IsAuto() {
fmt.Fprintf(w, "/Auto")
}
// node status
if n.Cordoned() && n.Deleting() {
fmt.Fprintf(w, "\tCordoned/Deleting")
} else if n.Deleting() {
fmt.Fprintf(w, "\tDeleting")
} else if n.Cordoned() {
fmt.Fprintf(w, "\tCordoned")
} else {
fmt.Fprintf(w, "\t-")
}
// node readiness or time we've been waiting for it to be ready
if n.Ready() {
fmt.Fprintf(w, "\tReady")
} else {
fmt.Fprintf(w, "\tNotReady/%s", duration.HumanDuration(time.Since(n.NotReadyTime())))
}
for _, label := range u.extraLabels {
labelValue, ok := n.node.Labels[label]
if !ok {
// support computed label values
labelValue = n.ComputeLabel(label)
}
fmt.Fprintf(w, "\t%s", labelValue)
}
} else {
fmt.Fprintf(w, " \t%s\t%s\t\t\t\t\t", res, u.progress.ViewAs(pct))
for range u.extraLabels {
fmt.Fprintf(w, "\t")
}
}
fmt.Fprintln(w)
firstLine = false
}
}
func (u *UIModel) writeClusterSummary(resources []v1.ResourceName, stats Stats, w io.Writer) {
firstLine := true
for _, res := range resources {
allocatable := stats.AllocatableResources[res]
used := stats.UsedResources[res]
pctUsed := 0.0
if allocatable.AsApproximateFloat64() != 0 {
pctUsed = 100 * (used.AsApproximateFloat64() / allocatable.AsApproximateFloat64())
}
pctUsedStr := fmt.Sprintf("%0.1f%%", pctUsed)
if pctUsed > 90 {
pctUsedStr = u.style.green(pctUsedStr)
} else if pctUsed > 60 {
pctUsedStr = u.style.yellow(pctUsedStr)
} else {
pctUsedStr = u.style.red(pctUsedStr)
}
u.progress.ShowPercentage = false
monthlyPrice := stats.TotalPrice * (365 * 24) / 12 // average hours per month
// message printer formats numbers nicely with commas
enPrinter := message.NewPrinter(language.English)
clusterPrice := enPrinter.Sprintf("$%0.3f/hour | $%0.3f/month", stats.TotalPrice, monthlyPrice)
if u.DisablePricing {
clusterPrice = ""
}
if firstLine {
enPrinter.Fprintf(w, "%d nodes\t(%10s/%s)\t%s\t%s\t%s\t%s\n",
stats.NumNodes, used.String(), allocatable.String(), pctUsedStr, res, u.progress.ViewAs(pctUsed/100.0), clusterPrice)
} else {
enPrinter.Fprintf(w, " \t%s/%s\t%s\t%s\t%s\t\n",
used.String(), allocatable.String(), pctUsedStr, res, u.progress.ViewAs(pctUsed/100.0))
}
firstLine = false
}
}
// computeItemsPerPage dynamically calculates the number of lines we can fit per page
// taking into account header and footer text
func (u *UIModel) computeItemsPerPage(nodes []*Node, b *strings.Builder) int {
var buf bytes.Buffer
u.writeNodeInfo(nodes[0], &buf, u.cluster.resources)
headerLines := strings.Count(b.String(), "\n") + 2
nodeLines := strings.Count(buf.String(), "\n")
if nodeLines == 0 {
nodeLines = 1
}
return ((u.height - headerLines) / nodeLines) - 1
}
type tickMsg time.Time
func tickCmd() tea.Cmd {
return tea.Tick(100*time.Millisecond, func(t time.Time) tea.Msg {
return tickMsg(t)
})
}
func (u *UIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
u.height = msg.Height
return u, tickCmd()
case tea.KeyMsg:
switch msg.String() {
case "q", "esc", "ctrl+c":
return u, tea.Quit
}
case tickMsg:
return u, tickCmd()
}
var cmd tea.Cmd
u.paginator, cmd = u.paginator.Update(msg)
return u, cmd
}
func (u *UIModel) SetResources(resources []string) {
u.cluster.resources = nil
for _, r := range resources {
u.cluster.resources = append(u.cluster.resources, v1.ResourceName(r))
}
}
func makeNodeSorter(nodeSort string) func(lhs *Node, rhs *Node) bool {
sortOrder := func(b bool) bool { return b }
if strings.HasSuffix(nodeSort, "=asc") {
nodeSort = nodeSort[:len(nodeSort)-4]
}
if strings.HasSuffix(nodeSort, "=dsc") {
sortOrder = func(b bool) bool { return !b }
nodeSort = nodeSort[:len(nodeSort)-4]
}
if nodeSort == "creation" {
return func(lhs *Node, rhs *Node) bool {
if lhs.Created() == rhs.Created() {
return sortOrder(natsort.Compare(lhs.Name(), rhs.Name()))
}
return sortOrder(rhs.Created().Before(lhs.Created()))
}
}
return func(lhs *Node, rhs *Node) bool {
lhsLabel, ok := lhs.node.Labels[nodeSort]
if !ok {
lhsLabel = lhs.ComputeLabel(nodeSort)
}
rhsLabel, ok := rhs.node.Labels[nodeSort]
if !ok {
rhsLabel = rhs.ComputeLabel(nodeSort)
}
if lhsLabel == rhsLabel {
return sortOrder(natsort.Compare(lhs.InstanceID(), rhs.InstanceID()))
}
return sortOrder(natsort.Compare(lhsLabel, rhsLabel))
}
}