Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
implement subresource foos/config
  • Loading branch information
phosae committed Jul 21, 2023
commit c8aaefdba992b7999372259492b2396b52110b71
1 change: 1 addition & 0 deletions api-aggregation-lib/pkg/api/hello.zeng.dev/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Foo{},
&FooList{},
&Config{},
)
return nil
}
18 changes: 18 additions & 0 deletions api-aggregation-lib/pkg/api/hello.zeng.dev/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,21 @@ type FooList struct {

Items []Foo
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Config is the config subresource of Foo
type Config struct {
metav1.TypeMeta
metav1.ObjectMeta

Spec ConfigSpec
}

type ConfigSpec struct {
// Msg says hello world!
Msg string
// Msg1 provides some verbose information
// +optional
Msg1 string
}

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

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

28 changes: 16 additions & 12 deletions api-aggregation-lib/pkg/apiserver/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,20 +110,24 @@ func (c completedConfig) New() (*HelloApiServer, error) {
}

apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(hello.GroupName, Scheme, metav1.ParameterCodec, Codecs)
restStorage, err := func() (rest.Storage, error) {
if c.ExtraConfig.EnableEtcdStorage {
return fooregistry.NewREST(Scheme, c.GenericConfig.RESTOptionsGetter)
} else {
return fooregistry.NewMemStore(), nil

if !c.ExtraConfig.EnableEtcdStorage {
restStorage := fooregistry.NewMemStore()
v1storage := map[string]rest.Storage{"foos": restStorage}
v2storage := map[string]rest.Storage{"foos": restStorage}
apiGroupInfo.VersionedResourcesStorageMap["v1"] = v1storage
apiGroupInfo.VersionedResourcesStorageMap["v2"] = v2storage
} else {
restStorage, err := fooregistry.NewREST(Scheme, c.GenericConfig.RESTOptionsGetter)
if err != nil {
return nil, err
}
}()
if err != nil {
return nil, err

v1storage := map[string]rest.Storage{"foos": restStorage.Foo}
v2storage := map[string]rest.Storage{"foos": restStorage.Foo, "foos/config": restStorage.Config}
apiGroupInfo.VersionedResourcesStorageMap["v1"] = v1storage
apiGroupInfo.VersionedResourcesStorageMap["v2"] = v2storage
}
v1storage := map[string]rest.Storage{"foos": restStorage}
v2storage := map[string]rest.Storage{"foos": restStorage}
apiGroupInfo.VersionedResourcesStorageMap["v1"] = v1storage
apiGroupInfo.VersionedResourcesStorageMap["v2"] = v2storage

if err := s.GenericAPIServer.InstallAPIGroup(&apiGroupInfo); err != nil {
return nil, err
Expand Down
171 changes: 167 additions & 4 deletions api-aggregation-lib/pkg/registry/hello.zeng.dev/foo/etcd.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
package foo

import (
"context"
"fmt"

"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/registry/generic"
genericregistry "k8s.io/apiserver/pkg/registry/generic/registry"
"k8s.io/apiserver/pkg/registry/rest"
"sigs.k8s.io/structured-merge-diff/v4/fieldpath"

hello "github.com/phosae/x-kubernetes/api-aggregation-lib/pkg/api/hello.zeng.dev"
)

type fooStorage struct {
type REST struct {
*genericregistry.Store
}

var _ rest.ShortNamesProvider = &fooStorage{}
type fooStorage struct {
Foo *REST
Config *ConfigREST
}

var _ rest.ShortNamesProvider = &REST{}

func (*fooStorage) ShortNames() []string {
func (*REST) ShortNames() []string {
return []string{"fo"}
}

Expand All @@ -39,5 +50,157 @@ func NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) (*foo
if err := store.CompleteWithOptions(options); err != nil {
return nil, err
}
return &fooStorage{store}, nil

configStore := *store

return &fooStorage{&REST{store}, &ConfigREST{Store: &configStore}}, nil
}

// ConfigREST implements the config subresource for a Foo
type ConfigREST struct {
Store *genericregistry.Store
}

var _ = rest.Patcher(&ConfigREST{})

// New creates a new Config resource
func (r *ConfigREST) New() runtime.Object {
return &hello.Config{}
}

func (*ConfigREST) Destroy() {
// Given that underlying store is shared with REST,
// we don't destroy it here explicitly.
}

// Get retrieves the object from the storage. It is required to support Patch.
func (r *ConfigREST) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
fooObj, err := r.Store.Get(ctx, name, options)
if err != nil {
if errors.IsNotFound(err) {
return nil, errors.NewNotFound(hello.Resource("foos/config"), name)
}
return nil, err
}

foo := fooObj.(*hello.Foo)

return configFromFoo(foo), nil
}

// Update alters the spec.config subset of an object.
func (r *ConfigREST) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) {
obj, _, err := r.Store.Update(
ctx,
name,
&configUpdatedObjectInfo{name, objInfo},
toConfigCreateValidation(createValidation),
toConfigUpdateValidation(updateValidation),
false,
options,
)
if err != nil {
return nil, false, err
}
foo := obj.(*hello.Foo)
newConfig := configFromFoo(foo)
if err != nil {
return nil, false, errors.NewBadRequest(fmt.Sprintf("%v", err))
}
return newConfig, false, nil
}

// GetResetFields implements rest.ResetFieldsStrategy
func (r *ConfigREST) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {
return r.Store.GetResetFields()
}

// configFromFoo returns a config subresource for a foo.
func configFromFoo(foo *hello.Foo) *hello.Config {
return &hello.Config{
ObjectMeta: metav1.ObjectMeta{
Name: foo.Name,
Namespace: foo.Namespace,
UID: foo.UID,
ResourceVersion: foo.ResourceVersion,
CreationTimestamp: foo.CreationTimestamp,
},
Spec: hello.ConfigSpec{
Msg: foo.Spec.Config.Msg,
Msg1: foo.Spec.Config.Msg1,
},
}
}

func (r *ConfigREST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) {
return r.Store.ConvertToTable(ctx, object, tableOptions)
}

func toConfigCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {
return func(ctx context.Context, obj runtime.Object) error {
config := configFromFoo(obj.(*hello.Foo))
return f(ctx, config)
}
}

func toConfigUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {
return func(ctx context.Context, obj, old runtime.Object) error {
config := configFromFoo(obj.(*hello.Foo))
oldConfig := configFromFoo(old.(*hello.Foo))
return f(ctx, config, oldConfig)
}
}

// configUpdatedObjectInfo transforms existing foo -> existing config -> new config -> new foo
type configUpdatedObjectInfo struct {
name string
reqObjInfo rest.UpdatedObjectInfo
}

func (c *configUpdatedObjectInfo) Preconditions() *metav1.Preconditions {
return c.reqObjInfo.Preconditions()
}

func (c *configUpdatedObjectInfo) UpdatedObject(ctx context.Context, oldObj runtime.Object) (runtime.Object, error) {
foo, ok := oldObj.DeepCopyObject().(*hello.Foo)
if !ok {
return nil, errors.NewBadRequest(fmt.Sprintf("expected existing object type to be Foo, got %T", foo))
}

// if zero-value, the existing object does not exist
if len(foo.ResourceVersion) == 0 {
return nil, errors.NewNotFound(hello.Resource("foos/config"), c.name)
}

oldConfig := configFromFoo(foo)

// old config -> new config
newConfigObj, err := c.reqObjInfo.UpdatedObject(ctx, oldConfig)
if err != nil {
return nil, err
}
if newConfigObj == nil {
return nil, errors.NewBadRequest("nil update passed to Config")
}

config, ok := newConfigObj.(*hello.Config)
if !ok {
return nil, errors.NewBadRequest(fmt.Sprintf("expected input object type to be Config, but %T", newConfigObj))
}

// validate precondition if specified (resourceVersion matching is handled by storage)
if len(config.UID) > 0 && config.UID != foo.UID {
return nil, errors.NewConflict(
hello.Resource("foos/config"),
foo.Name,
fmt.Errorf("precondition failed: UID in precondition: %v, UID in object meta: %v", config.UID, foo.UID),
)
}

// move fields to object and return
foo.Spec.Config.Msg = config.Spec.Msg
foo.Spec.Config.Msg1 = config.Spec.Msg1
foo.ResourceVersion = config.ResourceVersion

return foo, nil
}