This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
/
conditionutils.go
1178 lines (1014 loc) · 36.5 KB
/
conditionutils.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 OnMetal 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 conditionutils simplifies condition handling with any structurally compatible condition
// (comparable to a sort of duck-typing) via go reflection.
package conditionutils
import (
"fmt"
"reflect"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/utils/clock"
)
const (
// DefaultTypeField is the default name for a condition's type field.
DefaultTypeField = "Type"
// DefaultStatusField is the default name for a condition's status field.
DefaultStatusField = "Status"
// DefaultLastUpdateTimeField field is the default name for a condition's last update time field.
DefaultLastUpdateTimeField = "LastUpdateTime"
// DefaultLastTransitionTimeField field is the default name for a condition's last transition time field.
DefaultLastTransitionTimeField = "LastTransitionTime"
// DefaultReasonField field is the default name for a condition's reason field.
DefaultReasonField = "Reason"
// DefaultMessageField field is the default name for a condition's message field.
DefaultMessageField = "Message"
// DefaultObservedGenerationField field is the default name for a condition's observed generation field.
DefaultObservedGenerationField = "ObservedGeneration"
)
func enforceStruct(cond interface{}) (reflect.Value, error) {
v := reflect.ValueOf(cond)
if v.Kind() != reflect.Struct {
return reflect.Value{}, fmt.Errorf("type %T is not a struct", cond)
}
return v, nil
}
func enforcePtrToStruct(cond interface{}) (reflect.Value, error) {
v := reflect.ValueOf(cond)
if v.Kind() != reflect.Ptr {
return reflect.Value{}, fmt.Errorf("type %T is not a pointer to a struct", cond)
}
v = v.Elem()
if v.Kind() != reflect.Struct {
return reflect.Value{}, fmt.Errorf("type %T is not a pointer to a struct", cond)
}
return v, nil
}
func enforceStructSlice(condSlice interface{}) (sliceV reflect.Value, structType reflect.Type, err error) {
v := reflect.ValueOf(condSlice)
if v.Kind() != reflect.Slice {
return reflect.Value{}, nil, fmt.Errorf("type %T is not a slice of structs", condSlice)
}
structType = v.Type().Elem()
if structType.Kind() != reflect.Struct {
return reflect.Value{}, nil, fmt.Errorf("type %T is not a slice of structs", condSlice)
}
return v, structType, nil
}
func enforcePtrToStructSlice(condSlicePtr interface{}) (sliceV reflect.Value, structType reflect.Type, err error) {
v := reflect.ValueOf(condSlicePtr)
if v.Kind() != reflect.Ptr {
return reflect.Value{}, nil, fmt.Errorf("type %T is not a pointer to a slice of structs", condSlicePtr)
}
v = v.Elem()
if v.Kind() != reflect.Slice {
return reflect.Value{}, nil, fmt.Errorf("type %T is not a pointer to a slice of structs", condSlicePtr)
}
structType = v.Type().Elem()
if structType.Kind() != reflect.Struct {
return reflect.Value{}, nil, fmt.Errorf("type %T is not a pointer to a slice of structs", condSlicePtr)
}
return v, structType, nil
}
func getAndConvertField(v reflect.Value, name string, into interface{}) error {
f := v.FieldByName(name)
if !v.IsValid() {
return fmt.Errorf("type %T has no field %q", v.Interface(), name)
}
intoV, err := conversion.EnforcePtr(into)
if err != nil {
return err
}
fType := f.Type()
if fType.Kind() == reflect.Ptr {
fType = fType.Elem()
}
if !fType.ConvertibleTo(intoV.Type()) {
return fmt.Errorf("type %T field %q type %s cannot be converted into %T", v.Interface(), fType, name, into)
}
intoV.Set(reflect.Indirect(f).Convert(intoV.Type()))
return nil
}
// direct is the inverse to reflect.Indirect.
//
// It takes in a value and returns nil if it is a zero value.
// Otherwise, it returns a pointer to that value.
func direct(v reflect.Value) reflect.Value {
if v.IsZero() {
return reflect.New(reflect.PtrTo(v.Type())).Elem()
}
res := reflect.New(v.Type())
res.Elem().Set(v)
return res
}
// setFieldConverted sets the specified field to the given value, potentially converting it before.
func setFieldConverted(v reflect.Value, name string, newValue interface{}) error {
f := v.FieldByName(name)
if f == (reflect.Value{}) {
return fmt.Errorf("type %T has no field %q", v.Interface(), name)
}
fType := f.Type()
var isPtr bool
if fType.Kind() == reflect.Ptr {
isPtr = true
fType = fType.Elem()
}
newV := reflect.ValueOf(newValue)
if !newV.CanConvert(fType) {
return fmt.Errorf("value %T cannot be converted into type %s of field %q of type %T", newValue, fType, name, v.Interface())
}
newV = newV.Convert(fType)
if isPtr {
newV = direct(newV)
}
f.Set(newV)
return nil
}
func valueHasField(v reflect.Value, name string) bool {
return v.FieldByName(name) != (reflect.Value{})
}
// Accessor allows getting and setting fields from conditions as well as to check on their presence.
// In addition, it allows complex manipulations on individual conditions and condition slices.
type Accessor struct {
typeField string
statusField string
lastUpdateTimeField string
lastTransitionTimeField string
reasonField string
messageField string
observedGenerationField string
disableTimestampUpdates bool
transition Transition
clock clock.Clock
}
// Transition can determine whether a condition transitioned (i.e. LastTransitionTime needs to be updated) or not.
type Transition interface {
// Checkpoint creates a TransactionCheckpoint using the current values of cond extracted with Accessor.
Checkpoint(acc *Accessor, cond interface{}) (TransitionCheckpoint, error)
}
// TransitionCheckpoint can determine whether a condition transitioned using pre-gathered values of a condition.
type TransitionCheckpoint interface {
// Transitioned reports whether the condition transitioned.
Transitioned(acc *Accessor, cond interface{}) (bool, error)
}
// FieldsTransition computes whether a condition transitioned using the `Include`-Fields.
type FieldsTransition struct {
// IncludeStatus includes Accessor.Status for the transition calculation. This is the most frequent choice.
IncludeStatus bool
// IncludeReason includes Accessor.Reason for the transition calculation. While more seldom, there are use cases
// for including the reason in the transition calculation.
IncludeReason bool
// IncludeMessage includes Accessor.Message for the transition calculation. Used rarely, usually causes
// a lot of transitions.
IncludeMessage bool
}
func (f *FieldsTransition) computeValues(acc *Accessor, cond interface{}) (*fieldsTransitionValues, error) {
var fields fieldsTransitionValues
if f.IncludeStatus {
status, err := acc.Status(cond)
if err != nil {
return nil, err
}
fields.Status = status
}
if f.IncludeReason {
reason, err := acc.Reason(cond)
if err != nil {
return nil, err
}
fields.Reason = reason
}
if f.IncludeMessage {
message, err := acc.Message(cond)
if err != nil {
return nil, err
}
fields.Message = message
}
return &fields, nil
}
// Checkpoint implements Transition.
func (f *FieldsTransition) Checkpoint(acc *Accessor, cond interface{}) (TransitionCheckpoint, error) {
values, err := f.computeValues(acc, cond)
if err != nil {
return nil, err
}
return &fieldsTransitionCheckpoint{
transition: *f,
values: *values,
}, nil
}
type fieldsTransitionValues struct {
Status corev1.ConditionStatus
Reason string
Message string
}
type fieldsTransitionCheckpoint struct {
transition FieldsTransition
values fieldsTransitionValues
}
// Transitioned implements TransitionCheckpoint.
func (f *fieldsTransitionCheckpoint) Transitioned(acc *Accessor, cond interface{}) (bool, error) {
newValues, err := f.transition.computeValues(acc, cond)
if err != nil {
return false, err
}
return newValues.Status != f.values.Status ||
newValues.Reason != f.values.Reason ||
newValues.Message != f.values.Message, nil
}
// Type extracts the type of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) Type(cond interface{}) (string, error) {
v, err := enforceStruct(cond)
if err != nil {
return "", err
}
var typeValue string
if err := getAndConvertField(v, a.typeField, &typeValue); err != nil {
return "", err
}
return typeValue, nil
}
// MustType extracts the type of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) MustType(cond interface{}) string {
typ, err := a.Type(cond)
utilruntime.Must(err)
return typ
}
// SetType sets the type of the given condition to the given value.
//
// It errors if the given value is not a pointer to a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) SetType(condPtr interface{}, typ string) error {
v, err := enforcePtrToStruct(condPtr)
if err != nil {
return err
}
return setFieldConverted(v, a.typeField, typ)
}
// MustSetType sets the type of the given condition to the given value.
//
// It panics if the given value is not a pointer to a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) MustSetType(condPtr interface{}, typ string) {
utilruntime.Must(a.SetType(condPtr, typ))
}
// Status extracts the status of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) Status(cond interface{}) (corev1.ConditionStatus, error) {
v, err := enforceStruct(cond)
if err != nil {
return "", err
}
var status corev1.ConditionStatus
if err := getAndConvertField(v, a.statusField, &status); err != nil {
return "", err
}
return status, nil
}
// MustStatus extracts the status of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) MustStatus(cond interface{}) corev1.ConditionStatus {
status, err := a.Status(cond)
utilruntime.Must(err)
return status
}
// SetStatus sets the status of the given condition.
//
// It errors if the given value is not a pointer to a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) SetStatus(condPtr interface{}, status corev1.ConditionStatus) error {
v, err := enforcePtrToStruct(condPtr)
if err != nil {
return err
}
return setFieldConverted(v, a.statusField, status)
}
// MustSetStatus sets the status of the given condition.
//
// It panics if the given value is not a pointer to a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) MustSetStatus(condPtr interface{}, status corev1.ConditionStatus) {
utilruntime.Must(a.SetStatus(condPtr, status))
}
// HasLastUpdateTime checks if the given condition has a 'LastUpdateTime' field.
//
// It errors if the given value is not a struct.
func (a *Accessor) HasLastUpdateTime(cond interface{}) (bool, error) {
v, err := enforceStruct(cond)
if err != nil {
return false, err
}
return valueHasField(v, a.lastUpdateTimeField), nil
}
// MustHasLastUpdateTime checks if the given condition has a 'LastUpdateTime' field.
//
// It panics if the given value is not a struct.
func (a *Accessor) MustHasLastUpdateTime(cond interface{}) bool {
ok, err := a.HasLastUpdateTime(cond)
utilruntime.Must(err)
return ok
}
// LastUpdateTime extracts the last update time of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) LastUpdateTime(cond interface{}) (metav1.Time, error) {
v, err := enforceStruct(cond)
if err != nil {
return metav1.Time{}, err
}
var lastUpdateTime metav1.Time
if err := getAndConvertField(v, a.lastUpdateTimeField, &lastUpdateTime); err != nil {
return metav1.Time{}, err
}
return lastUpdateTime, nil
}
// MustLastUpdateTime extracts the last update time of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) MustLastUpdateTime(cond interface{}) metav1.Time {
t, err := a.LastUpdateTime(cond)
utilruntime.Must(err)
return t
}
// SetLastUpdateTime sets the last update time of the given condition.
//
// It errors if the given value is not a pointer to a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) SetLastUpdateTime(condPtr interface{}, lastUpdateTime metav1.Time) error {
v, err := enforcePtrToStruct(condPtr)
if err != nil {
return err
}
return setFieldConverted(v, a.lastUpdateTimeField, lastUpdateTime)
}
// MustSetLastUpdateTime sets the last update time of the given condition.
//
// It errors if the given value is not a pointer to a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) MustSetLastUpdateTime(condPtr interface{}, lastUpdateTime metav1.Time) {
utilruntime.Must(a.SetLastUpdateTime(condPtr, lastUpdateTime))
}
// SetLastUpdateTimeIfExists sets the last update time of the given condition if the field exists.
//
// It errors if the given value is not a pointer to a struct or the field value cannot be converted
// to the given format.
func (a *Accessor) SetLastUpdateTimeIfExists(condPtr interface{}, lastUpdateTime metav1.Time) error {
condV, err := conversion.EnforcePtr(condPtr)
if err != nil {
return err
}
cond := condV.Interface()
if ok, err := a.HasLastUpdateTime(cond); err != nil || !ok {
return err
}
return a.SetLastUpdateTime(condPtr, lastUpdateTime)
}
// MustSetLastUpdateTimeIfExists sets the last update time of the given condition if the field exists.
//
// It panics if the given value is not a pointer to a struct or the field value cannot be converted
// to the given format.
func (a *Accessor) MustSetLastUpdateTimeIfExists(condPtr interface{}, lastUpdateTime metav1.Time) {
utilruntime.Must(a.SetLastUpdateTimeIfExists(condPtr, lastUpdateTime))
}
// HasLastTransitionTime checks if the given condition has a 'LastTransitionTime' field.
//
// It errors if the given value is not a struct.
func (a *Accessor) HasLastTransitionTime(cond interface{}) (bool, error) {
v, err := enforceStruct(cond)
if err != nil {
return false, err
}
return valueHasField(v, a.lastTransitionTimeField), nil
}
// MustHasLastTransitionTime checks if the given condition has a 'LastTransitionTime' field.
//
// It panics if the given value is not a struct.
func (a *Accessor) MustHasLastTransitionTime(cond interface{}) bool {
ok, err := a.HasLastTransitionTime(cond)
utilruntime.Must(err)
return ok
}
// LastTransitionTime extracts the last transition time of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) LastTransitionTime(cond interface{}) (metav1.Time, error) {
v, err := enforceStruct(cond)
if err != nil {
return metav1.Time{}, err
}
var lastTransitionTime metav1.Time
if err := getAndConvertField(v, a.lastTransitionTimeField, &lastTransitionTime); err != nil {
return metav1.Time{}, err
}
return lastTransitionTime, nil
}
// MustLastTransitionTime extracts the last transition time of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) MustLastTransitionTime(cond interface{}) metav1.Time {
t, err := a.LastTransitionTime(cond)
utilruntime.Must(err)
return t
}
// SetLastTransitionTime sets the last transition time of the given condition if the field exists.
//
// It errors if the given value is not a pointer to a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) SetLastTransitionTime(condPtr interface{}, lastTransitionTime metav1.Time) error {
v, err := enforcePtrToStruct(condPtr)
if err != nil {
return err
}
return setFieldConverted(v, a.lastTransitionTimeField, lastTransitionTime)
}
// MustSetLastTransitionTime sets the last transition time of the given condition.
//
// It panics if the given value is not a pointer to a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) MustSetLastTransitionTime(condPtr interface{}, lastTransitionTime metav1.Time) {
utilruntime.Must(a.SetLastTransitionTime(condPtr, lastTransitionTime))
}
// SetLastTransitionTimeIfExists sets the last transition time of the given condition.
//
// It errors if the given value is not a pointer to a struct or the field value cannot be converted
// to the given format.
func (a *Accessor) SetLastTransitionTimeIfExists(condPtr interface{}, lastTransitionTime metav1.Time) error {
condV, err := conversion.EnforcePtr(condPtr)
if err != nil {
return err
}
cond := condV.Interface()
if ok, err := a.HasLastTransitionTime(cond); err != nil || !ok {
return err
}
return a.SetLastTransitionTime(condPtr, lastTransitionTime)
}
// MustSetLastTransitionTimeIfExists sets the last transition time of the given condition.
//
// It panics if the given value is not a pointer to a struct or the field value cannot be converted
// to the given format.
func (a *Accessor) MustSetLastTransitionTimeIfExists(condPtr interface{}, lastTransitionTime metav1.Time) {
utilruntime.Must(a.SetLastTransitionTimeIfExists(condPtr, lastTransitionTime))
}
// Reason extracts the reason of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) Reason(cond interface{}) (string, error) {
v, err := enforceStruct(cond)
if err != nil {
return "", err
}
var reason string
if err := getAndConvertField(v, a.reasonField, &reason); err != nil {
return "", err
}
return reason, nil
}
// MustReason extracts the reason of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the output format.
func (a *Accessor) MustReason(cond interface{}) string {
s, err := a.Reason(cond)
utilruntime.Must(err)
return s
}
// SetReason sets the reason of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) SetReason(condPtr interface{}, reason string) error {
v, err := enforcePtrToStruct(condPtr)
if err != nil {
return err
}
return setFieldConverted(v, a.reasonField, reason)
}
// MustSetReason sets the reason of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) MustSetReason(condPtr interface{}, reason string) {
utilruntime.Must(a.SetReason(condPtr, reason))
}
// Message gets the message of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the input format.
func (a *Accessor) Message(cond interface{}) (string, error) {
v, err := enforceStruct(cond)
if err != nil {
return "", err
}
var message string
if err := getAndConvertField(v, a.messageField, &message); err != nil {
return "", err
}
return message, nil
}
// MustMessage gets the message of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the input format.
func (a *Accessor) MustMessage(cond interface{}) string {
s, err := a.Message(cond)
utilruntime.Must(err)
return s
}
// SetMessage sets the message of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) SetMessage(condPtr interface{}, message string) error {
v, err := enforcePtrToStruct(condPtr)
if err != nil {
return err
}
return setFieldConverted(v, a.messageField, message)
}
// MustSetMessage sets the message of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) MustSetMessage(condPtr interface{}, message string) {
utilruntime.Must(a.SetMessage(condPtr, message))
}
// HasObservedGeneration checks if the given condition has a observed generation field.
//
// It errors if the given value is not a struct.
func (a *Accessor) HasObservedGeneration(cond interface{}) (bool, error) {
v, err := enforceStruct(cond)
if err != nil {
return false, err
}
return valueHasField(v, a.observedGenerationField), nil
}
// MustHasObservedGeneration checks if the given condition has a observed generation field.
//
// It panics if the given value is not a struct.
func (a *Accessor) MustHasObservedGeneration(cond interface{}) bool {
ok, err := a.HasObservedGeneration(cond)
utilruntime.Must(err)
return ok
}
// ObservedGeneration gets the observed generation of the given condition.
//
// It errors if the given value is not a struct or does not have a field
// that can be converted to the input format.
func (a *Accessor) ObservedGeneration(cond interface{}) (int64, error) {
v, err := enforceStruct(cond)
if err != nil {
return 0, err
}
var gen int64
if err := getAndConvertField(v, a.observedGenerationField, &gen); err != nil {
return 0, err
}
return gen, nil
}
// MustObservedGeneration gets the observed generation of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the input format.
func (a *Accessor) MustObservedGeneration(cond interface{}) int64 {
gen, err := a.ObservedGeneration(cond)
utilruntime.Must(err)
return gen
}
// SetObservedGeneration sets the observed generation of the given condition.
//
// It errors if the given value is not a pointer to a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) SetObservedGeneration(condPtr interface{}, gen int64) error {
v, err := enforcePtrToStruct(condPtr)
if err != nil {
return err
}
return setFieldConverted(v, a.observedGenerationField, gen)
}
// MustSetObservedGeneration sets the observed generation of the given condition.
//
// It panics if the given value is not a pointer to a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) MustSetObservedGeneration(condPtr interface{}, gen int64) {
utilruntime.Must(a.SetObservedGeneration(condPtr, gen))
}
// MustSetMessage sets the message of the given condition.
//
// It panics if the given value is not a struct or does not have a field
// that can be converted to the given format.
func (a *Accessor) findTypeIndex(condSliceV reflect.Value, typ string) (int, error) {
for i, n := 0, condSliceV.Len(); i < n; i++ {
it := condSliceV.Index(i)
itType, err := a.Type(it.Interface())
if err != nil {
return -1, fmt.Errorf("[index %d]: %w", i, err)
}
if itType == typ {
return i, nil
}
}
return -1, nil
}
// FindSliceIndex finds the index of the condition with the given type.
//
// If the target type is not found, -1 is returned.
// FindSliceIndex errors if condSlice is not a slice of structs.
func (a *Accessor) FindSliceIndex(condSlice interface{}, typ string) (int, error) {
v, _, err := enforceStructSlice(condSlice)
if err != nil {
return 0, err
}
return a.findTypeIndex(v, typ)
}
// MustFindSliceIndex finds the index of the condition with the given type.
//
// If the target type is not found, -1 is returned.
// MustFindSliceIndex panics if condSlice is not a slice of structs.
func (a *Accessor) MustFindSliceIndex(condSlice interface{}, typ string) int {
idx, err := a.FindSliceIndex(condSlice, typ)
utilruntime.Must(err)
return idx
}
// FindSlice finds the condition with the given type from the given slice and updates the target value with it.
//
// If the target type is not found, false is returned and the target value is not updated.
// FindSlice errors if condSlice is not a slice, intoPtr is not a pointer to a struct and if intoPtr's target
// value is not settable with an element of condSlice.
func (a *Accessor) FindSlice(condSlice interface{}, typ string, intoPtr interface{}) (ok bool, err error) {
v, elemType, err := enforceStructSlice(condSlice)
if err != nil {
return false, err
}
intoV, err := enforcePtrToStruct(intoPtr)
if err != nil {
return false, err
}
if intoV.Type() != elemType {
return false, fmt.Errorf("into type %T cannot accept slice type %T", intoPtr, condSlice)
}
idx, err := a.findTypeIndex(v, typ)
if err != nil {
return false, err
}
if idx == -1 {
return false, nil
}
intoV.Set(v.Index(idx))
return true, nil
}
// MustFindSlice finds the condition with the given type from the given slice and updates the target value with it.
//
// If the target type is not found, false is returned and the target value is not updated.
// FindSlice panics if condSlice is not a slice, intoPtr is not a pointer to a struct and if intoPtr's target
// value is not settable with an element of condSlice.
func (a *Accessor) MustFindSlice(condSlice interface{}, typ string, intoPtr interface{}) bool {
ok, err := a.FindSlice(condSlice, typ, intoPtr)
utilruntime.Must(err)
return ok
}
// FindSliceStatus finds the status of the condition with the given type.
// If the condition cannot be found, corev1.ConditionUnknown is returned.
//
// FindSliceStatus errors if the given condSlice is not a slice of structs or if any
// of the conditions does not support access.
func (a *Accessor) FindSliceStatus(condSlice interface{}, typ string) (corev1.ConditionStatus, error) {
v, _, err := enforceStructSlice(condSlice)
if err != nil {
return "", err
}
idx, err := a.findTypeIndex(v, typ)
if err != nil {
return "", err
}
if idx == -1 {
return corev1.ConditionUnknown, nil
}
condV := v.Index(idx)
return a.Status(condV.Interface())
}
// MustFindSliceStatus finds the status of the condition with the given type.
// If the condition cannot be found, corev1.ConditionUnknown is returned.
//
// MustFindSliceStatus errors if the given condSlice is not a slice of structs or if any
// of the conditions does not support access.
func (a *Accessor) MustFindSliceStatus(condSlice interface{}, typ string) corev1.ConditionStatus {
status, err := a.FindSliceStatus(condSlice, typ)
utilruntime.Must(err)
return status
}
// UpdateOption is an option given to Accessor.UpdateSlice that updates an individual condition.
type UpdateOption interface {
// ApplyUpdate applies the update, given a condition pointer.
ApplyUpdate(a *Accessor, condPtr interface{}) error
}
// Update updates the condition with the given options, setting transition- and update time accordingly.
//
// Update errors if the given condPtr is not a pointer to a struct supporting the required condition fields.
func (a *Accessor) Update(condPtr interface{}, opts ...UpdateOption) error {
if !a.disableTimestampUpdates {
opts = []UpdateOption{
UpdateTimestamps{
Transition: a.transition,
Clock: a.clock,
Updates: opts,
},
}
}
for _, opt := range opts {
if err := opt.ApplyUpdate(a, condPtr); err != nil {
return err
}
}
return nil
}
// MustUpdate updates the condition with the given options, setting transition- and update time accordingly.
//
// MustUpdate panics if the given condPtr is not a pointer to a struct supporting the required condition fields.
func (a *Accessor) MustUpdate(condPtr interface{}, opts ...UpdateOption) {
utilruntime.Must(a.Update(condPtr, opts...))
}
// UpdateSlice finds and updates the condition with the given target type.
//
// UpdateSlice errors if condSlicePtr is not a pointer to a slice of structs that can be accessed with
// this Accessor.
// If no condition with the given type can be found, a new one is appended with the given type and updates
// applied.
// The last update time and last transition time of the new / existing condition is correctly updated:
// For new conditions, it's always set to the current time while for existing conditions, it's checked
// whether the status changed and then updated.
func (a *Accessor) UpdateSlice(condSlicePtr interface{}, typ string, opts ...UpdateOption) error {
sliceV, elemType, err := enforcePtrToStructSlice(condSlicePtr)
if err != nil {
return err
}
idx, err := a.findTypeIndex(sliceV, typ)
if err != nil {
return err
}
var v reflect.Value
if idx != -1 {
v = sliceV.Index(idx).Addr()
} else {
v = reflect.New(elemType)
}
condPtr := v.Interface()
// Ensure both type and initial transition time (if applicable) are set
// for new conditions.
if idx == -1 {
if err := a.SetType(condPtr, typ); err != nil {
return err
}
now := metav1.NewTime(a.clock.Now())
if err := a.SetLastTransitionTimeIfExists(condPtr, now); err != nil {
return err
}
}
if err := a.Update(condPtr, opts...); err != nil {
return err
}
// Make sure to append to the slice in case the condition is new, otherwise
// it was already updated in-place.
if idx == -1 {
sliceV.Set(reflect.Append(sliceV, v.Elem()))
}
return nil
}
// MustUpdateSlice finds and updates the condition with the given target type.
//
// MustUpdateSlice panics if condSlicePtr is not a pointer to a slice of structs that can be accessed with
// this Accessor.
// If no condition with the given type can be found, a new one is appended with the given type and updates
// applied.
// The last update time and last transition time of the new / existing condition is correctly updated:
// For new conditions, it's always set to the current time while for existing conditions, it's checked
// whether the status changed and then updated.
func (a *Accessor) MustUpdateSlice(condSlicePtr interface{}, typ string, opts ...UpdateOption) {
utilruntime.Must(a.UpdateSlice(condSlicePtr, typ, opts...))
}
// UpdateTimestamps manages the LastUpdateTime and LastTransitionTime field by creating a checkpoint with
// Transition, running all Updates and then checking if the TransitionCheckpoint reports transitioned.
// If so, the LastTransitionTimeField and the LastUpdateTimeField will be set to the current time using Clock (if
// Clock is unset, it uses clock.RealClock). Otherwise, only LastUpdateTimeField is updated..
type UpdateTimestamps struct {
// Transition is the Transition to check whether a condition transitioned. Required.
Transition Transition
// Updates are all updates to run.
Updates []UpdateOption
// Clock is the clock to yield the current time. If unset, clock.RealClock is used.
Clock clock.Clock
}
// UpdateTimestampsWith updates timestamps with the DefaultTransition and clock.RealClock. See UpdateTimestamps for
// more information.
func UpdateTimestampsWith(updates ...UpdateOption) UpdateOption {
return UpdateTimestamps{
Transition: DefaultTransition,
Updates: updates,
}
}
// ApplyUpdate implements UpdateOption.
func (u UpdateTimestamps) ApplyUpdate(a *Accessor, condPtr interface{}) error {
condV, err := enforcePtrToStruct(condPtr)
if err != nil {
return err
}
checkpoint, err := u.Transition.Checkpoint(a, condV.Interface())
if err != nil {
return err
}
for _, update := range u.Updates {
if err := update.ApplyUpdate(a, condPtr); err != nil {
return err
}
}
c := u.Clock
if c == nil {
c = clock.RealClock{}
}
now := c.Now()