/
hostedcontrolplane.go
331 lines (293 loc) · 12.4 KB
/
hostedcontrolplane.go
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
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package hostedcontrolplane
import (
"context"
"fmt"
"github.com/go-logr/logr"
routev1 "github.com/openshift/api/route/v1"
"github.com/openshift/hypershift/api/v1beta1"
"github.com/openshift/route-monitor-operator/api/v1alpha1"
"github.com/openshift/route-monitor-operator/pkg/util/finalizer"
utilreconcile "github.com/openshift/route-monitor-operator/pkg/util/reconcile"
v1 "k8s.io/api/core/v1"
kerr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
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/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
// hostedcontrolplaneFinalizer defines the finalizer used by this controller's objects
hostedcontrolplaneFinalizer = "hostedcontrolplane.routemonitoroperator.monitoring.openshift.io/finalizer"
// watchResourceLabel is a label key indicating which objects this controller should reconcile against
watchResourceLabel = "hostedcontrolplane.routemonitoroperator.monitoring.openshift.io/managed"
)
var logger logr.Logger = ctrl.Log.WithName("controllers").WithName("HostedControlPlane")
// HostedControlPlaneReconciler reconciles a HostedControlPlane object
type HostedControlPlaneReconciler struct {
client.Client
Scheme *runtime.Scheme
}
// NewHostedControlPlaneReconciler creates a HostedControlPlaneReconciler
func NewHostedControlPlaneReconciler(mgr manager.Manager) *HostedControlPlaneReconciler {
return &HostedControlPlaneReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}
}
//+kubebuilder:rbac:groups=openshift.io,resources=hostedcontrolplanes,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=openshift.io,resources=hostedcontrolplanes/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=openshift.io,resources=hostedcontrolplanes/finalizers,verbs=update
// Reconcile responds to events against watched objects
func (r *HostedControlPlaneReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := logger.WithName("Reconcile").WithValues("name", req.Name, "namespace", req.Namespace)
log.Info("Reconciling HostedControlPlanes")
defer log.Info("Finished reconciling HostedControlPlane")
// Fetch the HostedControlPlane instance
hostedcontrolplane := &v1beta1.HostedControlPlane{}
err := r.Client.Get(ctx, req.NamespacedName, hostedcontrolplane)
if err != nil {
if kerr.IsNotFound(err) {
log.Info("HostedControlPlane not found, assumed deleted")
return utilreconcile.Stop()
}
log.Error(err, "unable to fetch HostedControlPlane")
return utilreconcile.RequeueWith(err)
}
// If the HostedControlPlane is marked for deletion, clean up
shouldDelete := finalizer.WasDeleteRequested(hostedcontrolplane)
if shouldDelete {
err := r.finalizeHostedControlPlane(ctx, log, hostedcontrolplane)
if err != nil {
log.Error(err, "failed to finalize HostedControlPlane")
return utilreconcile.RequeueWith(err)
}
finalizer.Remove(hostedcontrolplane, hostedcontrolplaneFinalizer)
err = r.Client.Update(ctx, hostedcontrolplane)
if err != nil {
return utilreconcile.RequeueWith(err)
}
return utilreconcile.Stop()
}
if !finalizer.Contains(hostedcontrolplane.Finalizers, hostedcontrolplaneFinalizer) {
finalizer.Add(hostedcontrolplane, hostedcontrolplaneFinalizer)
err := r.Client.Update(ctx, hostedcontrolplane)
if err != nil {
return utilreconcile.RequeueWith(err)
}
}
// Check if the HostedControlPlane is ready
if !hostedcontrolplane.Status.Ready {
log.Info("skipped deploying monitoring objects: HostedControlPlane not ready")
return utilreconcile.Stop()
}
log.Info("Deploying internal monitoring objects")
err = r.deployInternalMonitoringObjects(ctx, log, hostedcontrolplane)
if err != nil {
log.Error(err, "failed to deploy internal monitoring components")
return utilreconcile.RequeueWith(err)
}
return ctrl.Result{}, err
}
// deployInternalMonitoringObjects creates or updates the objects needed to monitor the kube-apiserver using cluster-internal routes
func (r *HostedControlPlaneReconciler) deployInternalMonitoringObjects(ctx context.Context, log logr.Logger, hostedcontrolplane *v1beta1.HostedControlPlane) error {
// Create or update route object
expectedRoute := r.buildInternalMonitoringRoute(hostedcontrolplane)
err := r.Client.Create(ctx, &expectedRoute)
if err != nil {
if !kerr.IsAlreadyExists(err) {
return err
}
// Object already exists: update it
actualRoute := routev1.Route{}
err := r.Client.Get(ctx, types.NamespacedName{Name: expectedRoute.Name, Namespace: expectedRoute.Namespace}, &actualRoute)
if err != nil {
return err
}
expectedRoute.ObjectMeta = buildMetadataForUpdate(expectedRoute.ObjectMeta, actualRoute.ObjectMeta)
err = r.Client.Update(ctx, &expectedRoute)
if err != nil {
return err
}
}
// Quick fix to discover the API server port from the service resource
apiServerService := v1.Service{}
err = r.Client.Get(ctx, types.NamespacedName{Name: "kube-apiserver", Namespace: hostedcontrolplane.Namespace}, &apiServerService)
if err != nil {
return fmt.Errorf("couldn't query API server service resource: %w", err)
}
apiServerPort := int64(6443)
if len(apiServerService.Spec.Ports) > 0 {
apiServerPort = int64(apiServerService.Spec.Ports[0].Port)
}
// Create or update RouteMonitor object
expectedRouteMonitor := r.buildInternalMonitoringRouteMonitor(expectedRoute, hostedcontrolplane, apiServerPort)
err = r.Client.Create(ctx, &expectedRouteMonitor)
if err != nil {
if !kerr.IsAlreadyExists(err) {
return err
}
// Object already exists: update it
actualRouteMonitor := v1alpha1.RouteMonitor{}
err = r.Client.Get(ctx, types.NamespacedName{Name: expectedRouteMonitor.Name, Namespace: expectedRouteMonitor.Namespace}, &actualRouteMonitor)
if err != nil {
return err
}
expectedRouteMonitor.ObjectMeta = buildMetadataForUpdate(expectedRouteMonitor.ObjectMeta, actualRouteMonitor.ObjectMeta)
err = r.Client.Update(ctx, &expectedRouteMonitor)
if err != nil {
return err
}
}
return nil
}
// buildMetadataForUpdate is a helper function to generate valid metadata for an Update request by combining the expected object's Metadata and the actual (on-cluster) object's Metadata
func buildMetadataForUpdate(expected, actual metav1.ObjectMeta) metav1.ObjectMeta {
actual.Labels = expected.Labels
actual.OwnerReferences = expected.OwnerReferences
return actual
}
// buildInternalMonitoringRoute constructs the Route needed to monitor a HostedControlPlane's kube-apiserver via cluster-internal routes
func (r *HostedControlPlaneReconciler) buildInternalMonitoringRoute(hostedcontrolplane *v1beta1.HostedControlPlane) routev1.Route {
weight := int32(100)
route := routev1.Route{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-kube-apiserver-monitoring", hostedcontrolplane.Name),
Namespace: hostedcontrolplane.Namespace,
OwnerReferences: buildOwnerReferences(hostedcontrolplane),
Labels: map[string]string{
watchResourceLabel: "true",
},
},
Spec: routev1.RouteSpec{
Host: fmt.Sprintf("kube-apiserver.%s.svc.cluster.local", hostedcontrolplane.Namespace),
TLS: &routev1.TLSConfig{
InsecureEdgeTerminationPolicy: routev1.InsecureEdgeTerminationPolicyNone,
Termination: routev1.TLSTerminationPassthrough,
},
To: routev1.RouteTargetReference{
Kind: "Service",
Name: "kube-apiserver",
Weight: &weight,
},
WildcardPolicy: routev1.WildcardPolicyNone,
},
}
return route
}
// buildInternalMonitoringRouteMonitor constructs the expected RouteMonitor needed to probe a HostedControlPlane's kube-apiserver using cluster-internal routes
func (r *HostedControlPlaneReconciler) buildInternalMonitoringRouteMonitor(route routev1.Route, hostedcontrolplane *v1beta1.HostedControlPlane, apiServerPort int64) v1alpha1.RouteMonitor {
routemonitor := v1alpha1.RouteMonitor{
ObjectMeta: metav1.ObjectMeta{
Name: route.Name,
Namespace: route.Namespace,
OwnerReferences: buildOwnerReferences(hostedcontrolplane),
Labels: map[string]string{
watchResourceLabel: "true",
},
},
Spec: v1alpha1.RouteMonitorSpec{
Route: v1alpha1.RouteMonitorRouteSpec{
Name: route.Name,
Namespace: route.Namespace,
Port: apiServerPort,
Suffix: "/livez",
},
SkipPrometheusRule: false,
Slo: v1alpha1.SloSpec{
TargetAvailabilityPercent: "99.5",
},
InsecureSkipTLSVerify: true,
ServiceMonitorType: v1alpha1.ServiceMonitorTypeRHOBS,
},
}
return routemonitor
}
// buildOwnerReferences generates a set OwnerReferences indicating the HostedControlPlane is the owner+controller of the object. This is used
// to trigger reconciles against non-HCP objects (ie - the route & routemonitor generated by this controller)
func buildOwnerReferences(hostedcontrolplane *v1beta1.HostedControlPlane) []metav1.OwnerReference {
return []metav1.OwnerReference{*metav1.NewControllerRef(&hostedcontrolplane.ObjectMeta, hostedcontrolplane.GroupVersionKind())}
}
// finalizeHostedControlPlane cleans up HostedControlPlane-related objects managed by the HostedControlPlaneReconciler
func (r *HostedControlPlaneReconciler) finalizeHostedControlPlane(ctx context.Context, log logr.Logger, hostedcontrolplane *v1beta1.HostedControlPlane) error {
err := r.deleteInternalMonitoringObjects(ctx, log, hostedcontrolplane)
if err != nil {
return fmt.Errorf("failed to cleanup internal monitoring resources: %w", err)
}
return nil
}
// deleteInternalMonitoringObjects removes the internal monitoring objects for the provided HostedControlPlane
func (r *HostedControlPlaneReconciler) deleteInternalMonitoringObjects(ctx context.Context, log logr.Logger, hostedcontrolplane *v1beta1.HostedControlPlane) error {
// Delete Route
expectedRoute := r.buildInternalMonitoringRoute(hostedcontrolplane)
err := r.Client.Delete(ctx, &expectedRoute)
if err != nil {
if !kerr.IsNotFound(err) {
return err
}
log.Info(fmt.Sprintf("Skipped deleting Route %s/%s: already deleted", expectedRoute.Namespace, expectedRoute.Name))
}
// Delete routemonitor, port is not relevant for deletion
expectedRouteMonitor := r.buildInternalMonitoringRouteMonitor(expectedRoute, hostedcontrolplane, 6443)
err = r.Client.Delete(ctx, &expectedRouteMonitor)
if err != nil {
if !kerr.IsNotFound(err) {
return err
}
log.Info(fmt.Sprintf("Skipped deleting RouteMonitor %s/%s: already deleted", expectedRoute.Namespace, expectedRoute.Name))
}
return nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *HostedControlPlaneReconciler) SetupWithManager(mgr ctrl.Manager) error {
selector := metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: watchResourceLabel,
Operator: metav1.LabelSelectorOpExists,
},
},
}
selectorPredicate, err := predicate.LabelSelectorPredicate(selector)
if err != nil {
return fmt.Errorf("failed to build label selector predicate for routes: %w", err)
}
// The following:
// - Reconciles against all HostedControlPlane objects
// - Additionally watches against route & routemonitor objects with the 'watchResourceLabel' present.
// When these objects are modified, the HCP specified in the objects' .metadata.OwnerReferences is
// reconciled
return ctrl.NewControllerManagedBy(mgr).
For(&v1beta1.HostedControlPlane{}).
Watches(
&source.Kind{Type: &routev1.Route{}},
&handler.EnqueueRequestForOwner{
OwnerType: &v1beta1.HostedControlPlane{},
IsController: true,
},
builder.WithPredicates(selectorPredicate)).
Watches(
&source.Kind{Type: &v1alpha1.RouteMonitor{}},
&handler.EnqueueRequestForOwner{
OwnerType: &v1beta1.HostedControlPlane{},
IsController: true,
},
builder.WithPredicates(selectorPredicate)).
Complete(r)
}