@@ -12,6 +12,7 @@ import (
12
12
"k8s.io/apimachinery/pkg/watch"
13
13
"net/http"
14
14
"sigs.k8s.io/controller-runtime/pkg/client"
15
+ "sigs.k8s.io/controller-runtime/pkg/client/apiutil"
15
16
"sigs.k8s.io/controller-runtime/pkg/controller"
16
17
"sigs.k8s.io/controller-runtime/pkg/event"
17
18
"sigs.k8s.io/controller-runtime/pkg/handler"
@@ -87,24 +88,33 @@ func (wt *watchesForTemplate) setClient(ctx context.Context, objClient client.Wi
87
88
wt .client = objClient
88
89
}
89
90
90
- func (wt * watchesForTemplate ) addWatchForObject (ctx context.Context , objectRef templatesv1alpha1.ObjectRef ) error {
91
+ func (wt * watchesForTemplate ) addWatchForObject (ctx context.Context , objectRef templatesv1alpha1.ObjectRef ) (templatesv1alpha1. ObjectRef , error ) {
91
92
logger := log .FromContext (ctx )
92
93
94
+ gvk , err := objectRef .GroupVersionKind ()
95
+ if err != nil {
96
+ return objectRef , err
97
+ }
98
+
99
+ // if namespace is not set, default to the template's namespace
100
+ if objectRef .Namespace == "" {
101
+ if isNs , err := apiutil .IsGVKNamespaced (gvk , wt .client .RESTMapper ()); err != nil {
102
+ return objectRef , fmt .Errorf ("failed to determine if object is namespaced: %w" , err )
103
+ } else if isNs {
104
+ objectRef .Namespace = wt .templateKey .Namespace
105
+ }
106
+ }
107
+
93
108
wt .mutex .Lock ()
94
109
defer wt .mutex .Unlock ()
95
110
96
111
w := wt .watches [objectRef ]
97
112
if w != nil {
98
- return nil
113
+ return objectRef , nil
99
114
}
100
115
101
116
logger .V (1 ).Info ("Starting watch for object" , "templateKey" , wt .templateKey , "objectRef" , objectRef )
102
117
103
- gvk , err := objectRef .GroupVersionKind ()
104
- if err != nil {
105
- return err
106
- }
107
-
108
118
// this is a single-object watch that does NOT require global watch permissions!
109
119
var dummy unstructured.UnstructuredList
110
120
dummy .SetGroupVersionKind (gvk )
@@ -120,7 +130,7 @@ func (wt *watchesForTemplate) addWatchForObject(ctx context.Context, objectRef t
120
130
err = fmt .Errorf ("watch for %s \" %s\" is forbidden: %w" , gvk .Kind , objectRef .Name , err )
121
131
}
122
132
}
123
- return err
133
+ return objectRef , err
124
134
}
125
135
wt .watches [objectRef ] = w
126
136
@@ -132,7 +142,7 @@ func (wt *watchesForTemplate) addWatchForObject(ctx context.Context, objectRef t
132
142
}
133
143
}()
134
144
135
- return nil
145
+ return objectRef , nil
136
146
}
137
147
138
148
func (wt * watchesForTemplate ) removeDeletedWatches (ctx context.Context , newRefs map [templatesv1alpha1.ObjectRef ]struct {}) {
0 commit comments