MCPcopy
hub / github.com/apecloud/kubeblocks / ReadObjectTree

Function ReadObjectTree

pkg/controller/kubebuilderx/utils.go:40–84  ·  view source on GitHub ↗

ReadObjectTree reads all objects owned by the root object which is type of 'T' with key in 'req'.

(ctx context.Context, reader client.Reader, req ctrl.Request, ml client.MatchingLabels, kinds ...client.ObjectList)

Source from the content-addressed store, hash-verified

38
39// ReadObjectTree reads all objects owned by the root object which is type of 'T' with key in 'req'.
40func ReadObjectTree[T client.Object](ctx context.Context, reader client.Reader, req ctrl.Request, ml client.MatchingLabels, kinds ...client.ObjectList) (*ObjectTree, error) {
41 tree := NewObjectTree()
42
43 // read root object
44 var obj T
45 t := reflect.TypeOf(obj)
46 if t.Kind() == reflect.Ptr {
47 t = t.Elem()
48 }
49 rootObj := reflect.New(t).Interface()
50 root, _ := rootObj.(T)
51 if err := reader.Get(ctx, req.NamespacedName, root); err != nil {
52 if apierrors.IsNotFound(err) {
53 return tree, nil
54 }
55 return nil, err
56 }
57 tree.SetRoot(root)
58
59 // init placement
60 ctx = intoContext(ctx, placement(root))
61
62 // read child objects
63 inNS := client.InNamespace(req.Namespace)
64 for _, list := range kinds {
65 if err := reader.List(ctx, list, inNS, ml, inDataContext4C()); err != nil {
66 return nil, err
67 }
68 // reflect get list.Items
69 items := reflect.ValueOf(list).Elem().FieldByName("Items")
70 l := items.Len()
71 for i := 0; i < l; i++ {
72 // get the underlying object
73 object := items.Index(i).Addr().Interface().(client.Object)
74 if len(object.GetOwnerReferences()) > 0 && !model.IsOwnerOf(root, object) {
75 continue
76 }
77 if err := tree.Add(object); err != nil {
78 return nil, err
79 }
80 }
81 }
82
83 return tree, nil
84}
85
86func placement(obj client.Object) string {
87 if obj == nil || obj.GetAnnotations() == nil {

Callers 4

LoadMethod · 0.92
LoadMethod · 0.92
LoadMethod · 0.92
utils_test.goFile · 0.85

Calls 11

SetRootMethod · 0.95
AddMethod · 0.95
IsOwnerOfFunction · 0.92
NewObjectTreeFunction · 0.85
intoContextFunction · 0.85
placementFunction · 0.85
inDataContext4CFunction · 0.85
LenMethod · 0.80
KindMethod · 0.65
GetMethod · 0.65
ListMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…