|
| 1 | +/* |
| 2 | +Copyright 2026 The Kube Bind Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +// Package apibindingtemplate contains a kcp-specific controller that watches |
| 18 | +// APIBindings in provider/backend workspaces and automatically creates or |
| 19 | +// updates APIServiceExportTemplates based on the APIResourceSchemas exposed by |
| 20 | +// each bound APIExport. |
| 21 | +package apibindingtemplate |
| 22 | + |
| 23 | +import ( |
| 24 | + "context" |
| 25 | + "fmt" |
| 26 | + "net/url" |
| 27 | + "strings" |
| 28 | + |
| 29 | + apisv1alpha1 "github.com/kcp-dev/sdk/apis/apis/v1alpha1" |
| 30 | + apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2" |
| 31 | + "k8s.io/apimachinery/pkg/api/errors" |
| 32 | + "k8s.io/apimachinery/pkg/runtime" |
| 33 | + "k8s.io/apimachinery/pkg/types" |
| 34 | + "k8s.io/client-go/rest" |
| 35 | + ctrl "sigs.k8s.io/controller-runtime" |
| 36 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 37 | + "sigs.k8s.io/controller-runtime/pkg/cluster" |
| 38 | + "sigs.k8s.io/controller-runtime/pkg/controller" |
| 39 | + "sigs.k8s.io/controller-runtime/pkg/handler" |
| 40 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 41 | + "sigs.k8s.io/controller-runtime/pkg/reconcile" |
| 42 | + mcbuilder "sigs.k8s.io/multicluster-runtime/pkg/builder" |
| 43 | + mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" |
| 44 | + mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" |
| 45 | + |
| 46 | + kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" |
| 47 | +) |
| 48 | + |
| 49 | +const controllerName = "kube-bind-kcp-apibinding-template" |
| 50 | + |
| 51 | +// APIBindingTemplateReconciler watches APIBindings and ensures an |
| 52 | +// APIServiceExportTemplate exists for every bound APIExport. |
| 53 | +type APIBindingTemplateReconciler struct { |
| 54 | + manager mcmanager.Manager |
| 55 | + opts controller.TypedOptions[mcreconcile.Request] |
| 56 | + ignorePrefixes []string |
| 57 | + |
| 58 | + // baseConfig is the kcp admin/root REST config used to construct |
| 59 | + // VW clients for the apiresourceschema virtual workspace. |
| 60 | + baseConfig *rest.Config |
| 61 | + scheme *runtime.Scheme |
| 62 | +} |
| 63 | + |
| 64 | +// New returns a new APIBindingTemplateReconciler. |
| 65 | +func New( |
| 66 | + ctx context.Context, |
| 67 | + mgr mcmanager.Manager, |
| 68 | + opts controller.TypedOptions[mcreconcile.Request], |
| 69 | + ignorePrefixes []string, |
| 70 | + baseConfig *rest.Config, |
| 71 | + scheme *runtime.Scheme, |
| 72 | +) (*APIBindingTemplateReconciler, error) { |
| 73 | + r := &APIBindingTemplateReconciler{ |
| 74 | + manager: mgr, |
| 75 | + opts: opts, |
| 76 | + ignorePrefixes: ignorePrefixes, |
| 77 | + baseConfig: baseConfig, |
| 78 | + scheme: scheme, |
| 79 | + } |
| 80 | + |
| 81 | + return r, nil |
| 82 | +} |
| 83 | + |
| 84 | +// shouldIgnore returns true if the APIBinding name matches any of the |
| 85 | +// configured ignore prefixes. |
| 86 | +func (r *APIBindingTemplateReconciler) shouldIgnore(name string) bool { |
| 87 | + for _, prefix := range r.ignorePrefixes { |
| 88 | + if strings.HasPrefix(name, prefix) { |
| 89 | + return true |
| 90 | + } |
| 91 | + } |
| 92 | + return false |
| 93 | +} |
| 94 | + |
| 95 | +// extractClusterID extracts the cluster ID from an apiexport virtual workspace |
| 96 | +// URL. The URL format is: |
| 97 | +// https://host:port/services/apiexport/root:org:ws/<apiexport-name>/clusters/{cluster-id} |
| 98 | +func extractClusterID(clusterConfig *rest.Config) (string, error) { |
| 99 | + u, err := url.Parse(clusterConfig.Host) |
| 100 | + if err != nil { |
| 101 | + return "", fmt.Errorf("failed to parse cluster host URL: %w", err) |
| 102 | + } |
| 103 | + |
| 104 | + pathParts := strings.Split(strings.Trim(u.Path, "/"), "/") |
| 105 | + if len(pathParts) < 6 || pathParts[4] != "clusters" { |
| 106 | + return "", fmt.Errorf("unexpected apiexport URL format: %s", u.Path) |
| 107 | + } |
| 108 | + |
| 109 | + return pathParts[5], nil |
| 110 | +} |
| 111 | + |
| 112 | +// newVWClient creates a client pointing at the apiresourceschema virtual workspace |
| 113 | +// for the given cluster ID: |
| 114 | +// https://host:port/services/apiresourceschema/{clusterID}/clusters/*/ |
| 115 | +func (r *APIBindingTemplateReconciler) newVWClient(clusterID string) (client.Client, error) { |
| 116 | + cfg := rest.CopyConfig(r.baseConfig) |
| 117 | + u, err := url.Parse(cfg.Host) |
| 118 | + if err != nil { |
| 119 | + return nil, fmt.Errorf("failed to parse base config host: %w", err) |
| 120 | + } |
| 121 | + |
| 122 | + u.Path = fmt.Sprintf("/services/apiresourceschema/%s/clusters/*", clusterID) |
| 123 | + cfg.Host = u.String() |
| 124 | + |
| 125 | + return client.New(cfg, client.Options{Scheme: r.scheme}) |
| 126 | +} |
| 127 | + |
| 128 | +// Reconcile implements reconcile.Reconciler for multicluster-runtime. |
| 129 | +func (r *APIBindingTemplateReconciler) Reconcile(ctx context.Context, req mcreconcile.Request) (ctrl.Result, error) { |
| 130 | + logger := log.FromContext(ctx) |
| 131 | + |
| 132 | + if r.shouldIgnore(req.Name) { |
| 133 | + logger.V(4).Info("Ignoring APIBinding matching ignore prefix", "name", req.Name) |
| 134 | + return ctrl.Result{}, nil |
| 135 | + } |
| 136 | + |
| 137 | + logger.Info("Reconciling APIBinding", "request", req) |
| 138 | + |
| 139 | + cl, err := r.manager.GetCluster(ctx, req.ClusterName) |
| 140 | + if err != nil { |
| 141 | + return ctrl.Result{}, fmt.Errorf("failed to get client for cluster %q: %w", req.ClusterName, err) |
| 142 | + } |
| 143 | + |
| 144 | + c := cl.GetClient() |
| 145 | + clusterConfig := cl.GetConfig() |
| 146 | + |
| 147 | + binding := &apisv1alpha2.APIBinding{} |
| 148 | + if err := c.Get(ctx, req.NamespacedName, binding); err != nil { |
| 149 | + if errors.IsNotFound(err) { |
| 150 | + return ctrl.Result{}, nil |
| 151 | + } |
| 152 | + return ctrl.Result{}, fmt.Errorf("failed to get APIBinding %q: %w", req.Name, err) |
| 153 | + } |
| 154 | + |
| 155 | + // Build the schema getter with VW fallback. |
| 156 | + getSchema := r.schemaGetterWithFallback(c, clusterConfig) |
| 157 | + |
| 158 | + rec := reconciler{ |
| 159 | + client: c, |
| 160 | + scheme: r.scheme, |
| 161 | + getAPIResourceSchema: getSchema, |
| 162 | + } |
| 163 | + |
| 164 | + if err := rec.reconcile(ctx, binding); err != nil { |
| 165 | + logger.Error(err, "Failed to reconcile APIBinding", "name", req.Name) |
| 166 | + return ctrl.Result{}, err |
| 167 | + } |
| 168 | + |
| 169 | + return ctrl.Result{}, nil |
| 170 | +} |
| 171 | + |
| 172 | +// schemaGetterWithFallback returns a function that first tries to get the |
| 173 | +// APIResourceSchema from the current workspace, and if not found, falls back |
| 174 | +// to the apiresourceschema virtual workspace. |
| 175 | +func (r *APIBindingTemplateReconciler) schemaGetterWithFallback( |
| 176 | + workspaceClient client.Client, |
| 177 | + clusterConfig *rest.Config, |
| 178 | +) func(ctx context.Context, name string) (*apisv1alpha1.APIResourceSchema, error) { |
| 179 | + return func(ctx context.Context, name string) (*apisv1alpha1.APIResourceSchema, error) { |
| 180 | + logger := log.FromContext(ctx) |
| 181 | + |
| 182 | + // 1. Try the current workspace first. |
| 183 | + var schema apisv1alpha1.APIResourceSchema |
| 184 | + err := workspaceClient.Get(ctx, client.ObjectKey{Name: name}, &schema) |
| 185 | + if err == nil { |
| 186 | + return &schema, nil |
| 187 | + } |
| 188 | + if !errors.IsNotFound(err) { |
| 189 | + return nil, err |
| 190 | + } |
| 191 | + |
| 192 | + // 2. Fallback: try the apiresourceschema virtual workspace. |
| 193 | + logger.V(2).Info("APIResourceSchema not found in workspace, trying VW fallback", "schema", name) |
| 194 | + |
| 195 | + clusterID, err := extractClusterID(clusterConfig) |
| 196 | + if err != nil { |
| 197 | + return nil, fmt.Errorf("cannot build VW fallback client: %w", err) |
| 198 | + } |
| 199 | + |
| 200 | + vwClient, err := r.newVWClient(clusterID) |
| 201 | + if err != nil { |
| 202 | + return nil, fmt.Errorf("failed to create VW client for cluster %q: %w", clusterID, err) |
| 203 | + } |
| 204 | + |
| 205 | + var vwSchema apisv1alpha1.APIResourceSchema |
| 206 | + if err := vwClient.Get(ctx, client.ObjectKey{Name: name}, &vwSchema); err != nil { |
| 207 | + return nil, fmt.Errorf("APIResourceSchema %q not found in workspace or VW: %w", name, err) |
| 208 | + } |
| 209 | + |
| 210 | + return &vwSchema, nil |
| 211 | + } |
| 212 | +} |
| 213 | + |
| 214 | +// getTemplateMapper returns a mapper that enqueues the owning APIBinding when |
| 215 | +// an APIServiceExportTemplate changes. |
| 216 | +func getTemplateMapper(clusterName string, cl cluster.Cluster) handler.TypedEventHandler[client.Object, mcreconcile.Request] { |
| 217 | + return handler.TypedEnqueueRequestsFromMapFunc(func(ctx context.Context, obj client.Object) []mcreconcile.Request { |
| 218 | + annotations := obj.GetAnnotations() |
| 219 | + if annotations == nil { |
| 220 | + return nil |
| 221 | + } |
| 222 | + ownerName, ok := annotations[annotationOwnerBinding] |
| 223 | + if !ok { |
| 224 | + return nil |
| 225 | + } |
| 226 | + |
| 227 | + c := cl.GetClient() |
| 228 | + var binding apisv1alpha2.APIBinding |
| 229 | + if err := c.Get(ctx, client.ObjectKey{Name: ownerName}, &binding); err != nil { |
| 230 | + return nil |
| 231 | + } |
| 232 | + |
| 233 | + return []mcreconcile.Request{ |
| 234 | + { |
| 235 | + Request: reconcile.Request{ |
| 236 | + NamespacedName: types.NamespacedName{Name: ownerName}, |
| 237 | + }, |
| 238 | + ClusterName: clusterName, |
| 239 | + }, |
| 240 | + } |
| 241 | + }) |
| 242 | +} |
| 243 | + |
| 244 | +// SetupWithManager registers the controller with the multicluster-runtime Manager. |
| 245 | +func (r *APIBindingTemplateReconciler) SetupWithManager(mgr mcmanager.Manager) error { |
| 246 | + return mcbuilder.ControllerManagedBy(mgr). |
| 247 | + For(&apisv1alpha2.APIBinding{}). |
| 248 | + Watches( |
| 249 | + &kubebindv1alpha2.APIServiceExportTemplate{}, |
| 250 | + getTemplateMapper, |
| 251 | + ). |
| 252 | + WithOptions(r.opts). |
| 253 | + Named(controllerName). |
| 254 | + Complete(r) |
| 255 | +} |
0 commit comments