Skip to content

Commit

Permalink
Feat: add apply
Browse files Browse the repository at this point in the history
Signed-off-by: Yin Da <[email protected]>
  • Loading branch information
Somefive committed Jun 15, 2023
1 parent ac4f4eb commit 274bf1e
Show file tree
Hide file tree
Showing 10 changed files with 720 additions and 9 deletions.
53 changes: 53 additions & 0 deletions util/builder/option.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
Copyright 2023 The KubeVela 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 builder

// Option the generic type for option type T
type Option[T any] interface {
ApplyTo(*T)
}

// Constructor the constructor for option interface
type Constructor[T any] interface {
New() *T
}

// NewOptions create options T with given Option args. If T implements
// Constructor, it will call its construct function to initialize first
func NewOptions[T any](opts ...Option[T]) *T {
t := new(T)
if c, ok := any(t).(Constructor[T]); ok {
t = c.New()
}
ApplyTo(t, opts...)
return t
}

// ApplyTo run all option args for setting the options
func ApplyTo[T any](t *T, opts ...Option[T]) {
for _, opt := range opts {
opt.ApplyTo(t)
}
}

// OptionFn wrapper for ApplyTo function
type OptionFn[T any] func(*T)

// ApplyTo implements Option interface
func (in OptionFn[T]) ApplyTo(t *T) {
(in)(t)
}
47 changes: 47 additions & 0 deletions util/builder/option_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
Copyright 2023 The KubeVela 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 builder_test

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/kubevela/pkg/util/builder"
)

type B struct {
key string
val string
}

func (in *B) New() *B {
return &B{key: "key"}
}

type Suffix string

func (in Suffix) ApplyTo(b *B) {
b.key += string(in)
}

func TestOption(t *testing.T) {
opt := builder.OptionFn[B](func(b *B) { b.val = "val" })
b := builder.NewOptions[B](opt, Suffix("-x"))
require.Equal(t, "key-x", b.key)
require.Equal(t, "val", b.val)
}
35 changes: 35 additions & 0 deletions util/jsonutil/setter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
Copyright 2023 The KubeVela 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 jsonutil

// DropField remove field inside a given nested map
func DropField(obj map[string]any, fields ...string) {
if len(fields) == 0 {
return
}
var cur any = obj
for _, field := range fields[:len(fields)-1] {
if next, ok := cur.(map[string]any); ok {
cur = next[field]
} else {
return
}
}
if m, ok := cur.(map[string]any); ok {
delete(m, fields[len(fields)-1])
}
}
74 changes: 74 additions & 0 deletions util/jsonutil/setter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
Copyright 2023 The KubeVela 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 jsonutil_test

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/require"

"github.com/kubevela/pkg/util/jsonutil"
)

func TestDropField(t *testing.T) {
testCases := map[string]struct {
Input string
Fields []string
Output string
}{
"empty": {
Input: `{"a":1}`,
Fields: nil,
Output: `{"a":1}`,
},
"not-found": {
Input: `{"a":1}`,
Fields: []string{"b"},
Output: `{"a":1}`,
},
"type-not-match": {
Input: `{"a":[1]}`,
Fields: []string{"a", "b", "c"},
Output: `{"a":[1]}`,
},
"key-not-found": {
Input: `{"a":{"b":3}}`,
Fields: []string{"b", "a", "b"},
Output: `{"a":{"b":3}}`,
},
"nil": {
Input: `{"a":null}`,
Fields: []string{"a", "b"},
Output: `{"a":null}`,
},
"nested-drop": {
Input: `{"a":{"b":3}}`,
Fields: []string{"a", "b"},
Output: `{"a":{}}`,
},
}
for name, tt := range testCases {
t.Run(name, func(t *testing.T) {
m1, m2 := map[string]any{}, map[string]any{}
require.NoError(t, json.Unmarshal([]byte(tt.Input), &m1))
require.NoError(t, json.Unmarshal([]byte(tt.Output), &m2))
jsonutil.DropField(m1, tt.Fields...)
require.Equal(t, m2, m1)
})
}
}
150 changes: 150 additions & 0 deletions util/k8s/apply/apply.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
Copyright 2023 The KubeVela 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 apply

