This repository has been archived by the owner on Jan 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathutils.go
290 lines (254 loc) · 5.11 KB
/
utils.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
package fake_kubelet
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"net"
"strconv"
"strings"
"sync"
"text/template"
"time"
jsonpatch "gopkg.in/evanphx/json-patch.v5"
"sigs.k8s.io/yaml"
)
func parseCIDR(s string) (*net.IPNet, error) {
ip, ipnet, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
ipnet.IP = ip
return ipnet, nil
}
func addIp(ip net.IP, add uint64) net.IP {
if len(ip) < 8 {
return ip
}
out := make(net.IP, len(ip))
copy(out, ip)
i := binary.BigEndian.Uint64(out[len(out)-8:])
i += add
binary.BigEndian.PutUint64(out[len(out)-8:], i)
return out
}
type ipPool struct {
mut sync.Mutex
used map[string]struct{}
usable map[string]struct{}
cidr *net.IPNet
index uint64
}
func newIPPool(cidr *net.IPNet) *ipPool {
return &ipPool{
used: make(map[string]struct{}),
usable: make(map[string]struct{}),
cidr: cidr,
}
}
func (i *ipPool) new() string {
for {
ip := addIp(i.cidr.IP, i.index).String()
i.index++
if _, ok := i.used[ip]; ok {
continue
}
i.used[ip] = struct{}{}
i.usable[ip] = struct{}{}
return ip
}
}
func (i *ipPool) Get() string {
i.mut.Lock()
defer i.mut.Unlock()
ip := ""
if len(i.usable) != 0 {
for s := range i.usable {
ip = s
}
}
if ip == "" {
ip = i.new()
}
delete(i.usable, ip)
i.used[ip] = struct{}{}
return ip
}
func (i *ipPool) Put(ip string) {
i.mut.Lock()
defer i.mut.Unlock()
if !i.cidr.Contains(net.ParseIP(ip)) {
return
}
delete(i.used, ip)
i.usable[ip] = struct{}{}
}
func (i *ipPool) Use(ip string) {
i.mut.Lock()
defer i.mut.Unlock()
if !i.cidr.Contains(net.ParseIP(ip)) {
return
}
i.used[ip] = struct{}{}
}
func toTemplateJson(text string, original interface{}, funcMap template.FuncMap) ([]byte, error) {
text = strings.TrimSpace(text)
v, ok := templateCache.Load(text)
if !ok {
temp, err := template.New("_").Funcs(funcMap).Parse(text)
if err != nil {
return nil, err
}
templateCache.Store(text, temp)
v = temp
}
temp := v.(*template.Template)
buf := bufferPool.Get().(*bytes.Buffer)
defer bufferPool.Put(buf)
buf.Reset()
err := json.NewEncoder(buf).Encode(original)
if err != nil {
return nil, err
}
var data interface{}
decoder := json.NewDecoder(buf)
decoder.UseNumber()
err = decoder.Decode(&data)
if err != nil {
return nil, err
}
buf.Reset()
err = temp.Execute(buf, data)
if err != nil {
return nil, err
}
out, err := yaml.YAMLToJSON(buf.Bytes())
if err != nil {
return nil, fmt.Errorf("%w: %s", err, buf.String())
}
return out, nil
}
var (
templateCache = sync.Map{}
bufferPool = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
)
type parallelTasks struct {
wg sync.WaitGroup
bucket chan struct{}
tasks chan func()
}
func newParallelTasks(n int) *parallelTasks {
return ¶llelTasks{
bucket: make(chan struct{}, n),
tasks: make(chan func()),
}
}
func (p *parallelTasks) Add(fun func()) {
p.wg.Add(1)
select {
case p.tasks <- fun: // there are idle threads
case p.bucket <- struct{}{}: // there are free threads
go p.fork()
p.tasks <- fun
}
}
func (p *parallelTasks) fork() {
defer func() {
<-p.bucket
}()
timer := time.NewTimer(time.Second / 2)
for {
select {
case <-timer.C: // idle threads
return
case fun := <-p.tasks:
fun()
p.wg.Done()
timer.Reset(time.Second / 2)
}
}
}
func (p *parallelTasks) Wait() {
p.wg.Wait()
}
type stringSets struct {
mut sync.RWMutex
sets map[string]struct{}
}
func newStringSets() *stringSets {
return &stringSets{
sets: make(map[string]struct{}),
}
}
func (s *stringSets) Size() int {
s.mut.RLock()
defer s.mut.RUnlock()
return len(s.sets)
}
func (s *stringSets) Put(key string) {
s.mut.Lock()
defer s.mut.Unlock()
s.sets[key] = struct{}{}
}
func (s *stringSets) Delete(key string) {
s.mut.Lock()
defer s.mut.Unlock()
delete(s.sets, key)
}
func (s *stringSets) Has(key string) bool {
s.mut.RLock()
defer s.mut.RUnlock()
_, ok := s.sets[key]
return ok
}
func (s *stringSets) Foreach(f func(string)) {
s.mut.RLock()
defer s.mut.RUnlock()
for k := range s.sets {
f(k)
}
}
const overwriteTemplateAnnotations = "fake/status"
// modifyStatusByAnnotations modifies the status by the annotations.
func modifyStatusByAnnotations(origin []byte, anno map[string]string) ([]byte, error) {
const prefix = overwriteTemplateAnnotations + "."
var patch jsonpatch.Patch
for name, value := range anno {
if strings.HasPrefix(name, prefix) {
p := name[len(prefix):]
if p == "" {
continue
}
op := json.RawMessage(`"add"`)
n := json.RawMessage(strconv.Quote("/" + strings.ReplaceAll(p, ".", "/")))
v := json.RawMessage(value)
if !json.Valid(v) {
// Treat it as a string if it is not a valid JSON encoding
v = json.RawMessage(strconv.Quote(value))
}
patch = append(patch, jsonpatch.Operation{
"op": &op,
"path": &n,
"value": &v,
})
}
}
if len(patch) != 0 {
return patch.Apply(origin)
}
return origin, nil
}
func GenerateSerialNumber(n int, minLen int, fun func(string) bool) {
if n <= 0 {
return
}
for i := 0; i != n; i++ {
if !fun(fmt.Sprintf("%0*d", minLen, i)) {
break
}
}
}