Repository navigation
Expand file tree
/
Copy pathopenstackclient_controller.go
More file actions
811 lines (742 loc) · 28.4 KB
/
Copy pathopenstackclient_controller.go
File metadata and controls
811 lines (742 loc) · 28.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
/*
Copyright 2023.
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 client contains the OpenStackClient controller implementation
package client
import (
"context"
"errors"
"fmt"
"time"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
rbacv1 "k8s.io/api/rbac/v1"
k8s_errors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/utils/ptr"
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/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
keystonev1 "github.com/openstack-k8s-operators/keystone-operator/api/v1beta1"
"github.com/openstack-k8s-operators/lib-common/modules/common"
condition "github.com/openstack-k8s-operators/lib-common/modules/common/condition"
"github.com/openstack-k8s-operators/lib-common/modules/common/configmap"
"github.com/openstack-k8s-operators/lib-common/modules/common/endpoint"
"github.com/openstack-k8s-operators/lib-common/modules/common/env"
helper "github.com/openstack-k8s-operators/lib-common/modules/common/helper"
common_rbac "github.com/openstack-k8s-operators/lib-common/modules/common/rbac"
"github.com/openstack-k8s-operators/lib-common/modules/common/secret"
"github.com/openstack-k8s-operators/lib-common/modules/common/service"
"github.com/openstack-k8s-operators/lib-common/modules/common/tls"
"github.com/openstack-k8s-operators/lib-common/modules/common/util"
clientv1 "github.com/openstack-k8s-operators/openstack-operator/api/client/v1beta1"
"github.com/openstack-k8s-operators/openstack-operator/internal/openstackclient"
telemetryv1 "github.com/openstack-k8s-operators/telemetry-operator/api/v1beta1"
)
// OpenStackClientReconciler reconciles a OpenStackClient object
type OpenStackClientReconciler struct {
client.Client
Scheme *runtime.Scheme
Kclient kubernetes.Interface
}
// GetLogger returns a logger object with a prefix of "controller.name" and additional controller context fields
func (r *OpenStackClientReconciler) GetLogger(ctx context.Context) logr.Logger {
return log.FromContext(ctx).WithName("Controllers").WithName("OpenStackClient")
}
// ensureMCPResourceDeleted deletes obj if it exists, used to clean up
// MCP sidecar resources when the MCP server is disabled.
func ensureMCPResourceDeleted(ctx context.Context, c client.Client, obj client.Object) error {
key := client.ObjectKeyFromObject(obj)
if err := c.Get(ctx, key, obj); err != nil {
if k8s_errors.IsNotFound(err) {
return nil
}
return err
}
if obj.GetDeletionTimestamp().IsZero() {
if err := c.Delete(ctx, obj); err != nil && !k8s_errors.IsNotFound(err) {
return err
}
}
return nil
}
// +kubebuilder:rbac:groups=client.openstack.org,resources=openstackclients,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=client.openstack.org,resources=openstackclients/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=client.openstack.org,resources=openstackclients/finalizers,verbs=update
// +kubebuilder:rbac:groups=keystone.openstack.org,resources=keystoneapis,verbs=get;list;watch
// +kubebuilder:rbac:groups=telemetry.openstack.org,resources=metricstorages,verbs=get;list;watch
// +kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch;
// service account, role, rolebinding
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=roles,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=rolebindings,verbs=get;list;watch;create;update;patch
// service account permissions that are needed to grant permission to the above
// +kubebuilder:rbac:groups="security.openshift.io",resourceNames=nonroot-v2,resources=securitycontextconstraints,verbs=use
// +kubebuilder:rbac:groups="",resources=pods,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="networking.k8s.io",resources=networkpolicies,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=cert-manager.io,resources=issuers,verbs=get;list;watch
// +kubebuilder:rbac:groups=cert-manager.io,resources=certificates,verbs=get;list;watch;create;update;patch;delete
// Reconcile -
func (r *OpenStackClientReconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, _err error) {
Log := r.GetLogger(ctx)
instance := &clientv1.OpenStackClient{}
err := r.Get(context.TODO(), req.NamespacedName, instance)
if err != nil {
if k8s_errors.IsNotFound(err) {
Log.Info("OpenStackClient CR not found")
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
Log.Info("OpenStackClient CR values", "Name", instance.Name, "Namespace", instance.Namespace, "Secret", instance.Spec.OpenStackConfigSecret, "Image", instance.Spec.ContainerImage)
helper, err := helper.NewHelper(
instance,
r.Client,
r.Kclient,
r.Scheme,
Log,
)
if err != nil {
return ctrl.Result{}, err
}
//
// initialize status
//
isNewInstance := instance.Status.Conditions == nil
if isNewInstance {
instance.Status.Conditions = condition.Conditions{}
}
// Save a copy of the condtions so that we can restore the LastTransitionTime
// when a condition's state doesn't change.
savedConditions := instance.Status.Conditions.DeepCopy()
// Always patch the instance status when exiting this function so we can persist any changes.
defer func() {
// Don't update the status, if reconciler Panics
if r := recover(); r != nil {
Log.Info(fmt.Sprintf("panic during reconcile %v\n", r))
panic(r)
}
condition.RestoreLastTransitionTimes(&instance.Status.Conditions, savedConditions)
// update the Ready condition based on the sub conditions
if instance.Status.Conditions.AllSubConditionIsTrue() {
instance.Status.Conditions.MarkTrue(
condition.ReadyCondition, condition.ReadyMessage)
} else {
// something is not ready so reset the Ready condition
instance.Status.Conditions.MarkUnknown(
condition.ReadyCondition, condition.InitReason, condition.ReadyInitMessage)
// and recalculate it based on the state of the rest of the conditions
instance.Status.Conditions.Set(
instance.Status.Conditions.Mirror(condition.ReadyCondition))
}
err := helper.PatchInstance(ctx, instance)
if err != nil {
_err = err
return
}
}()
cl := condition.CreateList(
condition.UnknownCondition(clientv1.OpenStackClientReadyCondition, condition.InitReason, clientv1.OpenStackClientReadyInitMessage),
// service account, role, rolebinding conditions
condition.UnknownCondition(condition.ServiceAccountReadyCondition, condition.InitReason, condition.ServiceAccountReadyInitMessage),
condition.UnknownCondition(condition.RoleReadyCondition, condition.InitReason, condition.RoleReadyInitMessage),
condition.UnknownCondition(condition.RoleBindingReadyCondition, condition.InitReason, condition.RoleBindingReadyInitMessage),
)
instance.Status.Conditions.Init(&cl)
instance.Status.ObservedGeneration = instance.Generation
// Service account, role, binding. The client containers use a fixed non-root
// UID and RuntimeDefault seccomp profile, which matches the nonroot-v2 SCC.
rbacRules := []rbacv1.PolicyRule{
{
APIGroups: []string{"security.openshift.io"},
ResourceNames: []string{"nonroot-v2"},
Resources: []string{"securitycontextconstraints"},
Verbs: []string{"use"},
},
}
rbacResult, err := common_rbac.ReconcileRbac(ctx, helper, instance, rbacRules)
if err != nil {
return rbacResult, err
} else if (rbacResult != ctrl.Result{}) {
return rbacResult, nil
}
//
// Validate that keystoneAPI is up
//
keystoneAPI, err := keystonev1.GetKeystoneAPI(ctx, helper, instance.Namespace, map[string]string{})
if err != nil {
if k8s_errors.IsNotFound(err) {
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
clientv1.OpenStackClientKeystoneWaitingMessage))
Log.Info("KeystoneAPI not found!")
return ctrl.Result{RequeueAfter: time.Duration(5) * time.Second}, nil
}
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
clientv1.OpenStackClientReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
if !keystoneAPI.IsReady() {
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
clientv1.OpenStackClientKeystoneWaitingMessage))
Log.Info("KeystoneAPI not yet ready")
return ctrl.Result{RequeueAfter: time.Duration(5) * time.Second}, nil
}
clientLabels := map[string]string{
common.AppSelector: "openstackclient",
common.OwnerSelector: instance.Name,
}
configVars := make(map[string]env.Setter)
_, configMapHash, err := configmap.GetConfigMapAndHashWithName(ctx, helper, *instance.Spec.OpenStackConfigMap, instance.Namespace)
if err != nil {
if k8s_errors.IsNotFound(err) {
// Since the OpenStackConfigMap config map is usually automatically created by the Keystone operator,
// we treat this as an info (because the user is usually not responsible for manually creating it).
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
clientv1.OpenStackClientConfigMapWaitingMessage))
return ctrl.Result{RequeueAfter: time.Duration(10) * time.Second}, nil
}
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
clientv1.OpenStackClientReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
configVars[*instance.Spec.OpenStackConfigMap] = env.SetValue(configMapHash)
_, secretHash, err := secret.GetSecret(ctx, helper, *instance.Spec.OpenStackConfigSecret, instance.Namespace)
if err != nil {
if k8s_errors.IsNotFound(err) {
// Since the OpenStackConfigSecret secret is usually automatically created by the Keystone operator,
// we treat this as an info (because the user is usually not responsible for manually creating it).
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
clientv1.OpenStackClientSecretWaitingMessage))
return ctrl.Result{RequeueAfter: time.Duration(10) * time.Second}, nil
}
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
clientv1.OpenStackClientReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
configVars[*instance.Spec.OpenStackConfigSecret] = env.SetValue(secretHash)
if instance.Spec.CaBundleSecretName != "" {
secretHash, err := tls.ValidateCACertSecret(
ctx,
helper.GetClient(),
types.NamespacedName{
Name: instance.Spec.CaBundleSecretName,
Namespace: instance.Namespace,
},
)
if err != nil {
if k8s_errors.IsNotFound(err) {
// Since the CA cert secret should have been manually created by the user when provided in the spec,
// we treat this as a warning because it means that reconciliation will not be able to continue.
instance.Status.Conditions.Set(condition.FalseCondition(
condition.TLSInputReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.TLSInputReadyWaitingMessage,
instance.Spec.CaBundleSecretName))
return ctrl.Result{}, nil
}
instance.Status.Conditions.Set(condition.FalseCondition(
condition.TLSInputReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.TLSInputErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
configVars[instance.Spec.CaBundleSecretName] = env.SetValue(secretHash)
}
metricStorage := &telemetryv1.MetricStorage{}
err = helper.GetClient().Get(ctx, client.ObjectKey{
Namespace: instance.Namespace,
Name: telemetryv1.DefaultServiceName,
}, metricStorage)
if err == nil {
configVars["PrometheusTls"] = env.SetValue(fmt.Sprint(metricStorage.Spec.PrometheusTLS.Enabled()))
} else if k8s_errors.IsNotFound(err) {
// MetricStorage is optional; clear the object so MCP config does not
// point at a Prometheus service that is not present.
metricStorage = nil
} else {
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
clientv1.OpenStackClientReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
// all cert input checks out so report InputReady
instance.Status.Conditions.MarkTrue(condition.TLSInputReadyCondition, condition.InputReadyMessage)
// Reconcile MCP sidecar resources when enabled. The MCP server's TLS
// certificate is owned by the OpenStackControlPlane, which populates
// Spec.MCPCertSecretName; this controller only consumes it.
var mcpTLSSvc *tls.Service
instance.Status.MCPEndpoint = ""
if instance.Spec.MCP != nil && instance.Spec.MCP.Enabled {
if instance.Spec.MCPContainerImage == "" {
return ctrl.Result{}, fmt.Errorf("MCP is enabled but MCPContainerImage is not set")
}
// Use the internal Keystone endpoint for the MCP sidecar's clouds.yaml
internalAuthURL, err := keystoneAPI.GetEndpoint(endpoint.EndpointInternal)
if err != nil {
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
"waiting for internal Keystone endpoint"))
return ctrl.Result{RequeueAfter: time.Duration(5) * time.Second}, nil
}
// When the control plane has provisioned an MCP TLS cert, mount it in
// the sidecar. Otherwise the MCP server runs without TLS.
if instance.Spec.MCPCertSecretName != "" {
mcpTLSSvc = &tls.Service{
SecretName: instance.Spec.MCPCertSecretName,
CertMount: ptr.To("/etc/pki/tls/mcp/tls.crt"),
KeyMount: ptr.To("/etc/pki/tls/mcp/tls.key"),
}
certHash, err := mcpTLSSvc.ValidateCertSecret(ctx, helper, instance.Namespace)
if err != nil {
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
clientv1.OpenStackClientReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
configVars["mcp-tls"] = env.SetValue(certHash)
}
mcpConfigYAML := openstackclient.MCPConfigYAML(
instance.Name,
instance.Namespace,
instance.Spec.CaBundleSecretName,
mcpTLSSvc != nil,
metricStorage,
)
mcpCloudsYAML := openstackclient.MCPCloudsYAML(
internalAuthURL,
keystoneAPI.Spec.AdminProject,
keystoneAPI.Spec.AdminUser,
keystoneAPI.Spec.Region,
instance.Spec.CaBundleSecretName,
)
mcpConfigCM := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Name + "-mcp-config",
Namespace: instance.Namespace,
},
}
_, err = controllerutil.CreateOrPatch(ctx, r.Client, mcpConfigCM, func() error {
mcpConfigCM.Data = map[string]string{
"config.yaml": mcpConfigYAML,
"clouds.yaml": mcpCloudsYAML,
}
return controllerutil.SetControllerReference(instance, mcpConfigCM, r.Scheme)
})
if err != nil {
return ctrl.Result{}, fmt.Errorf("error creating MCP config ConfigMap: %w", err)
}
configVars[instance.Name+"-mcp-config"] = env.SetValue(mcpConfigYAML + mcpCloudsYAML)
} else {
// MCP is disabled, clean up any previously created MCP config ConfigMap
mcpConfigCM := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Name + "-mcp-config",
Namespace: instance.Namespace,
},
}
if err := ensureMCPResourceDeleted(ctx, r.Client, mcpConfigCM); err != nil {
return ctrl.Result{}, fmt.Errorf("error deleting MCP config ConfigMap: %w", err)
}
}
configVarsHash, err := util.HashOfInputHashes(configVars)
if err != nil {
return ctrl.Result{}, err
}
// Reconcile MCP Service
if instance.Spec.MCP != nil && instance.Spec.MCP.Enabled {
mcpSvc, err := service.NewService(
service.GenericService(&service.GenericServiceDetails{
Name: instance.Name + "-mcp",
Namespace: instance.Namespace,
Labels: clientLabels,
Selector: clientLabels,
Ports: []corev1.ServicePort{
{
Name: "mcp",
Port: 8080,
Protocol: corev1.ProtocolTCP,
},
},
}),
5*time.Second,
nil,
)
if err != nil {
return ctrl.Result{}, fmt.Errorf("error creating MCP Service: %w", err)
}
ctrlResult, err := mcpSvc.CreateOrPatch(ctx, helper)
if err != nil {
return ctrl.Result{}, fmt.Errorf("error reconciling MCP Service: %w", err)
} else if (ctrlResult != ctrl.Result{}) {
return ctrlResult, nil
}
scheme := "http"
if mcpTLSSvc != nil {
scheme = "https"
}
instance.Status.MCPEndpoint = fmt.Sprintf(
"%s://%s.%s.svc:8080/openstack/",
scheme,
instance.Name+"-mcp",
instance.Namespace,
)
// Restrict access to the MCP port to OpenStackAssistant pods in the
// same namespace. This blocks any other pod, including ones in other
// namespaces, from reaching the MCP server.
mcpNetworkPolicy := &networkingv1.NetworkPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Name + "-mcp",
Namespace: instance.Namespace,
},
}
_, err = controllerutil.CreateOrPatch(ctx, r.Client, mcpNetworkPolicy, func() error {
mcpNetworkPolicy.Spec = networkingv1.NetworkPolicySpec{
PodSelector: metav1.LabelSelector{
MatchLabels: clientLabels,
},
PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress},
Ingress: []networkingv1.NetworkPolicyIngressRule{
{
From: []networkingv1.NetworkPolicyPeer{
{
PodSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
common.AppSelector: "openstackassistant",
},
},
},
},
Ports: []networkingv1.NetworkPolicyPort{
{
Protocol: ptr.To(corev1.ProtocolTCP),
Port: ptr.To(intstr.FromInt32(8080)),
},
},
},
},
}
return controllerutil.SetControllerReference(instance, mcpNetworkPolicy, r.Scheme)
})
if err != nil {
return ctrl.Result{}, fmt.Errorf("error creating MCP NetworkPolicy: %w", err)
}
} else {
// MCP is disabled, clean up any previously created MCP resources so
// the Service does not continue selecting the client pod.
mcpService := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Name + "-mcp",
Namespace: instance.Namespace,
},
}
if err := ensureMCPResourceDeleted(ctx, r.Client, mcpService); err != nil {
return ctrl.Result{}, fmt.Errorf("error deleting MCP Service: %w", err)
}
mcpNetworkPolicy := &networkingv1.NetworkPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Name + "-mcp",
Namespace: instance.Namespace,
},
}
if err := ensureMCPResourceDeleted(ctx, r.Client, mcpNetworkPolicy); err != nil {
return ctrl.Result{}, fmt.Errorf("error deleting MCP NetworkPolicy: %w", err)
}
}
osclient := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Name,
Namespace: instance.Namespace,
},
}
spec := openstackclient.ClientPodSpec(ctx, instance, helper, configVarsHash, mcpTLSSvc)
podSpecHash, err := util.ObjectHash(spec)
if err != nil {
return ctrl.Result{}, err
}
podSpecHashName := "podSpec"
op, err := controllerutil.CreateOrPatch(ctx, r.Client, osclient, func() error {
isPodUpdate := !osclient.CreationTimestamp.IsZero()
currentPodSpecHash := instance.Status.Hash[podSpecHashName]
if !isPodUpdate || currentPodSpecHash != podSpecHash {
osclient.Spec = spec
}
osclient.Labels = util.MergeStringMaps(osclient.Labels, clientLabels)
err = controllerutil.SetControllerReference(instance, osclient, r.Scheme)
if err != nil {
return err
}
return nil
})
if err != nil {
var forbiddenPodSpecChangeErr *k8s_errors.StatusError
forbiddenPodSpec := false
if errors.As(err, &forbiddenPodSpecChangeErr) {
if forbiddenPodSpecChangeErr.ErrStatus.Reason == metav1.StatusReasonForbidden {
forbiddenPodSpec = true
}
}
if forbiddenPodSpec || k8s_errors.IsInvalid(err) {
// Delete pod when its config changed. In this case we just re-create the
// openstackclient pod
if err := r.Delete(ctx, osclient); err != nil && !k8s_errors.IsNotFound(err) {
// Error deleting the object
return ctrl.Result{}, fmt.Errorf("error deleting OpenStackClient pod %s: %w", osclient.Name, err)
}
Log.Info(fmt.Sprintf("OpenStackClient pod deleted due to change %s", err.Error()))
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, fmt.Errorf("failed to create or update pod %s: %w", osclient.Name, err)
}
if err != nil {
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.DeploymentReadyErrorMessage,
err.Error()))
return ctrl.Result{}, err
}
instance.Status.Hash, _ = util.SetHash(instance.Status.Hash, podSpecHashName, podSpecHash)
if op != controllerutil.OperationResultNone {
util.LogForObject(
helper,
fmt.Sprintf("Pod %s successfully reconciled - operation: %s", osclient.Name, string(op)),
instance,
)
}
// if pod is stuck in terminating state for more than 3 minutes, force delete it
if osclient.DeletionTimestamp != nil {
terminatingDuration := time.Since(osclient.DeletionTimestamp.Time)
if terminatingDuration > time.Minute*3 {
// Force delete only truly stuck pods
err := r.Delete(ctx, osclient, client.GracePeriodSeconds(0))
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to force delete pod: %w", err)
}
}
}
podReady := false
for _, condition := range osclient.Status.Conditions {
if condition.Type == corev1.PodReady && condition.Status == corev1.ConditionTrue {
podReady = true
break
}
}
if podReady {
instance.Status.Conditions.MarkTrue(
clientv1.OpenStackClientReadyCondition,
clientv1.OpenStackClientReadyMessage,
)
} else {
instance.Status.Conditions.Set(condition.FalseCondition(
clientv1.OpenStackClientReadyCondition,
condition.RequestedReason,
condition.SeverityInfo,
clientv1.OpenStackClientReadyRunningMessage))
}
return ctrl.Result{}, nil
}
// fields to index to reconcile when change
const (
caBundleSecretNameField = ".spec.caBundleSecretName"
openStackConfigMapField = ".spec.openStackConfigMap"
openStackConfigSecretField = ".spec.openStackConfigSecret"
mcpCertSecretNameField = ".spec.mcpCertSecretName"
)
var allWatchFields = []string{
caBundleSecretNameField,
openStackConfigMapField,
openStackConfigSecretField,
mcpCertSecretNameField,
}
// SetupWithManager sets up the controller with the Manager.
func (r *OpenStackClientReconciler) SetupWithManager(
ctx context.Context, mgr ctrl.Manager) error {
// index caBundleSecretNameField
if err := mgr.GetFieldIndexer().IndexField(ctx, &clientv1.OpenStackClient{}, caBundleSecretNameField, func(rawObj client.Object) []string {
// Extract the secret name from the spec, if one is provided
cr := rawObj.(*clientv1.OpenStackClient)
if cr.Spec.CaBundleSecretName == "" {
return nil
}
return []string{cr.Spec.CaBundleSecretName}
}); err != nil {
return err
}
// index openStackConfigMap
if err := mgr.GetFieldIndexer().IndexField(ctx, &clientv1.OpenStackClient{}, openStackConfigMapField, func(rawObj client.Object) []string {
// Extract the configmap name from the spec, if one is provided
cr := rawObj.(*clientv1.OpenStackClient)
if cr.Spec.OpenStackConfigMap == nil {
return nil
}
if *cr.Spec.OpenStackConfigMap == "" {
return nil
}
return []string{*cr.Spec.OpenStackConfigMap}
}); err != nil {
return err
}
// index openStackConfigSecret
if err := mgr.GetFieldIndexer().IndexField(ctx, &clientv1.OpenStackClient{}, openStackConfigSecretField, func(rawObj client.Object) []string {
// Extract the configmap name from the spec, if one is provided
cr := rawObj.(*clientv1.OpenStackClient)
if cr.Spec.OpenStackConfigSecret == nil {
return nil
}
if *cr.Spec.OpenStackConfigSecret == "" {
return nil
}
return []string{*cr.Spec.OpenStackConfigSecret}
}); err != nil {
return err
}
// index mcpCertSecretName so MCP cert rotation (secret content change) by
// the control plane triggers a reconcile and the sidecar pod is refreshed
if err := mgr.GetFieldIndexer().IndexField(ctx, &clientv1.OpenStackClient{}, mcpCertSecretNameField, func(rawObj client.Object) []string {
cr := rawObj.(*clientv1.OpenStackClient)
if cr.Spec.MCPCertSecretName == "" {
return nil
}
return []string{cr.Spec.MCPCertSecretName}
}); err != nil {
return err
}
Log := r.GetLogger(ctx)
metricStorageFn := func(ctx context.Context, o client.Object) []reconcile.Request {
result := []reconcile.Request{}
// get all openstackclient CRs
openstackclients := &clientv1.OpenStackClientList{}
listOpts := []client.ListOption{
client.InNamespace(o.GetNamespace()),
}
if err := r.List(ctx, openstackclients, listOpts...); err != nil {
Log.Error(err, "Unable to retrieve OpenstackClient CRs %v")
return nil
}
for _, cr := range openstackclients.Items {
name := client.ObjectKey{
Namespace: o.GetNamespace(),
Name: cr.Name,
}
Log.Info(fmt.Sprintf("OpenStackClient %s will be reconciled, because a MetricStorage %s changed", cr.Name, o.GetName()))
result = append(result, reconcile.Request{NamespacedName: name})
}
if len(result) > 0 {
return result
}
return nil
}
return ctrl.NewControllerManagedBy(mgr).
For(&clientv1.OpenStackClient{}).
Owns(&corev1.Pod{}).
Owns(&corev1.ServiceAccount{}).
Owns(&corev1.ConfigMap{}).
Owns(&corev1.Service{}).
Owns(&networkingv1.NetworkPolicy{}).
Owns(&rbacv1.Role{}).
Owns(&rbacv1.RoleBinding{}).
Watches(
&corev1.Secret{},
handler.EnqueueRequestsFromMapFunc(r.findObjectsForSrc),
builder.WithPredicates(predicate.ResourceVersionChangedPredicate{}),
).
Watches(
&corev1.ConfigMap{},
handler.EnqueueRequestsFromMapFunc(r.findObjectsForSrc),
builder.WithPredicates(predicate.ResourceVersionChangedPredicate{}),
).
Watches(
// Reconcile all openstackclients when a MetricStorage changes.
// This is needed to ensure the observability client is
// configured correctly when tls is enabled or disabled.
&telemetryv1.MetricStorage{},
handler.EnqueueRequestsFromMapFunc(metricStorageFn),
).
Complete(r)
}
func (r *OpenStackClientReconciler) findObjectsForSrc(ctx context.Context, src client.Object) []reconcile.Request {
requests := []reconcile.Request{}
Log := r.GetLogger(context.Background())
for _, field := range allWatchFields {
crList := &clientv1.OpenStackClientList{}
listOps := &client.ListOptions{
FieldSelector: fields.OneTermEqualSelector(field, src.GetName()),
Namespace: src.GetNamespace(),
}
err := r.List(ctx, crList, listOps)
if err != nil {
Log.Error(err, fmt.Sprintf("listing %s for field: %s - %s", crList.GroupVersionKind().Kind, field, src.GetNamespace()))
return requests
}
for _, item := range crList.Items {
Log.Info(fmt.Sprintf("input source %s changed, reconcile: %s - %s", src.GetName(), item.GetName(), item.GetNamespace()))
requests = append(requests,
reconcile.Request{
NamespacedName: types.NamespacedName{
Name: item.GetName(),
Namespace: item.GetNamespace(),
},
},
)
}
}
return requests
}