Skip to content

Commit

Permalink
Programmatic Tenant prefix for the Capsule namespaces
Browse files Browse the repository at this point in the history
  • Loading branch information
prometherion committed Aug 6, 2020
1 parent 941bddb commit a9e0c4c
Show file tree
Hide file tree
Showing 3 changed files with 125 additions and 1 deletion.
17 changes: 17 additions & 0 deletions config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,23 @@ webhooks:
- CREATE
resources:
- namespaces
- clientConfig:
caBundle: Cg==
service:
name: webhook-service
namespace: system
path: /mutate-v1-namespace-tenant-prefix
failurePolicy: Fail
name: prefix.namespace.capsule.clastix.io
rules:
- apiGroups:
- ""
apiVersions:
- v1
operations:
- CREATE
resources:
- namespaces

---
apiVersion: admissionregistration.k8s.io/v1beta1
Expand Down
13 changes: 12 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import (
"github.com/clastix/capsule/pkg/webhook/network_policies"
"github.com/clastix/capsule/pkg/webhook/owner_reference"
"github.com/clastix/capsule/pkg/webhook/pvc"
"github.com/clastix/capsule/pkg/webhook/tenant_prefix"
"github.com/clastix/capsule/version"
// +kubebuilder:scaffold:imports
)
Expand All @@ -66,12 +67,16 @@ func printVersion() {
func main() {
var metricsAddr string
var enableLeaderElection bool
var forceTenantPrefix bool
var v bool

flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.BoolVar(&v, "version", false, "Print the Capsule version and exit")
flag.BoolVar(&forceTenantPrefix, "force-tenant-prefix", false, "Enforce at Namespace creation the Tenant prefix to the resource name, +" +
"separated by a dash. This is useful to avoid Namespace name collision in a public CaaS environment.")
flag.Parse()

ctrl.SetLogger(zap.New(zap.UseDevMode(true)))
Expand Down Expand Up @@ -104,7 +109,13 @@ func main() {
// +kubebuilder:scaffold:builder

//webhooks
err = webhook.Register(mgr, &ingress.ExtensionIngress{}, &ingress.NetworkIngress{}, pvc.Webhook{}, &owner_reference.Webhook{}, &namespace_quota.Webhook{}, network_policies.Webhook{})
wl := make([]webhook.Webhook, 0)
wl = append(wl, &ingress.ExtensionIngress{}, &ingress.NetworkIngress{}, pvc.Webhook{}, &owner_reference.Webhook{}, &namespace_quota.Webhook{}, network_policies.Webhook{})
if forceTenantPrefix {
setupLog.Info("Enabling the Namespace Tenant Prefix webhook")
wl = append(wl, tenant_prefix.Webhook{})
}
err = webhook.Register(mgr, wl...)
if err != nil {
setupLog.Error(err, "unable to setup webhooks")
os.Exit(1)
Expand Down
96 changes: 96 additions & 0 deletions pkg/webhook/tenant_prefix/patching.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
Copyright 2020 Clastix Labs.
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 tenant_prefix

import (
"context"
"encoding/json"
"fmt"
"net/http"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

"github.com/clastix/capsule/api/v1alpha1"
"github.com/clastix/capsule/pkg/webhook"
)

// +kubebuilder:webhook:path=/mutate-v1-namespace-tenant-prefix,mutating=true,failurePolicy=fail,groups="",resources=namespaces,verbs=create,versions=v1,name=prefix.namespace.capsule.clastix.io

type Webhook struct {
}

func (o Webhook) GetHandler() webhook.Handler {
return &handler{}
}

func (o Webhook) GetName() string {
return "OwnerReference"
}

func (o Webhook) GetPath() string {
return "/mutate-v1-namespace-tenant-prefix"
}

type handler struct {
}

func (r *handler) OnCreate(ctx context.Context, req admission.Request, clt client.Client, decoder *admission.Decoder) admission.Response {
ns := &corev1.Namespace{}
if err := decoder.Decode(req, ns); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}

t := &v1alpha1.Tenant{}
for _, or := range ns.ObjectMeta.OwnerReferences {
// retrieving the selected Tenant
if err := clt.Get(ctx, types.NamespacedName{Name: or.Name}, t); err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
}

o, _ := json.Marshal(ns.DeepCopy())
ns.SetName(fmt.Sprintf("%s-%s", t.GetName(), ns.GetName()))
c, _ := json.Marshal(ns)

return admission.PatchResponseFromRaw(o, c)
}

func (r *handler) OnDelete(ctx context.Context, req admission.Request, client client.Client, decoder *admission.Decoder) admission.Response {
return admission.Allowed("")
}

func (r *handler) OnUpdate(ctx context.Context, req admission.Request, client client.Client, decoder *admission.Decoder) admission.Response {
return admission.Allowed("")
}

func (r *handler) patchResponseForOwnerRef(tenant *v1alpha1.Tenant, ns *corev1.Namespace) admission.Response {
scheme := runtime.NewScheme()
_ = v1alpha1.AddToScheme(scheme)
_ = corev1.AddToScheme(scheme)

o, _ := json.Marshal(ns.DeepCopy())
if err := controllerutil.SetControllerReference(tenant, ns, scheme); err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
c, _ := json.Marshal(ns)
return admission.PatchResponseFromRaw(o, c)
}

0 comments on commit a9e0c4c

Please sign in to comment.