-
Notifications
You must be signed in to change notification settings - Fork 19
/
node.go
388 lines (346 loc) · 9.57 KB
/
node.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
package v1
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"time"
"github.com/baetyl/baetyl-go/v2/errors"
"github.com/evanphx/json-patch"
coreV1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
)
// maxJSONLevel the max level of json
const (
maxJSONLevel = 5
milliPrecision = 1000
)
// ErrJSONLevelExceedsLimit the level of json exceeds the max limit
var ErrJSONLevelExceedsLimit = fmt.Errorf("the level of json exceeds the max limit (%d)", maxJSONLevel)
// Node the spec of node
type Node struct {
Namespace string `json:"namespace,omitempty"`
Name string `json:"name,omitempty" validate:"omitempty,resourceName"`
Version string `json:"version,omitempty"`
CreationTimestamp time.Time `json:"createTime,omitempty"`
Labels map[string]string `json:"labels,omitempty" validate:"omitempty,validLabels"`
Annotations map[string]string `json:"annotations,omitempty"`
Report Report `json:"report,omitempty"`
Desire Desire `json:"desire,omitempty"`
Description string `json:"description,omitempty"`
}
type NodeView struct {
Namespace string `json:"namespace,omitempty"`
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
CreationTimestamp time.Time `json:"createTime,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
Report *ReportView `json:"report,omitempty"`
Desire Desire `json:"desire,omitempty"`
Description string `json:"description,omitempty"`
Ready bool `json:"ready"`
}
type ReportView struct {
Time *time.Time `json:"time,omitempty"`
Apps []AppInfo `json:"apps,omitempty"`
SysApps []AppInfo `json:"sysapps,omitempty"`
Core *CoreInfo `json:"core,omitempty"`
AppStats []AppStats `json:"appstats,omitempty"`
SysAppStats []AppStats `json:"sysappstats,omitempty"`
Node *NodeInfo `json:"node,omitempty"`
NodeStats *NodeStats `json:"nodestats,omitempty"`
}
// Report report data
type Report map[string]interface{}
// Desire desire data
type Desire map[string]interface{}
// Merge merge new reported data
func (r Report) Merge(reported Report) error {
return errors.Trace(merge(r, reported, 1, maxJSONLevel))
}
// Merge merge new reported data
func (d Desire) Merge(desired Desire) error {
return errors.Trace(merge(d, desired, 1, maxJSONLevel))
}
// Diff diff with reported data, return the delta fo desire
func (d Desire) Diff(reported Report) (Desire, error) {
res, err := diff(d, reported)
return res, errors.Trace(err)
}
func (r Report) AppInfos(isSys bool) []AppInfo {
if isSys {
return getAppInfos("sysapps", r)
} else {
return getAppInfos("apps", r)
}
}
func (r Report) SetAppInfos(isSys bool, apps []AppInfo) {
if isSys {
r["sysapps"] = apps
} else {
r["apps"] = apps
}
}
func (d Desire) AppInfos(isSys bool) []AppInfo {
if isSys {
return getAppInfos("sysapps", d)
} else {
return getAppInfos("apps", d)
}
}
func (d Desire) SetAppInfos(isSys bool, apps []AppInfo) {
if isSys {
d["sysapps"] = apps
} else {
d["apps"] = apps
}
}
func (r Report) SetAppStats(isSys bool, stats []AppStats) {
if isSys {
r["sysappstats"] = stats
} else {
r["appstats"] = stats
}
}
func (d Desire) SetAppStats(isSys bool, stats []AppStats) {
if isSys {
d["sysappstats"] = stats
} else {
d["appstats"] = stats
}
}
func (r Report) AppStats(isSys bool) []AppStats {
if isSys {
return getAppStats("sysappstats", r)
} else {
return getAppStats("appstats", r)
}
}
func (d Desire) AppStats(isSys bool) []AppStats {
if isSys {
return getAppStats("sysappstats", d)
} else {
return getAppStats("appstats", d)
}
}
func (n *Node) View(timeout time.Duration) (*NodeView, error) {
view := new(NodeView)
nodeStr, err := json.Marshal(n)
if err != nil {
return nil, errors.Trace(err)
}
err = json.Unmarshal(nodeStr, view)
if err != nil {
return nil, errors.Trace(err)
}
if err = view.populateNodeStats(timeout); err != nil {
return nil, errors.Trace(err)
}
if report := view.Report; report != nil {
if err = report.translateServiceResourceQuantity(); err != nil {
return nil, errors.Trace(err)
}
}
return view, nil
}
func (view *NodeView) populateNodeStats(timeout time.Duration) (err error) {
if view.Report == nil || view.Report.NodeStats == nil {
return nil
}
s := view.Report.NodeStats
s.Percent = map[string]string{}
memory := string(coreV1.ResourceMemory)
if s.Percent[memory], err = s.processResourcePercent(s, memory, populateMemoryResource); err != nil {
return errors.Trace(err)
}
cpu := string(coreV1.ResourceCPU)
if s.Percent[cpu], err = s.processResourcePercent(s, cpu, populateCPUResource); err != nil {
return errors.Trace(err)
}
if view.Report.Time != nil {
view.Ready = time.Now().Before(view.Report.Time.Add(timeout))
}
return
}
func (s *NodeStats) processResourcePercent(status *NodeStats, resourceType string,
populate func(usage string, resource map[string]string) (int64, error)) (string, error) {
cap, capOk := status.Capacity[resourceType]
usg, usageOk := status.Usage[resourceType]
var total, usage int64
var err error
if capOk {
if total, err = populate(cap, status.Capacity); err != nil {
return "0", errors.Trace(err)
}
}
if usageOk {
if usage, err = populate(usg, status.Usage); err != nil {
return "0", errors.Trace(err)
}
}
if capOk && usageOk && total != 0 {
return strconv.FormatFloat(float64(usage)/float64(total), 'f', -1, 64), nil
}
return "0", nil
}
func (view *ReportView) translateServiceResourceQuantity() error {
for idx := range view.SysAppStats {
instances := view.SysAppStats[idx].InstanceStats
if instances == nil {
continue
}
for _, v := range instances {
if err := v.translateResourceQuantity(); err != nil {
return errors.Trace(err)
}
}
}
for idx := range view.AppStats {
services := view.AppStats[idx].InstanceStats
if services == nil {
continue
}
for _, v := range services {
if err := v.translateResourceQuantity(); err != nil {
return errors.Trace(err)
}
}
}
return nil
}
func (s *InstanceStats) translateResourceQuantity() error {
if s.Usage == nil {
return nil
}
if cpuUsage, cpuOk := s.Usage[string(coreV1.ResourceCPU)]; cpuOk {
if _, err := populateCPUResource(cpuUsage, s.Usage); err != nil {
return errors.Trace(err)
}
}
if memoryUsage, mOk := s.Usage[string(coreV1.ResourceMemory)]; mOk {
if _, err := populateMemoryResource(memoryUsage, s.Usage); err != nil {
return errors.Trace(err)
}
}
return nil
}
func getAppInfos(appType string, data map[string]interface{}) []AppInfo {
if data == nil {
return nil
}
apps, ok := data[appType]
if !ok || apps == nil {
return nil
}
res, ok := apps.([]AppInfo)
if ok {
return res
}
res = []AppInfo{}
ais, ok := apps.([]interface{})
if !ok {
return nil
}
for _, ai := range ais {
aim := ai.(map[string]interface{})
if aim == nil {
return nil
}
res = append(res, AppInfo{Name: aim["name"].(string), Version: aim["version"].(string)})
}
return res
}
func getAppStats(statsType string, data map[string]interface{}) []AppStats {
if data == nil {
return nil
}
apps, ok := data[statsType]
if !ok || apps == nil {
return nil
}
if res, ok := apps.([]AppStats); ok {
return res
} else {
return nil
}
}
// merge right map into left map
func merge(left, right map[string]interface{}, depth, maxDepth int) error {
if depth >= maxDepth {
return ErrJSONLevelExceedsLimit
}
for rk, rv := range right {
lv, ok := left[rk]
if !ok || lv == nil || rv == nil || reflect.TypeOf(rv).Kind() != reflect.Map || reflect.TypeOf(lv).Kind() != reflect.Map {
left[rk] = rv
continue
}
if err := merge(lv.(map[string]interface{}), rv.(map[string]interface{}), depth+1, maxDepth); err != nil {
return errors.Trace(err)
}
}
return nil
}
func diff(desired, reported map[string]interface{}) (map[string]interface{}, error) {
var delta map[string]interface{}
r, err := json.Marshal(reported)
if err != nil {
return delta, errors.Trace(err)
}
d, err := json.Marshal(desired)
if err != nil {
return delta, errors.Trace(err)
}
patch, err := jsonpatch.CreateMergePatch(r, d)
if err != nil {
return delta, errors.Trace(err)
}
err = json.Unmarshal(patch, &delta)
if err != nil {
return delta, errors.Trace(err)
}
clean(delta)
return delta, nil
}
func clean(m map[string]interface{}) {
for k, v := range m {
if v == nil {
delete(m, k)
continue
}
bk := reflect.TypeOf(v).Kind()
if bk != reflect.Map {
continue
}
if vm, ok := v.(map[string]interface{}); ok {
clean(vm)
}
}
}
func populateCPUResource(usage string, resource map[string]string) (int64, error) {
usg, err := translateQuantityToDecimal(usage, true)
if err != nil {
return 0, errors.Trace(err)
}
resource[string(coreV1.ResourceCPU)] = strconv.FormatFloat(float64(usg)/milliPrecision, 'f', -1, 64)
return usg, nil
}
func populateMemoryResource(usage string, resource map[string]string) (int64, error) {
usg, err := translateQuantityToDecimal(usage, false)
if err != nil {
return 0, errors.Trace(err)
}
resource[string(coreV1.ResourceMemory)] = strconv.FormatInt(usg, 10)
return usg, nil
}
func translateQuantityToDecimal(q string, milli bool) (int64, error) {
num, err := resource.ParseQuantity(q)
if err != nil {
return 0, errors.Trace(err)
}
if milli {
return num.MilliValue(), nil
}
return num.Value(), nil
}