-
Notifications
You must be signed in to change notification settings - Fork 47
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1199 from jcanocan/vm-delete-protection
feat: Add VM delete protection
- Loading branch information
Showing
10 changed files
with
433 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
package vm_delete_protection | ||
|
||
import ( | ||
"fmt" | ||
|
||
admissionregistrationv1 "k8s.io/api/admissionregistration/v1" | ||
utilruntime "k8s.io/apimachinery/pkg/util/runtime" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
|
||
"kubevirt.io/ssp-operator/internal/common" | ||
"kubevirt.io/ssp-operator/internal/operands" | ||
) | ||
|
||
// Define RBAC rules needed by this operand: | ||
// +kubebuilder:rbac:groups=admissionregistration.k8s.io,resources=validatingadmissionpolicies;validatingadmissionpolicybindings,verbs=get;list;create;watch;update;delete | ||
|
||
const ( | ||
operandName = "vm-delete-protection" | ||
operandComponent = common.AppComponentVMDeletionProtection | ||
virtualMachineDeleteProtectionPolicyName = "kubevirt-vm-deletion-protection" | ||
) | ||
|
||
func init() { | ||
utilruntime.Must(admissionregistrationv1.AddToScheme(common.Scheme)) | ||
} | ||
|
||
func WatchClusterTypes() []operands.WatchType { | ||
return []operands.WatchType{ | ||
{Object: &admissionregistrationv1.ValidatingAdmissionPolicy{}}, | ||
{Object: &admissionregistrationv1.ValidatingAdmissionPolicyBinding{}}, | ||
} | ||
} | ||
|
||
type VMDeleteProtection struct{} | ||
|
||
var _ operands.Operand = &VMDeleteProtection{} | ||
|
||
func New() operands.Operand { return &VMDeleteProtection{} } | ||
|
||
func (v *VMDeleteProtection) WatchTypes() []operands.WatchType { return nil } | ||
|
||
func (v *VMDeleteProtection) WatchClusterTypes() []operands.WatchType { return WatchClusterTypes() } | ||
|
||
func (v *VMDeleteProtection) Reconcile(request *common.Request) ([]common.ReconcileResult, error) { | ||
return common.CollectResourceStatus(request, | ||
reconcileVAP, | ||
reconcileVAPB, | ||
) | ||
} | ||
|
||
func (v *VMDeleteProtection) Cleanup(request *common.Request) ([]common.CleanupResult, error) { | ||
return common.DeleteAll(request, | ||
newValidatingAdmissionPolicy(), | ||
newValidatingAdmissionPolicyBinding(), | ||
) | ||
} | ||
|
||
func (v *VMDeleteProtection) Name() string { return operandName } | ||
|
||
func reconcileVAP(request *common.Request) (common.ReconcileResult, error) { | ||
return common.CreateOrUpdate(request). | ||
ClusterResource(newValidatingAdmissionPolicy()). | ||
WithAppLabels(operandName, operandComponent). | ||
UpdateFunc(func(expected, found client.Object) { | ||
foundVAP := found.(*admissionregistrationv1.ValidatingAdmissionPolicy) | ||
expectedVAP := expected.(*admissionregistrationv1.ValidatingAdmissionPolicy) | ||
|
||
foundVAP.Spec = expectedVAP.Spec | ||
}). | ||
StatusFunc(func(resource client.Object) common.ResourceStatus { | ||
vap := resource.(*admissionregistrationv1.ValidatingAdmissionPolicy) | ||
if vap.Status.TypeChecking == nil { | ||
msg := fmt.Sprintf("Delete protection VAP type checking in progress") | ||
return common.ResourceStatus{ | ||
Progressing: &msg, | ||
NotAvailable: &msg, | ||
Degraded: &msg, | ||
} | ||
} | ||
|
||
if len(vap.Status.TypeChecking.ExpressionWarnings) != 0 { | ||
msg := fmt.Sprintf("Incorrect VM delete protection VAP CEL expression %v", | ||
vap.Status.TypeChecking) | ||
return common.ResourceStatus{ | ||
NotAvailable: &msg, | ||
Degraded: &msg, | ||
} | ||
} | ||
return common.ResourceStatus{} | ||
}). | ||
Reconcile() | ||
} | ||
|
||
func reconcileVAPB(request *common.Request) (common.ReconcileResult, error) { | ||
return common.CreateOrUpdate(request). | ||
ClusterResource(newValidatingAdmissionPolicyBinding()). | ||
WithAppLabels(operandName, operandComponent). | ||
UpdateFunc(func(expected, found client.Object) { | ||
foundVAPB := found.(*admissionregistrationv1.ValidatingAdmissionPolicyBinding) | ||
expectedVAPB := expected.(*admissionregistrationv1.ValidatingAdmissionPolicyBinding) | ||
|
||
foundVAPB.Spec = expectedVAPB.Spec | ||
}). | ||
Reconcile() | ||
} |
134 changes: 134 additions & 0 deletions
134
internal/operands/vm-delete-protection/reconcile_test.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
package vm_delete_protection | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
|
||
. "github.com/onsi/ginkgo/v2" | ||
. "github.com/onsi/gomega" | ||
|
||
"github.com/google/cel-go/cel" | ||
admissionregistrationv1 "k8s.io/api/admissionregistration/v1" | ||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
"k8s.io/apimachinery/pkg/types" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
"sigs.k8s.io/controller-runtime/pkg/client/fake" | ||
"sigs.k8s.io/controller-runtime/pkg/reconcile" | ||
|
||
ssp "kubevirt.io/ssp-operator/api/v1beta2" | ||
"kubevirt.io/ssp-operator/internal/common" | ||
. "kubevirt.io/ssp-operator/internal/test-utils" | ||
) | ||
|
||
var _ = Describe("VM delete protection operand", func() { | ||
const ( | ||
namespace = "kubevirt" | ||
name = "test-ssp" | ||
) | ||
|
||
var ( | ||
request common.Request | ||
operand = New() | ||
key = client.ObjectKey{Name: virtualMachineDeleteProtectionPolicyName} | ||
) | ||
|
||
BeforeEach(func() { | ||
client := fake.NewClientBuilder().WithScheme(common.Scheme).Build() | ||
request = common.Request{ | ||
Request: reconcile.Request{ | ||
NamespacedName: types.NamespacedName{ | ||
Namespace: namespace, | ||
Name: name, | ||
}, | ||
}, | ||
Client: client, | ||
Context: context.Background(), | ||
Instance: &ssp.SSP{ | ||
TypeMeta: metav1.TypeMeta{ | ||
Kind: "SSP", | ||
APIVersion: ssp.GroupVersion.String(), | ||
}, | ||
ObjectMeta: metav1.ObjectMeta{ | ||
Name: name, | ||
Namespace: namespace, | ||
}, | ||
}, | ||
VersionCache: common.VersionCache{}, | ||
} | ||
}) | ||
|
||
It("should create VM deletion protection resources", func() { | ||
_, err := operand.Reconcile(&request) | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
ExpectResourceExists(newValidatingAdmissionPolicy(), request) | ||
ExpectResourceExists(newValidatingAdmissionPolicyBinding(), request) | ||
}) | ||
|
||
It("should update VAP spec if changed", func() { | ||
_, err := operand.Reconcile(&request) | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
vap := &admissionregistrationv1.ValidatingAdmissionPolicy{} | ||
|
||
Expect(request.Client.Get(request.Context, key, vap)).To(Succeed()) | ||
|
||
vap.Spec.Variables = []admissionregistrationv1.Variable{ | ||
{ | ||
Name: "test-variable", | ||
Expression: `test-expression`, | ||
}, | ||
} | ||
|
||
Expect(request.Client.Update(request.Context, vap)).ToNot(HaveOccurred()) | ||
|
||
_, err = operand.Reconcile(&request) | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
Expect(request.Client.Get(request.Context, key, vap)).To(Succeed()) | ||
Expect(vap.Spec).To(Equal(newValidatingAdmissionPolicy().Spec)) | ||
|
||
}) | ||
|
||
It("should update VAPB spec if changed", func() { | ||
_, err := operand.Reconcile(&request) | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
vapb := &admissionregistrationv1.ValidatingAdmissionPolicyBinding{} | ||
|
||
Expect(request.Client.Get(request.Context, key, vapb)).To(Succeed()) | ||
|
||
vapb.Spec.ValidationActions = []admissionregistrationv1.ValidationAction{ | ||
admissionregistrationv1.Warn, | ||
} | ||
|
||
Expect(request.Client.Update(request.Context, vapb)).To(Succeed()) | ||
|
||
_, err = operand.Reconcile(&request) | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
Expect(request.Client.Get(request.Context, key, vapb)).To(Succeed()) | ||
Expect(vapb.Spec).To(Equal(newValidatingAdmissionPolicyBinding().Spec)) | ||
}) | ||
|
||
It("should create one valid CEL expression", func() { | ||
_, err := operand.Reconcile(&request) | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
vap := &admissionregistrationv1.ValidatingAdmissionPolicy{} | ||
|
||
Expect(request.Client.Get(request.Context, key, vap)).To(Succeed()) | ||
Expect(vap.Spec.Validations).To(HaveLen(1)) | ||
|
||
celEnv, err := cel.NewEnv() | ||
Expect(err).ToNot(HaveOccurred()) | ||
|
||
_, issues := celEnv.Parse(vap.Spec.Validations[0].Expression) | ||
Expect(issues.Err()).ToNot(HaveOccurred()) | ||
}) | ||
}) | ||
|
||
func TestVMDeleteProtection(t *testing.T) { | ||
RegisterFailHandler(Fail) | ||
RunSpecs(t, "VM Delete Protection Suite") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package vm_delete_protection | ||
|
||
import ( | ||
admissionregistrationv1 "k8s.io/api/admissionregistration/v1" | ||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
"k8s.io/utils/ptr" | ||
kubevirt "kubevirt.io/api/core" | ||
kubevirtv1 "kubevirt.io/api/core/v1" | ||
) | ||
|
||
const vmDeleteProtectionCELExpression = `(!has(oldObject.metadata.labels) || !(variables.label in oldObject.metadata.labels) || !oldObject.metadata.labels[variables.label].matches('^(true|True)$'))` | ||
|
||
func newValidatingAdmissionPolicy() *admissionregistrationv1.ValidatingAdmissionPolicy { | ||
var apiVersions []string | ||
for _, version := range kubevirtv1.ApiSupportedVersions { | ||
apiVersions = append(apiVersions, version.Name) | ||
} | ||
|
||
return &admissionregistrationv1.ValidatingAdmissionPolicy{ | ||
ObjectMeta: metav1.ObjectMeta{ | ||
Name: virtualMachineDeleteProtectionPolicyName, | ||
}, | ||
Spec: admissionregistrationv1.ValidatingAdmissionPolicySpec{ | ||
FailurePolicy: ptr.To(admissionregistrationv1.Fail), | ||
MatchConstraints: &admissionregistrationv1.MatchResources{ | ||
ResourceRules: []admissionregistrationv1.NamedRuleWithOperations{ | ||
{ | ||
RuleWithOperations: admissionregistrationv1.RuleWithOperations{ | ||
Operations: []admissionregistrationv1.OperationType{ | ||
admissionregistrationv1.Delete, | ||
}, | ||
Rule: admissionregistrationv1.Rule{ | ||
APIGroups: []string{kubevirt.GroupName}, | ||
APIVersions: apiVersions, | ||
Resources: []string{"virtualmachines"}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
Variables: []admissionregistrationv1.Variable{ | ||
{ | ||
Name: "label", | ||
Expression: `string('kubevirt.io/vm-delete-protection')`, | ||
}, | ||
}, | ||
Validations: []admissionregistrationv1.Validation{ | ||
{ | ||
Expression: vmDeleteProtectionCELExpression, | ||
MessageExpression: `'VirtualMachine ' + string(oldObject.metadata.name) + ' cannot be deleted, remove delete protection'`, | ||
}, | ||
}, | ||
}, | ||
} | ||
} | ||
|
||
func newValidatingAdmissionPolicyBinding() *admissionregistrationv1.ValidatingAdmissionPolicyBinding { | ||
return &admissionregistrationv1.ValidatingAdmissionPolicyBinding{ | ||
ObjectMeta: metav1.ObjectMeta{ | ||
Name: virtualMachineDeleteProtectionPolicyName, | ||
}, | ||
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{ | ||
PolicyName: virtualMachineDeleteProtectionPolicyName, | ||
ValidationActions: []admissionregistrationv1.ValidationAction{ | ||
admissionregistrationv1.Deny, | ||
}, | ||
}, | ||
} | ||
} |
Oops, something went wrong.