-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdependencyrule_controller.go
More file actions
249 lines (200 loc) · 7.52 KB
/
dependencyrule_controller.go
File metadata and controls
249 lines (200 loc) · 7.52 KB
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
// Copyright 2026 BWI GmbH and Dependency Controller contributors
// SPDX-License-Identifier: Apache-2.0
package controller
import (
"context"
"fmt"
"strings"
"sync"
"github.com/kcp-dev/logicalcluster/v3"
tenancyv1alpha1 "github.com/kcp-dev/sdk/apis/tenancy/v1alpha1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager"
mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile"
v1alpha1 "go.opendefense.cloud/dependency-controller/api/v1alpha1"
)
// DependencyRuleReconciler watches DependencyRule objects across provider workspaces
// via the dep-ctrl's own APIExport. It handles webhook installation in
// dependency provider workspaces. Per-rule indexed caches are managed by the
// webhook server's RuleCacheManager instead.
type DependencyRuleReconciler struct {
// DepCtrlManager is the multicluster manager for the dep-ctrl's APIExport.
DepCtrlManager mcmanager.Manager
// WebhookInstaller installs ValidatingWebhookConfigurations in provider
// workspaces. Nil if webhook installation is not configured.
WebhookInstaller *WebhookInstaller
// BaseConfig is the kcp front-proxy REST config (no workspace path suffix).
// Used for webhook installation (routed to the correct shard per workspace)
// and to resolve workspace paths to logical cluster names.
BaseConfig *rest.Config
// mu protects lazy initialization of wsResolver.
mu sync.Mutex
wsResolver *workspaceResolver
}
func NewDependencyRuleReconciler(depCtrlMgr mcmanager.Manager) *DependencyRuleReconciler {
return &DependencyRuleReconciler{
DepCtrlManager: depCtrlMgr,
}
}
// ensureInitialized lazily creates the workspace resolver used to map
// workspace paths to logical cluster names for webhook installation.
func (r *DependencyRuleReconciler) ensureInitialized() error {
r.mu.Lock()
defer r.mu.Unlock()
if r.wsResolver != nil {
return nil
}
localMgr := r.DepCtrlManager.GetLocalManager()
r.wsResolver = &workspaceResolver{
baseCfg: r.BaseConfig,
scheme: localMgr.GetScheme(),
newClient: client.New,
}
return nil
}
// Reconcile handles DependencyRule events: installs/removes webhooks in
// dependency provider workspaces.
func (r *DependencyRuleReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx).WithValues("rule", req.Name, "cluster", req.ClusterName)
if err := r.ensureInitialized(); err != nil {
logger.Error(err, "failed to initialize workspace resolver")
return ctrl.Result{}, err
}
cl, err := r.DepCtrlManager.GetCluster(ctx, req.ClusterName)
if err != nil {
logger.Error(err, "failed to get cluster")
return ctrl.Result{}, err
}
ruleKey := string(req.ClusterName) + "/" + req.Name
var rule v1alpha1.DependencyRule
if err := cl.GetClient().Get(ctx, client.ObjectKey{Name: req.Name}, &rule); err != nil {
if client.IgnoreNotFound(err) == nil {
logger.Info("DependencyRule deleted")
return ctrl.Result{}, r.handleDeletion(ctx, ruleKey, req.Name)
}
return ctrl.Result{}, err
}
// Resolve workspace paths to logical cluster names for VW access.
wsPaths := r.collectWorkspacePaths(&rule)
if err := r.wsResolver.ensureResolved(ctx, wsPaths); err != nil {
logger.Error(err, "failed to resolve workspace paths")
return ctrl.Result{}, err
}
if r.WebhookInstaller != nil {
if err := r.ensureWebhooks(ctx, ruleKey, &rule); err != nil {
logger.Error(err, "failed to ensure webhooks")
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
// ensureWebhooks installs webhooks in dependency provider workspaces via the virtual workspace.
func (r *DependencyRuleReconciler) ensureWebhooks(ctx context.Context, ruleKey string, rule *v1alpha1.DependencyRule) error {
// Build a mapping from workspace path to logical cluster name.
clusterNames := make(map[string]string, len(rule.Spec.Dependencies))
for _, dep := range rule.Spec.Dependencies {
wsPath := dep.APIExportRef.Path
if _, ok := clusterNames[wsPath]; ok {
continue
}
clusterName, err := r.wsResolver.resolve(wsPath)
if err != nil {
return fmt.Errorf("resolving %s: %w", wsPath, err)
}
clusterNames[wsPath] = clusterName
}
return r.WebhookInstaller.EnsureWebhooks(ctx, ruleKey, rule, clusterNames)
}
// collectWorkspacePaths extracts dependency workspace paths referenced in a DependencyRule.
func (r *DependencyRuleReconciler) collectWorkspacePaths(rule *v1alpha1.DependencyRule) []string {
seen := make(map[string]struct{})
var paths []string
for _, dep := range rule.Spec.Dependencies {
if _, ok := seen[dep.APIExportRef.Path]; !ok {
seen[dep.APIExportRef.Path] = struct{}{}
paths = append(paths, dep.APIExportRef.Path)
}
}
return paths
}
// handleDeletion cleans up webhooks for a deleted DependencyRule.
func (r *DependencyRuleReconciler) handleDeletion(ctx context.Context, key, ruleName string) error {
if r.WebhookInstaller != nil {
if err := r.WebhookInstaller.RemoveWebhooks(ctx, key); err != nil {
return fmt.Errorf("removing webhooks for rule %s: %w", ruleName, err)
}
}
return nil
}
// workspaceResolver maps kcp workspace paths (e.g., "root:compute-provider")
// to logical cluster names by reading Workspace objects from the root workspace.
type workspaceResolver struct {
baseCfg *rest.Config // kcp front-proxy URL without any workspace path suffix
scheme *runtime.Scheme
newClient func(cfg *rest.Config, options client.Options) (client.Client, error)
mu sync.Mutex
cache map[string]string // workspace path -> logical cluster name
}
// ensureResolved ensures all the given workspace paths are resolved to logical
// cluster names, fetching any missing mappings from the root workspace.
func (w *workspaceResolver) ensureResolved(ctx context.Context, paths []string) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.cache == nil {
w.cache = make(map[string]string)
}
var missing []string
for _, path := range paths {
if _, ok := w.cache[path]; !ok {
missing = append(missing, path)
}
}
if len(missing) == 0 {
return nil
}
for _, path := range missing {
if _, ok := w.cache[path]; ok {
continue
}
var parentPath string
if i := strings.LastIndex(path, ":"); i >= 0 {
parentPath = path[:i]
} else {
return fmt.Errorf("workspace path %q must have at least one parent segment", path)
}
parentCfg := rest.CopyConfig(w.baseCfg)
parentCfg.Host += logicalcluster.NewPath(parentPath).RequestPath()
c, err := w.newClient(parentCfg, client.Options{Scheme: w.scheme})
if err != nil {
return fmt.Errorf("creating %s workspace client: %w", parentPath, err)
}
var wsList tenancyv1alpha1.WorkspaceList
if err := c.List(ctx, &wsList); err != nil {
return fmt.Errorf("list workspaces in %s: %w", parentPath, err)
}
for _, ws := range wsList.Items {
if ws.Spec.Cluster == "" {
log.FromContext(ctx).Info("skipping workspace with no logical cluster name (still provisioning?)", "workspace", ws.Name, "parent", parentPath)
continue
}
wsPath := parentPath + ":" + ws.Name
w.cache[wsPath] = ws.Spec.Cluster
log.FromContext(ctx).Info("resolved workspace path", "path", wsPath, "cluster", ws.Spec.Cluster)
}
}
return nil
}
// resolve returns the logical cluster name for a workspace path.
func (w *workspaceResolver) resolve(path string) (string, error) {
w.mu.Lock()
defer w.mu.Unlock()
name, ok := w.cache[path]
if !ok {
return "", fmt.Errorf("workspace path %s not resolved", path)
}
return name, nil
}