Skip to content
This repository has been archived by the owner on Sep 16, 2024. It is now read-only.

refactor: move schema validation/default from extemsion api to webhook #2276

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
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
32 changes: 0 additions & 32 deletions pkg/extensionapis/walrus/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package walrus

import (
"context"
"strings"

meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
Expand All @@ -12,10 +11,7 @@ import (

walrus "github.com/seal-io/walrus/pkg/apis/walrus/v1"
walruscore "github.com/seal-io/walrus/pkg/apis/walruscore/v1"
"github.com/seal-io/walrus/pkg/apistatus"
"github.com/seal-io/walrus/pkg/extensionapi"
"github.com/seal-io/walrus/pkg/systemmeta"
"github.com/seal-io/walrus/pkg/templates/kubehelper"
)

// SchemaHandler handles v1.Schema objects.
Expand Down Expand Up @@ -96,31 +92,3 @@ func (h *SchemaHandler) CastObjectTo(do *walrus.Schema) (uo *walruscore.Schema)
func (h *SchemaHandler) CastObjectFrom(uo *walruscore.Schema) (do *walrus.Schema) {
return (*walrus.Schema)(uo)
}

func (h *SchemaHandler) OnUpdate(ctx context.Context, obj, _ runtime.Object, opts ctrlcli.UpdateOptions) (runtime.Object, error) {
s := obj.(*walrus.Schema)

if apistatus.SchemaStatusReset.IsTrue(obj) {
var (
ouis walruscore.Schema
ouisKey = ctrlcli.ObjectKey{
Namespace: s.Namespace,
Name: strings.TrimSuffix(s.Name, walruscore.NameSuffixUISchema) + walruscore.NameSuffixOriginalUISchema,
}
)
err := h.client.Get(ctx, ouisKey, &ouis)
if err != nil {
return nil, err
}

apistatus.SchemaStatusReset.False(s, "", "")
systemmeta.UnnoteResource(s)
s.Status.Value = ouis.Status.Value
} else {
systemmeta.NoteResource(s, "", map[string]string{kubehelper.SchemaUserEditedNote: "true"})
}

uo := h.CastObjectTo(s)
err := h.client.Update(ctx, uo, &opts)
return h.CastObjectFrom(uo), err
}
12 changes: 11 additions & 1 deletion pkg/templates/kubehelper/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,12 @@ func GenTemplateVersion(
func createOrUpdateSchema(ctx context.Context, loopbackKubeCli clientset.Interface, t *walruscore.Template, name string, data []byte) error {
cli := loopbackKubeCli.WalruscoreV1().Schemas(t.Namespace)

var es *walruscore.Schema
var (
es *walruscore.Schema
editBySystemAnn = map[string]string{
SchemaUserEditedNote: "false",
}
)
{
es = &walruscore.Schema{
ObjectMeta: meta.ObjectMeta{
Expand All @@ -101,9 +106,14 @@ func createOrUpdateSchema(ctx context.Context, loopbackKubeCli clientset.Interfa
},
}
kubemeta.ControlOn(es, t, walruscore.SchemeGroupVersion.WithKind("Template"))
systemmeta.NoteResource(es, "", editBySystemAnn)
}

alignFn := func(as *walruscore.Schema) (*walruscore.Schema, bool, error) {
if systemmeta.DescribeResourceNote(as, SchemaUserEditedNote) != "true" {
systemmeta.NoteResource(as, "", editBySystemAnn)
}

if bytes.Equal(as.Status.Value.Raw, data) {
return as, true, nil
}
Expand Down
1 change: 1 addition & 0 deletions pkg/webhooks/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ var (
new(walruscore.ConnectorBindingWebhook),
new(walruscore.ResourceDefinitionWebhook),
new(walruscore.TemplateWebhook),
new(walruscore.SchemaWebhook),
}
cfgGetters = []_WebhookConfigurationsGetter{
walruscore.GetWebhookConfigurations,
Expand Down
107 changes: 107 additions & 0 deletions pkg/webhooks/walruscore/schema.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package walruscore

import (
"context"
"encoding/json"
"fmt"
"strings"

"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrlcli "sigs.k8s.io/controller-runtime/pkg/client"
ctrlwebhook "sigs.k8s.io/controller-runtime/pkg/webhook"
ctrladmission "sigs.k8s.io/controller-runtime/pkg/webhook/admission"

walruscore "github.com/seal-io/walrus/pkg/apis/walruscore/v1"
"github.com/seal-io/walrus/pkg/apistatus"
"github.com/seal-io/walrus/pkg/systemmeta"
"github.com/seal-io/walrus/pkg/templates/api"
"github.com/seal-io/walrus/pkg/templates/kubehelper"
"github.com/seal-io/walrus/pkg/webhook"
)

// SchemaWebhook hooks a v1.Schema object.
//
// nolint: lll
// nolint: lll
// +k8s:webhook-gen:mutating:group="walruscore.seal.io",version="v1",resource="schemas",scope="Namespaced"
// +k8s:webhook-gen:mutating:operations=["UPDATE"],failurePolicy="Fail",sideEffects="None",matchPolicy="Equivalent",timeoutSeconds=10
// +k8s:webhook-gen:validating:group="walruscore.seal.io",version="v1",resource="schemas",scope="Namespaced"
// +k8s:webhook-gen:validating:operations=["UPDATE"],failurePolicy="Fail",sideEffects="None",matchPolicy="Equivalent",timeoutSeconds=10
type SchemaWebhook struct {
webhook.DefaultCustomValidator

client ctrlcli.Client
}

func (r *SchemaWebhook) SetupWebhook(_ context.Context, opts webhook.SetupOptions) (runtime.Object, error) {
r.client = opts.Manager.GetClient()

return &walruscore.Schema{}, nil
}

var (
_ ctrlwebhook.CustomValidator = (*SchemaWebhook)(nil)
_ ctrlwebhook.CustomDefaulter = (*SchemaWebhook)(nil)
)

func (r *SchemaWebhook) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) (ctrladmission.Warnings, error) {
s := newObj.(*walruscore.Schema)

if s.Status.Value.Size() == 0 {
return nil, field.Invalid(
field.NewPath("status.value"), "", "empty schema")
}

var ws api.WrapSchema
err := json.Unmarshal(s.Status.Value.Raw, &ws)
if err != nil {
return nil, field.Invalid(
field.NewPath("status.value"), "", err.Error())
}

err = ws.Validate()
if err != nil {
return nil, field.Invalid(
field.NewPath("status.value"), "", err.Error())
}

return nil, nil
}

func (r *SchemaWebhook) Default(ctx context.Context, obj runtime.Object) error {
s := obj.(*walruscore.Schema)

// Skip template schema and original ui schema.
if strings.HasSuffix(s.Name, walruscore.NameSuffixTemplateSchema) || strings.HasSuffix(s.Name, walruscore.NameSuffixOriginalUISchema) {
return nil
}

switch {
case systemmeta.DescribeResourceNote(s, kubehelper.SchemaUserEditedNote) == "false":
// System edit.
case apistatus.SchemaStatusReset.IsTrue(obj):
// User reset.
var (
ouis walruscore.Schema
ouisKey = ctrlcli.ObjectKey{
Namespace: s.Namespace,
Name: strings.TrimSuffix(s.Name, walruscore.NameSuffixUISchema) + walruscore.NameSuffixOriginalUISchema,
}
)
err := r.client.Get(ctx, ouisKey, &ouis)
if err != nil {
return fmt.Errorf("failed to find %s: %w", ouisKey.String(), err)
}

apistatus.SchemaStatusReset.False(s, "", "")
systemmeta.UnnoteResource(s)
s.Status.Value = ouis.Status.Value

default:
// User edit.
systemmeta.NoteResource(s, "", map[string]string{kubehelper.SchemaUserEditedNote: "true"})
}

return nil
}
94 changes: 94 additions & 0 deletions pkg/webhooks/walruscore/zz_generated.webhooks.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading