Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(webhook): cleanup validatingconfig on openebs namespace deletion #248

Merged
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
29 changes: 25 additions & 4 deletions pkg/webhook/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,17 @@ var (
Ignore = admissionregistration.Ignore
// Fail means that an error calling the webhook causes the admission to fail.
Fail = admissionregistration.Fail
// SideEffectClassNone means that calling the webhook will have no side effects.
SideEffectClassNone = v1beta1.SideEffectClassNone
// WebhookFailurePolicye represents failure policy env name to make it configurable
// via ENV
WebhookFailurePolicy = "ADMISSION_WEBHOOK_FAILURE_POLICY"
// transformation function lists to upgrade webhook resources
transformSecret = []transformSecretFunc{}
transformSvc = []transformSvcFunc{}
transformConfig = []transformConfigFunc{}
transformSecret = []transformSecretFunc{}
transformSvc = []transformSvcFunc{}
transformConfig = []transformConfigFunc{
addNSWithDeleteRule,
}
cvcRuleWithOperations = v1beta1.RuleWithOperations{
Operations: []v1beta1.OperationType{
v1beta1.Update,
Expand All @@ -90,6 +94,16 @@ var (
Resources: []string{"cstorvolumeconfigs"},
},
}
nsRuleWithOperations = v1beta1.RuleWithOperations{
Operations: []v1beta1.OperationType{
v1beta1.Delete,
},
Rule: v1beta1.Rule{
APIGroups: []string{"*"},
APIVersions: []string{"*"},
Resources: []string{"namespaces"},
},
}
)

// createWebhookService creates our webhook Service resource if it does not
Expand Down Expand Up @@ -202,6 +216,7 @@ func (c *client) createAdmissionValidatingConfig(
},
},
cvcRuleWithOperations,
nsRuleWithOperations,
},
ClientConfig: admissionregistration.WebhookClientConfig{
Service: &admissionregistration.ServiceReference{
Expand All @@ -211,7 +226,7 @@ func (c *client) createAdmissionValidatingConfig(
},
CABundle: signingCert,
},
// SideEffects: &sideEffectClass,
SideEffects: &SideEffectClassNone,
// AdmissionReviewVersions: []string{"v1"},
TimeoutSeconds: &five,
FailurePolicy: failurePolicy(),
Expand Down Expand Up @@ -423,6 +438,12 @@ func getOpenebsNamespace() (string, error) {
return ns, nil
}

func addNSWithDeleteRule(config *v1beta1.ValidatingWebhookConfiguration) {
if IsCurrentLessThanNewVersion(config.Labels[string(types.OpenEBSVersionLabelKey)], "2.5.0") {
config.Webhooks[0].Rules = append(config.Webhooks[0].Rules, nsRuleWithOperations)
}
}

// GetAdmissionName return the admission server name
func GetAdmissionName() (string, error) {
admissionName, found := os.LookupEnv(AdmissionNameEnvVar)
Expand Down
69 changes: 69 additions & 0 deletions pkg/webhook/namespace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
Copyright 2021 The OpenEBS Authors.

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 webhook

import (
"fmt"

"k8s.io/api/admission/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog"
)

func (wh *webhook) validateNamespace(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
req := ar.Request
response := &v1beta1.AdmissionResponse{}
response.Allowed = true
openebsNamespace, err := getOpenebsNamespace()
if err != nil {
response.Allowed = false
response.Result = &metav1.Status{
Message: fmt.Sprintf("error getting OPENEBS_NAMESPACE env %s: %v", req.Name, err.Error()),
}
return response
}
// validates only if requested operation is DELETE
if openebsNamespace == req.Name && req.Operation == v1beta1.Delete {
return wh.validateNamespaceDeleteRequest(req)
}
klog.V(2).Info("Admission wehbook for Namespace module not " +
"configured for operations other than DELETE")
return response
}

func (wh *webhook) validateNamespaceDeleteRequest(req *v1beta1.AdmissionRequest) *v1beta1.AdmissionResponse {
response := &v1beta1.AdmissionResponse{}
response.Allowed = true

// ignore the Delete request of Namespace if resource name is empty
if req.Name == "" {
return response
}
// Delete the validatingWebhookConfiguration only if its a delete request to
// delete openebs namespace
err := wh.kubeClient.AdmissionregistrationV1().
ValidatingWebhookConfigurations().
Delete(validatorWebhook, &metav1.DeleteOptions{})
if err != nil {
response.Allowed = false
response.Result = &metav1.Status{
Message: err.Error(),
}
return response
}
return response
}
21 changes: 20 additions & 1 deletion pkg/webhook/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@

package webhook

import "fmt"
import (
"fmt"
"strconv"
"strings"
)

const (
unit = 1024
Expand All @@ -33,3 +37,18 @@ func ByteCount(b uint64) string {
return fmt.Sprintf("%d%c",
uint64(b)/uint64(div), "KMGTPE"[index])
}

// if currentversion is less `<` then new version (return true in case of equal version)
// TODO use version lib to properly handle versions https://github.com/hashicorp/go-version
func IsCurrentLessThanNewVersion(old, new string) bool {
oldVersions := strings.Split(strings.Split(old, "-")[0], ".")
newVersions := strings.Split(strings.Split(new, "-")[0], ".")
for i := 0; i < len(oldVersions); i++ {
oldVersion, _ := strconv.Atoi(oldVersions[i])
newVersion, _ := strconv.Atoi(newVersions[i])
if oldVersion > newVersion {
return false
}
}
return true
}
6 changes: 5 additions & 1 deletion pkg/webhook/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,13 +182,16 @@ func validationRequired(ignoredList []string, metadata *metav1.ObjectMeta) bool
return required
}

// validate validates the persistentvolumeclaim(PVC) create, delete request
// validate validates the different openebs resource related operations
func (wh *webhook) validate(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
req := ar.Request
response := &v1beta1.AdmissionResponse{}
response.Allowed = true
klog.Info("Admission webhook request received")
switch req.Kind.Kind {
case "Namespace":
klog.V(2).Infof("Admission webhook request for type %s", req.Kind.Kind)
return wh.validateNamespace(ar)
case "PersistentVolumeClaim":
klog.V(2).Infof("Admission webhook request for type %s", req.Kind.Kind)
return wh.validatePVC(ar)
Expand All @@ -198,6 +201,7 @@ func (wh *webhook) validate(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionRespo
case "CStorVolumeConfig":
klog.V(2).Infof("Admission webhook request for type %s", req.Kind.Kind)
return wh.validateCVC(ar)

default:
klog.V(2).Infof("Admission webhook not configured for type %s", req.Kind.Kind)
return response
Expand Down