Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,7 @@ resources:
kind: OpenStackBackupConfig
path: github.com/openstack-k8s-operators/openstack-operator/api/backup/v1beta1
version: v1beta1
webhooks:
validation: true
webhookVersion: v1
version: "3"
15 changes: 15 additions & 0 deletions api/backup/v1beta1/openstackbackupconfig_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@ limitations under the License.
package v1beta1

import (
"context"

condition "github.com/openstack-k8s-operators/lib-common/modules/common/condition"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// BackupLabelingPolicy controls whether backup labeling is active for a resource type
Expand Down Expand Up @@ -144,6 +147,18 @@ type OpenStackBackupConfigList struct {
Items []OpenStackBackupConfig `json:"items"`
}

// GetOpenStackBackupConfigs returns the OpenStackBackupConfig resources in the given namespace.
func GetOpenStackBackupConfigs(ctx context.Context, namespace string, c client.Client) (*OpenStackBackupConfigList, error) {
configList := &OpenStackBackupConfigList{}
listOpts := []client.ListOption{
client.InNamespace(namespace),
}
if err := c.List(ctx, configList, listOpts...); err != nil {
return nil, err
}
return configList, nil
}

func init() {
SchemeBuilder.Register(&OpenStackBackupConfig{}, &OpenStackBackupConfigList{})
}
20 changes: 20 additions & 0 deletions bindata/operator/operator.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,26 @@ metadata:
cert-manager.io/inject-ca-from: '{{ .OperatorNamespace }}/openstack-operator-serving-cert'
name: openstack-operator-validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
clientConfig:
service:
name: openstack-operator-webhook-service
namespace: '{{ .OperatorNamespace }}'
path: /validate-backup-openstack-org-v1beta1-openstackbackupconfig
failurePolicy: Fail
name: vopenstackbackupconfig-v1beta1.kb.io
rules:
- apiGroups:
- backup.openstack.org
apiVersions:
- v1beta1
operations:
- CREATE
- UPDATE
resources:
- openstackbackupconfigs
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
Expand Down
6 changes: 6 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import (
backupv1beta1 "github.com/openstack-k8s-operators/openstack-operator/api/backup/v1beta1"
backupcontroller "github.com/openstack-k8s-operators/openstack-operator/internal/controller/backup"

webhookbackupv1beta1 "github.com/openstack-k8s-operators/openstack-operator/internal/webhook/backup/v1beta1"
// +kubebuilder:scaffold:imports
certmgrv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
k8s_networkv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
Expand Down Expand Up @@ -425,6 +426,11 @@ func main() {
setupLog.Error(err, "unable to create webhook", "webhook", "OpenStackDataPlaneService")
os.Exit(1)
}
// nolint:goconst
if err := webhookbackupv1beta1.SetupOpenStackBackupConfigWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "OpenStackBackupConfig")
os.Exit(1)
}
checker = mgr.GetWebhookServer().StartedChecker()
}
// +kubebuilder:scaffold:builder
Expand Down
20 changes: 20 additions & 0 deletions config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,26 @@ kind: ValidatingWebhookConfiguration
metadata:
name: validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-backup-openstack-org-v1beta1-openstackbackupconfig
failurePolicy: Fail
name: vopenstackbackupconfig-v1beta1.kb.io
rules:
- apiGroups:
- backup.openstack.org
apiVersions:
- v1beta1
operations:
- CREATE
- UPDATE
resources:
- openstackbackupconfigs
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
Expand Down
15 changes: 13 additions & 2 deletions internal/openstack/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,26 @@ import (
// Automatically creates an OpenStackBackupConfig CR when OpenStackControlPlane is created
// Similar pattern to ReconcileVersion
func ReconcileBackupConfig(ctx context.Context, instance *corev1beta1.OpenStackControlPlane, helper *helper.Helper) (ctrl.Result, *backupv1beta1.OpenStackBackupConfig, error) {
Log := GetLogger(ctx)

// Check if a BackupConfig already exists (may have been pre-created by the user)
configList, err := backupv1beta1.GetOpenStackBackupConfigs(ctx, instance.Namespace, helper.GetClient())
if err != nil {
return ctrl.Result{}, nil, fmt.Errorf("failed to list OpenStackBackupConfigs: %w", err)
}
if len(configList.Items) > 0 {
existing := &configList.Items[0]
Log.Info("Using existing OpenStackBackupConfig", "name", existing.Name)
return ctrl.Result{}, existing, nil
}

backupConfig := &backupv1beta1.OpenStackBackupConfig{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Name,
Namespace: instance.Namespace,
},
}

Log := GetLogger(ctx)

defaultLabeling := backupv1beta1.BackupLabelingEnabled

op, err := controllerutil.CreateOrPatch(ctx, helper.GetClient(), backupConfig, func() error {
Expand Down
119 changes: 119 additions & 0 deletions internal/webhook/backup/v1beta1/openstackbackupconfig_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
Copyright 2026.

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 v1beta1 contains webhooks for backup API resources.
package v1beta1

import (
"context"
"fmt"

apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

backupv1beta1 "github.com/openstack-k8s-operators/openstack-operator/api/backup/v1beta1"
)

var openstackbackupconfiglog = logf.Log.WithName("openstackbackupconfig-resource")

var backupConfigWebhookClient client.Client

// SetupOpenStackBackupConfigWebhookWithManager registers the webhook for OpenStackBackupConfig in the manager.
func SetupOpenStackBackupConfigWebhookWithManager(mgr ctrl.Manager) error {
if backupConfigWebhookClient == nil {
backupConfigWebhookClient = mgr.GetClient()
}

return ctrl.NewWebhookManagedBy(mgr).For(&backupv1beta1.OpenStackBackupConfig{}).
WithValidator(&OpenStackBackupConfigCustomValidator{}).
Complete()
}

// +kubebuilder:webhook:path=/validate-backup-openstack-org-v1beta1-openstackbackupconfig,mutating=false,failurePolicy=fail,sideEffects=None,groups=backup.openstack.org,resources=openstackbackupconfigs,verbs=create;update,versions=v1beta1,name=vopenstackbackupconfig-v1beta1.kb.io,admissionReviewVersions=v1

// OpenStackBackupConfigCustomValidator struct is responsible for validating the OpenStackBackupConfig resource
// when it is created, updated, or deleted.
//
// NOTE: The +kubebuilder:object:generate=false marker prevents controller-gen from generating DeepCopy methods,
// as this struct is used only for temporary operations and does not need to be deeply copied.
type OpenStackBackupConfigCustomValidator struct{}

var _ webhook.CustomValidator = &OpenStackBackupConfigCustomValidator{}

// ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type OpenStackBackupConfig.
func (v *OpenStackBackupConfigCustomValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
backupConfig, ok := obj.(*backupv1beta1.OpenStackBackupConfig)
if !ok {
return nil, fmt.Errorf("expected an OpenStackBackupConfig object but got %T", obj)
}
openstackbackupconfiglog.Info("Validation for OpenStackBackupConfig upon creation", "name", backupConfig.GetName())

configList, err := backupv1beta1.GetOpenStackBackupConfigs(ctx, backupConfig.Namespace, backupConfigWebhookClient)
if err != nil {
return nil, apierrors.NewForbidden(
schema.GroupResource{
Group: backupv1beta1.GroupVersion.WithKind("OpenStackBackupConfig").Group,
Resource: backupv1beta1.GroupVersion.WithKind("OpenStackBackupConfig").Kind,
}, backupConfig.GetName(), &field.Error{
Type: field.ErrorTypeForbidden,
Detail: err.Error(),
},
Comment on lines +73 to +80

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really important, but is there some other type of general error that would make more sense here instead of Forbidden? Or is this just the pattern we've used in webhook error handling across all operators?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its the same as we also use in other places, like the osversion https://github.com/openstack-k8s-operators/openstack-operator/blob/main/api/core/v1beta1/openstackversion_webhook.go#L97 . maybe NewConflict is better. maybe we follow up to make them all the same.

)
}

if len(configList.Items) >= 1 {
return nil, apierrors.NewForbidden(
schema.GroupResource{
Group: backupv1beta1.GroupVersion.WithKind("OpenStackBackupConfig").Group,
Resource: backupv1beta1.GroupVersion.WithKind("OpenStackBackupConfig").Kind,
}, backupConfig.GetName(), &field.Error{
Type: field.ErrorTypeForbidden,
Detail: "Only one OpenStackBackupConfig instance is supported per namespace.",
},
)
}

return nil, nil
}

// ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type OpenStackBackupConfig.
func (v *OpenStackBackupConfigCustomValidator) ValidateUpdate(_ context.Context, _, newObj runtime.Object) (admission.Warnings, error) {
backupConfig, ok := newObj.(*backupv1beta1.OpenStackBackupConfig)
if !ok {
return nil, fmt.Errorf("expected an OpenStackBackupConfig object for the newObj but got %T", newObj)
}
openstackbackupconfiglog.Info("Validation for OpenStackBackupConfig upon update", "name", backupConfig.GetName())

return nil, nil
}

// ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type OpenStackBackupConfig.
func (v *OpenStackBackupConfigCustomValidator) ValidateDelete(_ context.Context, obj runtime.Object) (admission.Warnings, error) {
backupConfig, ok := obj.(*backupv1beta1.OpenStackBackupConfig)
if !ok {
return nil, fmt.Errorf("expected an OpenStackBackupConfig object but got %T", obj)
}
openstackbackupconfiglog.Info("Validation for OpenStackBackupConfig upon deletion", "name", backupConfig.GetName())

return nil, nil
}
39 changes: 39 additions & 0 deletions test/functional/ctlplane/openstackbackupconfig_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
. "github.com/onsi/gomega" //revive:disable:dot-imports

k8s_corev1 "k8s.io/api/core/v1"
k8s_errors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"

Expand Down Expand Up @@ -879,4 +880,42 @@ var _ = Describe("OpenStackBackupConfig controller", func() {
}, timeout, interval).Should(Succeed())
})
})

