-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlambda.go
371 lines (334 loc) · 10.3 KB
/
lambda.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
package lambda
import (
"fmt"
"reflect"
"strings"
"time"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/dynamic"
)
// Predicate is a function has only one parameter and return boolean.
// When return value type is not boolean, panic will occur.
// The parameter can be of any type but nil and predicates is always used to test an element.
type Predicate interface{}
// Consumer is a function has one parameter and returns one value.
// Nil is not allowed to be used as parameter or return value, or panic will occur.
// Consumer is always used to apply some transformation to elements.
type Consumer interface{}
// Function is a function has one parameter and has no return value.
// The parameter must not be a nil
type Function interface{}
// Producer is a function takes no parameter and returns a value.
// Producer is recommeneded to be a closure so that the returning value can be controlled outside lambda.
type Producer interface{}
func callPredicate(f interface{}, arg interface{}) bool {
if isZeroOfUnderlyingType(arg) {
panic(fmt.Sprintf("nil argument detected when calling predicate %#v with arg %#v", f, arg))
}
ret := reflect.ValueOf(f).Call([]reflect.Value{
reflect.ValueOf(arg),
})
return ret[0].Bool()
}
func callFunction(f interface{}, arg interface{}) {
if isZeroOfUnderlyingType(arg) {
panic(fmt.Sprintf("nil argument detected when calling function %#v with arg %#v", f, arg))
}
reflect.ValueOf(f).Call([]reflect.Value{
reflect.ValueOf(arg),
})
}
func callConsumer(f interface{}, arg interface{}) interface{} {
if isZeroOfUnderlyingType(arg) {
panic(fmt.Sprintf("nil argument detected when calling consumer %#v with arg %#v", f, arg))
}
ret := reflect.ValueOf(f).Call([]reflect.Value{
reflect.ValueOf(arg),
})
if isZeroOfUnderlyingType(ret[0].Interface()) {
panic(fmt.Sprintf("nil return value detected when calling consumer %#v with arg %#v", f, arg))
}
return ret[0].Interface()
}
func callProducer(f interface{}) interface{} {
ret := reflect.ValueOf(f).Call([]reflect.Value{})
if isZeroOfUnderlyingType(ret[0].Interface()) {
panic(fmt.Sprintf("nil return value detected when calling producer %#v", f))
}
return ret[0].Interface()
}
// Lambda is a basic and core type of KCL. It holds a channel for receiving elements from previous
// lambda or kubernetes resource fetcher. Error is assigned if any error occured during lambda
// pipelining. The error will be recorded but the lambda pipelining will continue on, and forcing it
// fail-hard needs call MustNoError method. The error can be also be returned at the end of a pipeline
// via lambda operation method which is defined in lambda_operation.go
type Lambda struct {
getFunc func(namespace, name string) (runtime.Object, error)
listFunc func(namespace string, selector labels.Selector) ([]runtime.Object, error)
createFunc func(runtime.Object) error
updateFunc func(runtime.Object) error
deleteFunc func(runtime.Object) error
clientInterface dynamic.Interface
rs Resource
namespaces []string
val <-chan runtime.Object
Errors []error
}
func (lambda *Lambda) run(f func()) error {
if !lambda.NoError() {
return &ErrMultiLambdaFailure{
errors: lambda.Errors,
}
}
f()
if len(lambda.Errors) != 0 {
return &ErrMultiLambdaFailure{
errors: lambda.Errors,
}
}
return nil
}
func (lambda *Lambda) addError(err error) {
if lambda.Errors == nil {
lambda.Errors = []error{err}
}
lambda.Errors = append(lambda.Errors, err)
}
func (lambda *Lambda) clone() (*Lambda, chan runtime.Object) {
ch := make(chan runtime.Object)
l := &Lambda{
rs: lambda.rs,
val: ch,
Errors: lambda.Errors,
getFunc: lambda.getFunc,
listFunc: lambda.listFunc,
createFunc: lambda.createFunc,
updateFunc: lambda.updateFunc,
deleteFunc: lambda.deleteFunc,
clientInterface: lambda.clientInterface,
}
return l, ch
}
//********************************************************
// Lambda with no parameter
//********************************************************
// Collect deep copies every element in the lambda
func (lambda *Lambda) Collect() *Lambda {
l, ch := lambda.clone()
go func() {
defer close(ch)
for item := range lambda.val {
if obj, ok := item.(runtime.Object); !ok {
l.addError(fmt.Errorf("Invalid object type of %#v", obj))
} else {
ch <- obj.DeepCopyObject()
}
}
}()
return l
}
// LatestCreated filters out the latest created object
func (lambda *Lambda) LatestCreated() *Lambda {
l, ch := lambda.clone()
go func() {
defer close(ch)
var latestObj runtime.Object
var latestTimestamp *time.Time
for item := range lambda.val {
item := item
accessor, _ := meta.Accessor(item)
if latestTimestamp == nil || accessor.GetCreationTimestamp().Time.After(*latestTimestamp) {
t := accessor.GetCreationTimestamp().Time
latestTimestamp = &t
latestObj = item
}
}
ch <- latestObj
}()
return l
}
// Element returns a single element. Note that if multiple elements
// exists in the lambda pipeline, a random object may be returned.
func (lambda *Lambda) Element() (runtime.Object, error) {
var element runtime.Object
for item := range lambda.val {
element = item
}
if element == nil {
return nil, fmt.Errorf("no element found")
}
return element, nil
}
// Elements returns all elements from the lambda pipeline.
func (lambda *Lambda) Elements() ([]runtime.Object, error) {
var elements []runtime.Object
for item := range lambda.val {
item := item
elements = append(elements, item)
}
if len(elements) == 0 {
return nil, fmt.Errorf("no elements found")
}
return elements, nil
}
//********************************************************
// Lambda using Predicate
//********************************************************
// First returnes the first element matches the predicate
func (lambda *Lambda) First(predicate Predicate) *Lambda {
l, ch := lambda.clone()
go func() {
defer close(ch)
for item := range lambda.val {
if callPredicate(predicate, item) {
ch <- item
break
}
}
}()
return l
}
// Grep returnes the elements matches the predicate
func (lambda *Lambda) Grep(predicate Predicate) *Lambda {
l, ch := lambda.clone()
go func() {
defer close(ch)
for item := range lambda.val {
if callPredicate(predicate, item) {
ch <- item
}
}
}()
return l
}
//********************************************************
// Lambda using Consumer
//********************************************************
// Map transforms and replace the elements and put them to the next lambda
func (lambda *Lambda) Map(consumer Consumer) *Lambda {
l, ch := lambda.clone()
go func() {
defer close(ch)
for item := range lambda.val {
if v := callConsumer(consumer, item); v != nil {
ch <- v.(runtime.Object)
}
}
}()
return l
}
//********************************************************
// Lambda using Function
//********************************************************
// Iter iterates the elements and apply function to them
// Note that modifying is not recommened in Iter, use Map to modify elements instead
func (lambda *Lambda) Iter(function Function) *Lambda {
l, ch := lambda.clone()
go func() {
defer close(ch)
for item := range lambda.val {
callFunction(function, item)
ch <- item
}
}()
return l
}
//********************************************************
// Lambda using Producer
//********************************************************
// Add calls the producer and put the returned value into elements
func (lambda *Lambda) Add(producer Producer) *Lambda {
l, ch := lambda.clone()
go func() {
defer close(ch)
for item := range lambda.val {
ch <- item
}
if v := callProducer(producer); v != nil {
ch <- v.(runtime.Object)
}
}()
return l
}
//********************************************************
// Snippet Kubernetes Lambda Functions
// Utility Lambda Function
//********************************************************
// NameEqual filter the elements out if its name mismatches with the argument name
func (lambda *Lambda) NameEqual(name string) *Lambda {
return lambda.Grep(func(object runtime.Object) bool {
accessor, err := meta.Accessor(object)
if err != nil {
return false
}
return accessor.GetName() == name
})
}
// NamePrefix filter the elements out if its name doesn't have the prefix
func (lambda *Lambda) NamePrefix(prefix string) *Lambda {
return lambda.Grep(func(object runtime.Object) bool {
accessor, err := meta.Accessor(object)
if err != nil {
return false
}
return strings.HasPrefix(accessor.GetName(), prefix)
})
}
// NameRegex filter the elements out if its name fails to matches the regexp
func (lambda *Lambda) NameRegex(regex string) *Lambda {
return lambda.Grep(func(object runtime.Object) bool {
accessor, err := meta.Accessor(object)
if err != nil {
return false
}
name := accessor.GetName()
matched, err := regexMatch(name, regex)
if err != nil {
lambda.addError(err)
return false
}
return matched
})
}
// HasAnnotation filter the elements out if it doesn't have the arugument annotation
func (lambda *Lambda) HasAnnotation(key, value string) *Lambda {
return lambda.Grep(func(object runtime.Object) bool {
accessor, err := meta.Accessor(object)
if err != nil {
return false
}
return accessor.GetAnnotations()[key] == value
})
}
// HasAnnotationKey filter the elements out if it doesn't have the arugument annotation key
func (lambda *Lambda) HasAnnotationKey(key string) *Lambda {
return lambda.Grep(func(object runtime.Object) bool {
accessor, err := meta.Accessor(object)
if err != nil {
return false
}
return accessor.GetAnnotations()[key] != ""
})
}
// HasLabel filter the elements out if it doesn't have the arugument label
func (lambda *Lambda) HasLabel(key, value string) *Lambda {
return lambda.Grep(func(object runtime.Object) bool {
accessor, err := meta.Accessor(object)
if err != nil {
return false
}
return accessor.GetLabels()[key] != value
})
}
// HasLabelKey filter the elements out if it doesn't have the arugument label key
func (lambda *Lambda) HasLabelKey(key string) *Lambda {
return lambda.Grep(func(object runtime.Object) bool {
accessor, err := meta.Accessor(object)
if err != nil {
return false
}
return accessor.GetLabels()[key] != ""
})
}