-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathplugin_controller.go
More file actions
357 lines (317 loc) · 14.4 KB
/
plugin_controller.go
File metadata and controls
357 lines (317 loc) · 14.4 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Greenhouse contributors
// SPDX-License-Identifier: Apache-2.0
package plugin
import (
"context"
"errors"
"fmt"
"maps"
"strings"
"helm.sh/helm/v3/pkg/release"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
"k8s.io/cli-runtime/pkg/genericclioptions"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
greenhouseapis "github.com/cloudoperators/greenhouse/api"
greenhousev1alpha1 "github.com/cloudoperators/greenhouse/api/v1alpha1"
"github.com/cloudoperators/greenhouse/internal/clientutil"
"github.com/cloudoperators/greenhouse/internal/common"
"github.com/cloudoperators/greenhouse/internal/helm"
"github.com/cloudoperators/greenhouse/internal/util"
"github.com/cloudoperators/greenhouse/pkg/lifecycle"
)
// PluginReconciler reconciles a Plugin object.
type PluginReconciler struct {
client.Client
KubeRuntimeOpts clientutil.RuntimeOptions
kubeClientOpts []clientutil.KubeClientOption
ExpressionEvaluationEnabled bool
IntegrationEnabled bool
OCIMirroringEnabled bool
}
//+kubebuilder:rbac:groups=greenhouse.sap,resources=plugindefinitions,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=greenhouse.sap,resources=clusterplugindefinitions,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=greenhouse.sap,resources=plugins,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=greenhouse.sap,resources=plugins/status;,verbs=get;update;patch
//+kubebuilder:rbac:groups=greenhouse.sap,resources=plugins/finalizers,verbs=update
//+kubebuilder:rbac:groups=greenhouse.sap,resources=clusters;teams,verbs=get;list;watch
//+kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
//+kubebuilder:rbac:groups="events.k8s.io",resources=events,verbs=get;list;watch;create;patch;update
// +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases/finalizers,verbs=get;create;update;patch;delete
// +kubebuilder:rbac:groups=source.toolkit.fluxcd.io,resources=helmcharts,verbs=get;list;watch
// +kubebuilder:rbac:groups=source.toolkit.fluxcd.io,resources=ocirepositories,verbs=get;list;watch
// +kubebuilder:rbac:groups="events.k8s.io",resources=events,verbs=create;patch
// These broad permissions are required as the controller manages Helm charts which contain arbitrary Kubernetes resources.
//+kubebuilder:rbac:groups=*,resources=*,verbs=*
// SetupWithManager sets up the controller with the Manager.
func (r *PluginReconciler) SetupWithManager(name string, mgr ctrl.Manager) error {
r.Client = mgr.GetClient()
r.kubeClientOpts = []clientutil.KubeClientOption{
clientutil.WithRuntimeOptions(r.KubeRuntimeOpts),
clientutil.WithPersistentConfig(),
}
// index Plugins by the ClusterName field for faster lookups
if err := mgr.GetFieldIndexer().IndexField(context.Background(), &greenhousev1alpha1.Plugin{}, greenhouseapis.PluginClusterNameField, func(rawObj client.Object) []string {
// Extract the TeamRole name from the TeamRoleBinding Spec, if one is provided
plugin, ok := rawObj.(*greenhousev1alpha1.Plugin)
if plugin.Spec.ClusterName == "" || !ok {
return nil
}
return []string{plugin.Spec.ClusterName}
}); err != nil {
return err
}
return ctrl.NewControllerManagedBy(mgr).
Named(name).
WithOptions(controller.Options{
MaxConcurrentReconciles: 10,
}).
For(&greenhousev1alpha1.Plugin{}).
// Reconcile on owned flux HelmRelease changes.
Owns(&helmv2.HelmRelease{}).
// If a ClusterPluginDefinition was changed, reconcile relevant Plugins.
Watches(
&greenhousev1alpha1.ClusterPluginDefinition{},
handler.EnqueueRequestsFromMapFunc(r.enqueueAllPluginsForClusterPluginDefinition),
).
// If a PluginDefinition was changed, reconcile relevant Plugins.
Watches(
&greenhousev1alpha1.PluginDefinition{},
handler.EnqueueRequestsFromMapFunc(r.enqueueAllPluginsForPluginDefinition),
).
// Clusters and teams are passed as values to each Helm operation. Reconcile on change.
Watches(
&greenhousev1alpha1.Cluster{},
handler.EnqueueRequestsFromMapFunc(r.enqueueAllPluginsForCluster),
).
Watches(
&greenhousev1alpha1.Team{},
handler.EnqueueRequestsFromMapFunc(r.enqueueAllPluginsInNamespace),
builder.WithPredicates(predicate.GenerationChangedPredicate{}),
).
Complete(r)
}
func (r *PluginReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
return lifecycle.Reconcile(ctx, r.Client, req.NamespacedName, &greenhousev1alpha1.Plugin{}, r, r.setConditions())
}
func (r *PluginReconciler) setConditions() lifecycle.Conditioner {
return func(ctx context.Context, resource lifecycle.RuntimeObject) {
logger := ctrl.LoggerFrom(ctx)
plugin, ok := resource.(*greenhousev1alpha1.Plugin)
if !ok {
logger.Error(errors.New("resource is not a Plugin"), "status setup failed")
return
}
readyCondition := r.computeReadyConditionFlux(ctx, plugin)
UpdatePluginReadyMetric(plugin, readyCondition.Status == metav1.ConditionTrue)
ownerLabelCondition := util.ComputeOwnerLabelCondition(ctx, r.Client, plugin)
util.UpdateOwnedByLabelMissingMetric(plugin, ownerLabelCondition.IsFalse())
plugin.Status.SetConditions(readyCondition, ownerLabelCondition)
}
}
// reconcileTechnicalLabels ensures the plugin has the correct technical labels based on its status.
func (r *PluginReconciler) reconcileTechnicalLabels(ctx context.Context, plugin *greenhousev1alpha1.Plugin) error {
_, err := clientutil.Patch(ctx, r.Client, plugin, func() error {
labels := plugin.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
if plugin.Status.UIApplication != nil {
labels[greenhouseapis.LabelKeyUIPlugin] = "true"
} else {
delete(labels, greenhouseapis.LabelKeyUIPlugin)
}
if len(plugin.Status.ExposedServices) > 0 {
labels[greenhouseapis.LabelKeyPluginExposedServices] = "true"
} else {
delete(labels, greenhouseapis.LabelKeyPluginExposedServices)
}
plugin.SetLabels(labels)
return nil
})
return err
}
func (r *PluginReconciler) EnsureDeleted(ctx context.Context, resource lifecycle.RuntimeObject) (ctrl.Result, lifecycle.ReconcileResult, error) {
plugin := resource.(*greenhousev1alpha1.Plugin)
return r.EnsureFluxDeleted(ctx, plugin)
}
func (r *PluginReconciler) EnsureCreated(ctx context.Context, resource lifecycle.RuntimeObject) (ctrl.Result, lifecycle.ReconcileResult, error) {
plugin := resource.(*greenhousev1alpha1.Plugin)
InitPluginStatus(plugin)
// Check if we should continue with reconciliation or requeue if cluster is scheduled for deletion
result, err := shouldReconcileOrRequeue(ctx, r.Client, plugin)
if err != nil {
return ctrl.Result{}, lifecycle.Failed, err
}
if result != nil {
return ctrl.Result{RequeueAfter: result.requeueAfter}, lifecycle.Pending, nil
}
return r.EnsureFluxCreated(ctx, plugin)
}
func (r *PluginReconciler) EnsureSuspended(ctx context.Context, resource lifecycle.RuntimeObject) (ctrl.Result, error) {
plugin := resource.(*greenhousev1alpha1.Plugin)
return r.EnsureFluxSuspended(ctx, plugin)
}
// enqueueAllPluginsForCluster enqueues all Plugins which have .spec.clusterName set to the name of the given Cluster.
func (r *PluginReconciler) enqueueAllPluginsForCluster(ctx context.Context, o client.Object) []ctrl.Request {
listOpts := &client.ListOptions{
FieldSelector: fields.OneTermEqualSelector(greenhouseapis.PluginClusterNameField, o.GetName()),
Namespace: o.GetNamespace(),
}
return ListPluginsAsReconcileRequests(ctx, r.Client, listOpts)
}
func (r *PluginReconciler) enqueueAllPluginsInNamespace(ctx context.Context, o client.Object) []ctrl.Request {
return ListPluginsAsReconcileRequests(ctx, r.Client, client.InNamespace(o.GetNamespace()))
}
func (r *PluginReconciler) enqueueAllPluginsForClusterPluginDefinition(ctx context.Context, o client.Object) []ctrl.Request {
return ListPluginsAsReconcileRequests(
ctx,
r.Client,
client.MatchingLabels{greenhouseapis.LabelKeyClusterPluginDefinition: o.GetName()},
)
}
func (r *PluginReconciler) enqueueAllPluginsForPluginDefinition(ctx context.Context, o client.Object) []ctrl.Request {
return ListPluginsAsReconcileRequests(
ctx,
r.Client,
client.MatchingLabels{greenhouseapis.LabelKeyPluginDefinition: o.GetName()},
client.InNamespace(o.GetNamespace()),
)
}
func ListPluginsAsReconcileRequests(ctx context.Context, c client.Client, listOpts ...client.ListOption) []ctrl.Request {
var pluginList = new(greenhousev1alpha1.PluginList)
if err := c.List(ctx, pluginList, listOpts...); err != nil {
ctrl.LoggerFrom(ctx).Error(err, "failed to list Plugins for reconcile requests")
return nil
}
res := make([]ctrl.Request, len(pluginList.Items))
for idx, plugin := range pluginList.Items {
namespacedName := types.NamespacedName{Namespace: plugin.GetNamespace(), Name: plugin.GetName()}
res[idx] = ctrl.Request{NamespacedName: namespacedName}
}
return res
}
// getExposedServicesForPluginFromHelmRelease returns a map of exposed services for a plugin from a Helm release.
// The exposed services are collected from Helm release manifest and not from the template to make sure they are deployed.
func getExposedServicesForPluginFromHelmRelease(restClientGetter genericclioptions.RESTClientGetter, helmRelease *release.Release, plugin *greenhousev1alpha1.Plugin) (map[string]greenhousev1alpha1.Service, error) {
// Collect exposed services from the manifest.
exposedServiceList, err := helm.ObjectMapFromRelease(restClientGetter, helmRelease, &helm.ManifestObjectFilter{
APIVersion: "v1",
Kind: "Service",
Annotations: map[string]string{
greenhouseapis.AnnotationKeyExpose: "true",
},
})
if err != nil {
return nil, err
}
var exposedServices = make(map[string]greenhousev1alpha1.Service)
if len(exposedServiceList) == 0 {
return exposedServices, nil
}
if plugin.Spec.ClusterName == "" {
return nil, errors.New("plugin does not have ClusterName")
}
for _, svc := range exposedServiceList {
svcPort, err := getPortForExposedService(svc.Object)
if err != nil {
return nil, err
}
namespace := svc.Namespace
if namespace == "" {
namespace = helmRelease.Namespace // default namespace to release namespace
}
exposedURL := common.URLForExposedServiceInPlugin(svc.Name, plugin)
exposedServices[exposedURL] = greenhousev1alpha1.Service{
Namespace: namespace,
Name: svc.Name,
Protocol: svcPort.AppProtocol,
Port: svcPort.Port,
Type: greenhousev1alpha1.ServiceTypeService,
}
}
return exposedServices, nil
}
// getExposedIngressesForPluginFromHelmRelease discovers ingress resources from a Helm release that are marked for exposure.
// It searches for ingresses with the annotation "greenhouse.sap/expose": "true" and extracts their URLs.
//
// For each discovered ingress:
// - Automatically detects HTTPS protocol based on TLS configuration
// - Selects the host using greenhouse.sap/exposed-host annotation or defaults to the first host rule
// - Constructs complete URLs with protocol (http:// or https://)
// - Returns them as Service entries with type ServiceTypeIngress (port set to 0 as not applicable)
//
// The function filters ingresses from the Helm release manifest (not templates) to ensure they are actually deployed.
func getExposedIngressesForPluginFromHelmRelease(restClientGetter genericclioptions.RESTClientGetter, helmRelease *release.Release) (map[string]greenhousev1alpha1.Service, error) {
exposedIngressList, err := helm.ObjectMapFromRelease(restClientGetter, helmRelease, &helm.ManifestObjectFilter{
APIVersion: "v1",
Kind: "Ingress",
Annotations: map[string]string{
greenhouseapis.AnnotationKeyExpose: "true",
},
})
if err != nil {
return nil, err
}
var exposedServices = make(map[string]greenhousev1alpha1.Service)
for _, ingress := range exposedIngressList {
fullURL, err := getURLForExposedIngress(ingress.Object)
if err != nil {
return nil, err
}
namespace := ingress.Namespace
if namespace == "" {
namespace = helmRelease.Namespace
}
exposedServices[fullURL] = greenhousev1alpha1.Service{
Namespace: namespace,
Name: ingress.Name,
Type: greenhousev1alpha1.ServiceTypeIngress,
}
}
return exposedServices, nil
}
// getAllExposedServicesForPlugin aggregates all exposed services and ingresses for a plugin from its Helm release.
// This function combines two types of exposures into a unified map for Plugin.status.exposedServices:
//
// 1. Services (ServiceTypeService): Exposed via service-proxy for internal routing
// - Discovered from services with "greenhouse.sap/expose" annotation
// - URLs are generated using the service-proxy pattern
//
// 2. Ingresses (ServiceTypeIngress): Exposed directly via external URLs
// - Discovered from ingresses with "greenhouse.sap/expose" annotation
// - URLs are the actual ingress hostnames with proper protocol (http/https)
// - Protocol automatically detected from TLS configuration
//
// If either service or ingress discovery encounters an error, the entire operation fails.
func getAllExposedServicesForPlugin(restClientGetter genericclioptions.RESTClientGetter, helmRelease *release.Release, plugin *greenhousev1alpha1.Plugin, exposeServices bool) (map[string]greenhousev1alpha1.Service, error) {
var errorMessages []string
exposedServices := make(map[string]greenhousev1alpha1.Service)
if exposeServices {
serviceList, err := getExposedServicesForPluginFromHelmRelease(restClientGetter, helmRelease, plugin)
if err != nil {
errorMessages = append(errorMessages, "services: "+err.Error())
} else {
maps.Copy(exposedServices, serviceList)
}
}
ingressList, err := getExposedIngressesForPluginFromHelmRelease(restClientGetter, helmRelease)
if err != nil {
errorMessages = append(errorMessages, "ingresses: "+err.Error())
} else {
maps.Copy(exposedServices, ingressList)
}
if len(errorMessages) > 0 {
return nil, fmt.Errorf("failed to get exposed resources: %s", strings.Join(errorMessages, "; "))
}
return exposedServices, nil
}