When("A second OpenStackBackupConfig is created in the same namespace", func() {
BeforeEach(func() {
backupConfigName = types.NamespacedName{
Name: "first-backup-config",
Namespace: namespace,
}

backupConfig := CreateBackupConfig(backupConfigName)
DeferCleanup(th.DeleteInstance, backupConfig)
})

It("Should be rejected by the webhook", func() {
secondConfig := &backupv1.OpenStackBackupConfig{
ObjectMeta: metav1.ObjectMeta{
Name: "second-backup-config",
Namespace: namespace,
},
Spec: backupv1.OpenStackBackupConfigSpec{
DefaultRestoreOrder: "10",
Secrets: backupv1.ResourceBackupConfig{
Labeling: backupLabelingPtr(backupv1.BackupLabelingEnabled),
},
ConfigMaps: backupv1.ResourceBackupConfig{
Labeling: backupLabelingPtr(backupv1.BackupLabelingEnabled),
ExcludeNames: []string{"kube-root-ca.crt", "openshift-service-ca.crt"},
},
NetworkAttachmentDefinitions: backupv1.ResourceBackupConfig{
Labeling: backupLabelingPtr(backupv1.BackupLabelingEnabled),
},
},
}
err := k8sClient.Create(ctx, secondConfig)
Expect(err).To(HaveOccurred())
Expect(k8s_errors.IsForbidden(err)).To(BeTrue())
Expect(err.Error()).To(ContainSubstring("Only one OpenStackBackupConfig instance is supported per namespace"))
})
})
})
3 changes: 3 additions & 0 deletions test/functional/ctlplane/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import (
mariadb_test "github.com/openstack-k8s-operators/mariadb-operator/api/test/helpers"
ovn_test "github.com/openstack-k8s-operators/ovn-operator/api/test/helpers"

backupwebhook "github.com/openstack-k8s-operators/openstack-operator/internal/webhook/backup/v1beta1"
clientwebhook "github.com/openstack-k8s-operators/openstack-operator/internal/webhook/client/v1beta1"
corewebhook "github.com/openstack-k8s-operators/openstack-operator/internal/webhook/core/v1beta1"
dataplanewebhook "github.com/openstack-k8s-operators/openstack-operator/internal/webhook/dataplane/v1beta1"
Expand Down Expand Up @@ -378,6 +379,8 @@ var _ = BeforeSuite(func() {
Expect(err).NotTo(HaveOccurred())
err = dataplanewebhook.SetupOpenStackDataPlaneNodeSetWebhookWithManager(k8sManager)
Expect(err).NotTo(HaveOccurred())
err = backupwebhook.SetupOpenStackBackupConfigWebhookWithManager(k8sManager)
Expect(err).NotTo(HaveOccurred())

core_ctrl.SetupVersionDefaults()
openstack.SetupServiceOperatorDefaults()
Expand Down
Loading