import (
"context"
"fmt"

"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"

"github.com/kubevela/pkg/util/k8s/patch"
)

// Apply try to get desired object and update it, if not exist, create it
// The procedure of Apply is
// 1. Get the desired object
// 2. Run the PreApplyHook
// 3. If not exist, run the PreCreateHook and create the target object, exit
// 4. If exists, run the PreUpdateHook, get the UpdateStrategy, decide how to update
// 5. If Patch, get patch.PatchAction (implemented by PatchActionProvider)
// 6. Do the update operation
// The above procedure will also be affected by the DryRunOption
func Apply(ctx context.Context, c client.Client, desired client.Object, opts Options) error {
// wrap client for apply spec & status
c = &Client{c}

// pre-fill types
if desired.GetObjectKind().GroupVersionKind().Kind == "" {
if gvk, err := apiutil.GVKForObject(desired, c.Scheme()); err == nil {
desired.GetObjectKind().SetGroupVersionKind(gvk)
}
}

// get existing
existing, err := get(ctx, c, desired)
if err != nil {
return fmt.Errorf("cannot get object: %w", err)
}

if hook, ok := opts.(PreApplyHook); ok {
if err = hook.PreApply(desired); err != nil {
return err
}
}

// create
if existing == nil {
if err = create(ctx, c, desired, opts); err != nil {
return fmt.Errorf("cannot create object: %w", err)
}
return nil
}

// update
if err = update(ctx, c, existing, desired, opts); err != nil {
return fmt.Errorf("cannot update object: %w", err)
}
return nil
}

func get(ctx context.Context, c client.Client, desired client.Object) (client.Object, error) {
o := &unstructured.Unstructured{}
o.SetGroupVersionKind(desired.GetObjectKind().GroupVersionKind())
if err := c.Get(ctx, client.ObjectKeyFromObject(desired), o); err != nil {
return nil, client.IgnoreNotFound(err)
}
return o, nil
}

func create(ctx context.Context, c client.Client, desired client.Object, act Options) error {
if hook, ok := act.(PreCreateHook); ok {
if err := hook.PreCreate(desired); err != nil {
return err
}
}
klog.V(4).InfoS("creating object", "resource", klog.KObj(desired))
return c.Create(ctx, desired, act.DryRun())
}

func update(ctx context.Context, c client.Client, existing client.Object, desired client.Object, act Options) error {
if hook, ok := act.(PreUpdateHook); ok {
if err := hook.PreUpdate(existing, desired); err != nil {
return err
}
}
strategy, err := act.GetUpdateStrategy(existing, desired)
if err != nil {
return err
}
switch strategy {
case Recreate:
klog.V(4).InfoS("recreating object", "resource", klog.KObj(desired))
if act.DryRun() { // recreate does not support dryrun
return nil
}
if existing.GetDeletionTimestamp() == nil {
if err := c.Delete(ctx, existing); err != nil {
return fmt.Errorf("failed to delete object: %w", err)
}
}
return c.Create(ctx, desired)
case Replace:
klog.V(4).InfoS("replacing object", "resource", klog.KObj(desired))
desired.SetResourceVersion(existing.GetResourceVersion())
return c.Update(ctx, desired, act.DryRun())
case Patch:
klog.V(4).InfoS("patching object", "resource", klog.KObj(desired))
patchAction := patch.PatchAction{}
if prd, ok := act.(PatchActionProvider); ok {
patchAction = prd.GetPatchAction()
}
pat, err := patch.ThreeWayMergePatch(existing, desired, &patchAction)
if err != nil {
return fmt.Errorf("cannot calculate patch by computing a three way diff: %w", err)
}
if isEmptyPatch(pat) {
return nil
}
return c.Patch(ctx, desired, pat, act.DryRun())
case Skip:
return nil
default:
return fmt.Errorf("unrecognizable update strategy: %v", strategy)
}
}

func isEmptyPatch(patch client.Patch) bool {
if patch == nil {
return true
}
data, _ := patch.Data(nil)
return data == nil || string(data) == "{}"
}
Loading

0 comments on commit 274bf1e

Please sign in to comment.