-
Notifications
You must be signed in to change notification settings - Fork 103
/
common.go
372 lines (323 loc) · 7.17 KB
/
common.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
/*
Copyright 2022 The Katalyst Authors.
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 general
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/sets"
)
func Max(a, b int) int {
if a >= b {
return a
} else {
return b
}
}
func MaxUInt64(a, b uint64) uint64 {
if a >= b {
return a
} else {
return b
}
}
func MaxInt64(a, b int64) int64 {
if a >= b {
return a
} else {
return b
}
}
func MaxFloat64(a, b float64) float64 {
if a >= b {
return a
} else {
return b
}
}
func MaxTimePtr(a, b *time.Time) *time.Time {
if a == nil {
return b
} else if b == nil {
return a
} else if a.After(*b) {
return a
}
return b
}
func Min(a, b int) int {
if a >= b {
return b
} else {
return a
}
}
func MinUInt64(a, b uint64) uint64 {
if a <= b {
return a
} else {
return b
}
}
func MinInt64(a, b int64) int64 {
if a <= b {
return a
} else {
return b
}
}
func MinUInt32(a, b uint32) uint32 {
if a <= b {
return a
} else {
return b
}
}
func MinFloat64(a, b float64) float64 {
if a >= b {
return b
} else {
return a
}
}
// IsNameEnabled check if a specified name enabled or not.
func IsNameEnabled(name string, disabledByDefault sets.String, enableNames []string) bool {
hasStar := false
for _, ctrl := range enableNames {
if ctrl == name {
return true
}
if ctrl == "-"+name {
return false
}
if ctrl == "*" {
hasStar = true
}
}
// if we get here, there was no explicit choice
if !hasStar {
// nothing on by default
return false
}
if disabledByDefault != nil {
return !disabledByDefault.Has(name)
}
return true
}
func ParseUint64PointerToString(v *uint64) string {
if v == nil {
return "nil"
} else {
return fmt.Sprintf("%d", *v)
}
}
func ParseStringToUint64Pointer(s string) (*uint64, error) {
if s == "nil" {
return nil, nil
} else {
v, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return nil, err
}
return &v, nil
}
}
func GetInt64PointerFromUint64Pointer(v *uint64) (*int64, error) {
if v == nil {
return nil, nil
}
ret := int64(*v)
if ret < 0 {
return &ret, fmt.Errorf("transformation overflows")
} else {
return &ret, nil
}
}
func GenerateHash(data []byte, length int) string {
h := sha256.New()
h.Write(data)
result := fmt.Sprintf("%x", h.Sum(nil))
if len(result) > length {
return result[:length]
}
return result
}
func UIntPointerToFloat64(p *uint) float64 {
if p == nil {
return 0
}
return float64(*p)
}
func UInt64PointerToFloat64(p *uint64) float64 {
if p == nil {
return 0
}
return float64(*p)
}
// JsonPathEmpty is used to check whether the given str is empty for json-patch
func JsonPathEmpty(str []byte) bool {
if "{}" == string(str) || "" == string(str) {
return true
}
return false
}
// GetValueWithDefault gets value from the given map, and returns default if key not exist
func GetValueWithDefault(m map[string]string, key, defaultV string) string {
if _, ok := m[key]; !ok {
return defaultV
}
return m[key]
}
func GetStringValueFromMap(m map[string]string, key string) string {
if value, found := m[key]; found {
return value
}
return ""
}
// SumUpMultipleMapValues accumulates total values for the given multi-level map
func SumUpMultipleMapValues(m map[string]map[string]int) int {
total := 0
for _, v := range m {
total += SumUpMapValues(v)
}
return total
}
// SumUpMapValues accumulates total values for the given map
func SumUpMapValues(m map[string]int) int {
total := 0
for _, quantity := range m {
total += quantity
}
return total
}
func CheckMapEqual(pre, cur map[string]string) bool {
if len(pre) != len(cur) {
return false
}
for key, value := range pre {
if value != cur[key] {
return false
}
}
return true
}
// MergeMap merges the contents from override into the src
func MergeMap(src, override map[string]string) map[string]string {
res := map[string]string{}
for k, v := range src {
res[k] = v
}
for k, v := range override {
res[k] = v
}
return res
}
// MergeMapInt merges the contents from override into the src
func MergeMapInt(src, override map[string]int) map[string]int {
res := map[string]int{}
for k, v := range src {
res[k] = v
}
for k, v := range override {
res[k] = v
}
return res
}
// GetSortedMapKeys returns a slice containing sorted keys for the given map
func GetSortedMapKeys(m map[string]int) []string {
ret := make([]string, 0, len(m))
for key := range m {
ret = append(ret, key)
}
sort.Strings(ret)
return ret
}
// ParseMapWithPrefix converts selector string to label map
// and validates keys and values
func ParseMapWithPrefix(prefix, selector string) (map[string]string, error) {
labelsMap := make(map[string]string)
if len(selector) == 0 {
return labelsMap, nil
}
labels := strings.Split(selector, ",")
for _, label := range labels {
l := strings.Split(label, "=")
if len(l) != 2 {
return labelsMap, fmt.Errorf("invalid selector: %s", l)
}
key := strings.TrimSpace(l[0])
value := strings.TrimSpace(l[1])
labelsMap[prefix+key] = value
}
return labelsMap, nil
}
// ToString transform to string for better display etc. in log
func ToString(in interface{}) string {
var out bytes.Buffer
b, _ := json.Marshal(in)
_ = json.Indent(&out, b, "", " ")
return out.String()
}
func IntSliceToStringSlice(a []int) []string {
var ss []string
for _, i := range a {
ss = append(ss, strconv.Itoa(i))
}
return ss
}
func CovertInt64ToInt(numInt64 int64) (int, error) {
numInt := int(numInt64)
if int64(numInt) != numInt64 {
return 0, fmt.Errorf("convert numInt64: %d to numInt: %d failed", numInt64, numInt)
}
return numInt, nil
}
func CovertUInt64ToInt(numUInt64 uint64) (int, error) {
numInt := int(numUInt64)
if numInt < 0 || uint64(numInt) != numUInt64 {
return 0, fmt.Errorf("convert numUInt64: %d to numInt: %d failed", numUInt64, numInt)
}
return numInt, nil
}
// Clamp returns value itself if min < value < max; min if value < min; max if value > max
func Clamp(value, min, max float64) float64 {
return math.Max(math.Min(value, max), min)
}
// FormatMemoryQuantity aligned to Gi Mi Ki
func FormatMemoryQuantity(q float64) string {
value := int64(q)
if (value >> 30) > 0 {
value = (value >> 30) << 30
} else if (value >> 20) > 0 {
value = (value >> 20) << 20
} else if (value >> 10) > 0 {
value = (value >> 10) << 10
}
quantity := resource.NewQuantity(value, resource.BinarySI)
return fmt.Sprintf("%v[%v]", q, quantity.String())
}
// DedupStringSlice return deduplicated string slice from original
func DedupStringSlice(input []string) []string {
result := sets.NewString()
for _, v := range input {
result.Insert(v)
}
return result.UnsortedList()
}