@@ -17,11 +17,13 @@ limitations under the License.
17
17
package fake
18
18
19
19
import (
20
+ "bytes"
20
21
"context"
21
22
"encoding/json"
22
23
"errors"
23
24
"fmt"
24
25
"reflect"
26
+ "runtime/debug"
25
27
"strconv"
26
28
"strings"
27
29
"sync"
@@ -35,6 +37,7 @@ import (
35
37
"k8s.io/apimachinery/pkg/runtime"
36
38
"k8s.io/apimachinery/pkg/runtime/schema"
37
39
utilrand "k8s.io/apimachinery/pkg/util/rand"
40
+ "k8s.io/apimachinery/pkg/util/sets"
38
41
"k8s.io/apimachinery/pkg/util/validation/field"
39
42
"k8s.io/apimachinery/pkg/watch"
40
43
"k8s.io/client-go/kubernetes/scheme"
@@ -48,13 +51,15 @@ import (
48
51
49
52
type versionedTracker struct {
50
53
testing.ObjectTracker
51
- scheme * runtime.Scheme
54
+ scheme * runtime.Scheme
55
+ withStatusSubresource sets.Set [schema.GroupVersionKind ]
52
56
}
53
57
54
58
type fakeClient struct {
55
- tracker versionedTracker
56
- scheme * runtime.Scheme
57
- restMapper meta.RESTMapper
59
+ tracker versionedTracker
60
+ scheme * runtime.Scheme
61
+ restMapper meta.RESTMapper
62
+ withStatusSubresource sets.Set [schema.GroupVersionKind ]
58
63
59
64
// indexes maps each GroupVersionKind (GVK) to the indexes registered for that GVK.
60
65
// The inner map maps from index name to IndexerFunc.
@@ -95,12 +100,13 @@ func NewClientBuilder() *ClientBuilder {
95
100
96
101
// ClientBuilder builds a fake client.
97
102
type ClientBuilder struct {
98
- scheme * runtime.Scheme
99
- restMapper meta.RESTMapper
100
- initObject []client.Object
101
- initLists []client.ObjectList
102
- initRuntimeObjects []runtime.Object
103
- objectTracker testing.ObjectTracker
103
+ scheme * runtime.Scheme
104
+ restMapper meta.RESTMapper
105
+ initObject []client.Object
106
+ initLists []client.ObjectList
107
+ initRuntimeObjects []runtime.Object
108
+ withStatusSubresource []client.Object
109
+ objectTracker testing.ObjectTracker
104
110
105
111
// indexes maps each GroupVersionKind (GVK) to the indexes registered for that GVK.
106
112
// The inner map maps from index name to IndexerFunc.
@@ -185,6 +191,13 @@ func (f *ClientBuilder) WithIndex(obj runtime.Object, field string, extractValue
185
191
return f
186
192
}
187
193
194
+ // WithStatusSubresource configures the passed object with a status subresource, which means
195
+ // calls to Update and Patch will not alters its status.
196
+ func (f * ClientBuilder ) WithStatusSubresource (o ... client.Object ) * ClientBuilder {
197
+ f .withStatusSubresource = append (f .withStatusSubresource , o ... )
198
+ return f
199
+ }
200
+
188
201
// Build builds and returns a new fake client.
189
202
func (f * ClientBuilder ) Build () client.WithWatch {
190
203
if f .scheme == nil {
@@ -196,10 +209,19 @@ func (f *ClientBuilder) Build() client.WithWatch {
196
209
197
210
var tracker versionedTracker
198
211
212
+ withStatusSubResource := sets .New (inTreeResourcesWithStatus ()... )
213
+ for _ , o := range f .withStatusSubresource {
214
+ gvk , err := apiutil .GVKForObject (o , f .scheme )
215
+ if err != nil {
216
+ panic (fmt .Errorf ("failed to get gvk for object %T: %w" , withStatusSubResource , err ))
217
+ }
218
+ withStatusSubResource .Insert (gvk )
219
+ }
220
+
199
221
if f .objectTracker == nil {
200
- tracker = versionedTracker {ObjectTracker : testing .NewObjectTracker (f .scheme , scheme .Codecs .UniversalDecoder ()), scheme : f .scheme }
222
+ tracker = versionedTracker {ObjectTracker : testing .NewObjectTracker (f .scheme , scheme .Codecs .UniversalDecoder ()), scheme : f .scheme , withStatusSubresource : withStatusSubResource }
201
223
} else {
202
- tracker = versionedTracker {ObjectTracker : f .objectTracker , scheme : f .scheme }
224
+ tracker = versionedTracker {ObjectTracker : f .objectTracker , scheme : f .scheme , withStatusSubresource : withStatusSubResource }
203
225
}
204
226
205
227
for _ , obj := range f .initObject {
@@ -217,11 +239,13 @@ func (f *ClientBuilder) Build() client.WithWatch {
217
239
panic (fmt .Errorf ("failed to add runtime object %v to fake client: %w" , obj , err ))
218
240
}
219
241
}
242
+
220
243
return & fakeClient {
221
- tracker : tracker ,
222
- scheme : f .scheme ,
223
- restMapper : f .restMapper ,
224
- indexes : f .indexes ,
244
+ tracker : tracker ,
245
+ scheme : f .scheme ,
246
+ restMapper : f .restMapper ,
247
+ indexes : f .indexes ,
248
+ withStatusSubresource : withStatusSubResource ,
225
249
}
226
250
}
227
251
@@ -318,6 +342,16 @@ func convertFromUnstructuredIfNecessary(s *runtime.Scheme, o runtime.Object) (ru
318
342
}
319
343
320
344
func (t versionedTracker ) Update (gvr schema.GroupVersionResource , obj runtime.Object , ns string ) error {
345
+ isSubResource := false
346
+ // We apply patches using a client-go reaction that ends up calling the trackers Update. As we can't change
347
+ // that reaction, we use the callstack to figure out if this originated from the status client.
348
+ if bytes .Contains (debug .Stack (), []byte ("sigs.k8s.io/controller-runtime/pkg/client/fake.(*fakeSubResourceClient).Patch" )) {
349
+ isSubResource = true
350
+ }
351
+ return t .update (gvr , obj , ns , isSubResource )
352
+ }
353
+
354
+ func (t versionedTracker ) update (gvr schema.GroupVersionResource , obj runtime.Object , ns string , isStatus bool ) error {
321
355
accessor , err := meta .Accessor (obj )
322
356
if err != nil {
323
357
return fmt .Errorf ("failed to get accessor for object: %w" , err )
@@ -348,6 +382,19 @@ func (t versionedTracker) Update(gvr schema.GroupVersionResource, obj runtime.Ob
348
382
return err
349
383
}
350
384
385
+ if t .withStatusSubresource .Has (gvk ) {
386
+ if isStatus { // copy everything but status and metadata.ResourceVersion from original object
387
+ if err := copyNonStatusFrom (oldObject , obj ); err != nil {
388
+ return fmt .Errorf ("failed to copy non-status field for object with status subresouce: %w" , err )
389
+ }
390
+
391
+ } else { // copy status from original object
392
+ if err := copyStatusFrom (oldObject , obj ); err != nil {
393
+ return fmt .Errorf ("failed to copy the status for object with status subresource: %w" , err )
394
+ }
395
+ }
396
+ }
397
+
351
398
oldAccessor , err := meta .Accessor (oldObject )
352
399
if err != nil {
353
400
return err
@@ -689,6 +736,10 @@ func (c *fakeClient) DeleteAllOf(ctx context.Context, obj client.Object, opts ..
689
736
}
690
737
691
738
func (c * fakeClient ) Update (ctx context.Context , obj client.Object , opts ... client.UpdateOption ) error {
739
+ return c .update (obj , false , opts ... )
740
+ }
741
+
742
+ func (c * fakeClient ) update (obj client.Object , isStatus bool , opts ... client.UpdateOption ) error {
692
743
updateOptions := & client.UpdateOptions {}
693
744
updateOptions .ApplyOptions (opts )
694
745
@@ -706,10 +757,14 @@ func (c *fakeClient) Update(ctx context.Context, obj client.Object, opts ...clie
706
757
if err != nil {
707
758
return err
708
759
}
709
- return c .tracker .Update (gvr , obj , accessor .GetNamespace ())
760
+ return c .tracker .update (gvr , obj , accessor .GetNamespace (), isStatus )
710
761
}
711
762
712
763
func (c * fakeClient ) Patch (ctx context.Context , obj client.Object , patch client.Patch , opts ... client.PatchOption ) error {
764
+ return c .patch (obj , patch , opts ... )
765
+ }
766
+
767
+ func (c * fakeClient ) patch (obj client.Object , patch client.Patch , opts ... client.PatchOption ) error {
713
768
patchOptions := & client.PatchOptions {}
714
769
patchOptions .ApplyOptions (opts )
715
770
@@ -732,6 +787,11 @@ func (c *fakeClient) Patch(ctx context.Context, obj client.Object, patch client.
732
787
return err
733
788
}
734
789
790
+ gvk , err := apiutil .GVKForObject (obj , c .scheme )
791
+ if err != nil {
792
+ return err
793
+ }
794
+
735
795
reaction := testing .ObjectReaction (c .tracker )
736
796
handled , o , err := reaction (testing .NewPatchAction (gvr , accessor .GetNamespace (), accessor .GetName (), patch .Type (), data ))
737
797
if err != nil {
@@ -740,11 +800,6 @@ func (c *fakeClient) Patch(ctx context.Context, obj client.Object, patch client.
740
800
if ! handled {
741
801
panic ("tracker could not handle patch method" )
742
802
}
743
-
744
- gvk , err := apiutil .GVKForObject (obj , c .scheme )
745
- if err != nil {
746
- return err
747
- }
748
803
ta , err := meta .TypeAccessor (o )
749
804
if err != nil {
750
805
return err
@@ -762,6 +817,97 @@ func (c *fakeClient) Patch(ctx context.Context, obj client.Object, patch client.
762
817
return err
763
818
}
764
819
820
+ func copyNonStatusFrom (old , new runtime.Object ) error {
821
+ newClientObject , ok := new .(client.Object )
822
+ if ! ok {
823
+ return fmt .Errorf ("%T is not a client.Object" , new )
824
+ }
825
+ // The only thing other than status we have to retain
826
+ rv := newClientObject .GetResourceVersion ()
827
+
828
+ oldMapStringAny , err := toMapStringAny (old )
829
+ if err != nil {
830
+ return fmt .Errorf ("failed to convert old to *unstructured.Unstructured: %w" , err )
831
+ }
832
+ newMapStringAny , err := toMapStringAny (new )
833
+ if err != nil {
834
+ return fmt .Errorf ("failed to convert new to *unststructured.Unstructured: %w" , err )
835
+ }
836
+
837
+ // delete everything other than status in case it has fields that were not present in
838
+ // the old object
839
+ for k := range newMapStringAny {
840
+ if k != "status" {
841
+ delete (newMapStringAny , k )
842
+ }
843
+ }
844
+ // copy everything other than status from the old object
845
+ for k := range oldMapStringAny {
846
+ if k != "status" {
847
+ newMapStringAny [k ] = oldMapStringAny [k ]
848
+ }
849
+ }
850
+
851
+ newClientObject .SetResourceVersion (rv )
852
+
853
+ if err := fromMapStringAny (newMapStringAny , new ); err != nil {
854
+ return fmt .Errorf ("failed to convert back from map[string]any: %w" , err )
855
+ }
856
+ return nil
857
+ }
858
+
859
+ // copyStatusFrom copies the status from old into new
860
+ func copyStatusFrom (old , new runtime.Object ) error {
861
+ oldMapStringAny , err := toMapStringAny (old )
862
+ if err != nil {
863
+ return fmt .Errorf ("failed to convert old to *unstructured.Unstructured: %w" , err )
864
+ }
865
+ newMapStringAny , err := toMapStringAny (new )
866
+ if err != nil {
867
+ return fmt .Errorf ("failed to convert new to *unststructured.Unstructured: %w" , err )
868
+ }
869
+
870
+ newMapStringAny ["status" ] = oldMapStringAny ["status" ]
871
+
872
+ if err := fromMapStringAny (newMapStringAny , new ); err != nil {
873
+ return fmt .Errorf ("failed to convert back from map[string]any: %w" , err )
874
+ }
875
+
876
+ return nil
877
+ }
878
+
879
+ func toMapStringAny (obj runtime.Object ) (map [string ]any , error ) {
880
+ if unstructured , isUnstructured := obj .(* unstructured.Unstructured ); isUnstructured {
881
+ return unstructured .Object , nil
882
+ }
883
+
884
+ serialized , err := json .Marshal (obj )
885
+ if err != nil {
886
+ return nil , err
887
+ }
888
+
889
+ u := map [string ]any {}
890
+ return u , json .Unmarshal (serialized , & u )
891
+ }
892
+
893
+ func fromMapStringAny (u map [string ]any , target runtime.Object ) error {
894
+ if targetUnstructured , isUnstructured := target .(* unstructured.Unstructured ); isUnstructured {
895
+ targetUnstructured .Object = u
896
+ return nil
897
+ }
898
+
899
+ serialized , err := json .Marshal (u )
900
+ if err != nil {
901
+ return fmt .Errorf ("failed to serialize: %w" , err )
902
+ }
903
+
904
+ if err := json .Unmarshal (serialized , & target ); err != nil {
905
+ return fmt .Errorf ("failed to deserialize: %w" , err )
906
+ }
907
+
908
+ return nil
909
+ }
910
+
765
911
func (c * fakeClient ) Status () client.SubResourceWriter {
766
912
return c .SubResource ("status" )
767
913
}
@@ -809,22 +955,17 @@ func (sw *fakeSubResourceClient) Create(ctx context.Context, obj client.Object,
809
955
}
810
956
811
957
func (sw * fakeSubResourceClient ) Update (ctx context.Context , obj client.Object , opts ... client.SubResourceUpdateOption ) error {
812
- // TODO(droot): This results in full update of the obj (spec + subresources). Need
813
- // a way to update subresource only.
814
958
updateOptions := client.SubResourceUpdateOptions {}
815
959
updateOptions .ApplyOptions (opts )
816
960
817
961
body := obj
818
962
if updateOptions .SubResourceBody != nil {
819
963
body = updateOptions .SubResourceBody
820
964
}
821
- return sw .client .Update ( ctx , body , & updateOptions .UpdateOptions )
965
+ return sw .client .update ( body , true , & updateOptions .UpdateOptions )
822
966
}
823
967
824
968
func (sw * fakeSubResourceClient ) Patch (ctx context.Context , obj client.Object , patch client.Patch , opts ... client.SubResourcePatchOption ) error {
825
- // TODO(droot): This results in full update of the obj (spec + subresources). Need
826
- // a way to update subresource only.
827
-
828
969
patchOptions := client.SubResourcePatchOptions {}
829
970
patchOptions .ApplyOptions (opts )
830
971
@@ -833,7 +974,7 @@ func (sw *fakeSubResourceClient) Patch(ctx context.Context, obj client.Object, p
833
974
body = patchOptions .SubResourceBody
834
975
}
835
976
836
- return sw .client .Patch ( ctx , body , patch , & patchOptions .PatchOptions )
977
+ return sw .client .patch ( body , patch , & patchOptions .PatchOptions )
837
978
}
838
979
839
980
func allowsUnconditionalUpdate (gvk schema.GroupVersionKind ) bool {
@@ -933,6 +1074,42 @@ func allowsCreateOnUpdate(gvk schema.GroupVersionKind) bool {
933
1074
return false
934
1075
}
935
1076
1077
+ func inTreeResourcesWithStatus () []schema.GroupVersionKind {
1078
+ return []schema.GroupVersionKind {
1079
+ {Version : "v1" , Kind : "Namespace" },
1080
+ {Version : "v1" , Kind : "Node" },
1081
+ {Version : "v1" , Kind : "PersistentVolumeClaim" },
1082
+ {Version : "v1" , Kind : "PersistentVolume" },
1083
+ {Version : "v1" , Kind : "Pod" },
1084
+ {Version : "v1" , Kind : "ReplicationController" },
1085
+ {Version : "v1" , Kind : "Service" },
1086
+
1087
+ {Group : "apps" , Version : "v1" , Kind : "Deployment" },
1088
+ {Group : "apps" , Version : "v1" , Kind : "DaemonSet" },
1089
+ {Group : "apps" , Version : "v1" , Kind : "ReplicaSet" },
1090
+ {Group : "apps" , Version : "v1" , Kind : "StatefulSet" },
1091
+
1092
+ {Group : "autoscaling" , Version : "v1" , Kind : "HorizontalPodAutoscaler" },
1093
+
1094
+ {Group : "batch" , Version : "v1" , Kind : "CronJob" },
1095
+ {Group : "batch" , Version : "v1" , Kind : "Job" },
1096
+
1097
+ {Group : "certificates.k8s.io" , Version : "v1" , Kind : "CertificateSigningRequest" },
1098
+
1099
+ {Group : "networking.k8s.io" , Version : "v1" , Kind : "Ingress" },
1100
+ {Group : "networking.k8s.io" , Version : "v1" , Kind : "NetworkPolicy" },
1101
+
1102
+ {Group : "policy" , Version : "v1" , Kind : "PodDisruptionBudget" },
1103
+
1104
+ {Group : "storage.k8s.io" , Version : "v1" , Kind : "VolumeAttachment" },
1105
+
1106
+ {Group : "apiextensions.k8s.io" , Version : "v1" , Kind : "CustomResourceDefinition" },
1107
+
1108
+ {Group : "flowcontrol.apiserver.k8s.io" , Version : "v1beta2" , Kind : "FlowSchema" },
1109
+ {Group : "flowcontrol.apiserver.k8s.io" , Version : "v1beta2" , Kind : "PriorityLevelConfiguration" },
1110
+ }
1111
+ }
1112
+
936
1113
// zero zeros the value of a pointer.
937
1114
func zero (x interface {}) {
938
1115
if x == nil {
0 commit comments