mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-01 04:35:40 +09:00
Defaults set by the administrator have to reach every application kind, including ones from external catalogs, and give the same result for the dashboard, Terraform and kubectl, so the merge runs in the API server on create instead of in each client. User values win over installation defaults, which win over the developer defaults of the chart. Only objects with declared properties merge recursively. Arrays, dictionaries and free-form objects are replaced whole, so a pool that sets its own registry mirrors never receives the platform entries. The entry is checked against the application's OpenAPI schema before merging. CEL rules are left out of that check, since a rule such as an immutability test has no meaning on a partial object. The ConfigMap is read through a cache limited to that one object, so the API does not hold a watch on every ConfigMap in the cluster. A missing ConfigMap means no defaults. One that cannot be read, or an invalid configuration or entry, skips the defaults and the create goes on with a warning, because a configuration mistake must not stop applications from being created. Updates never apply defaults. The ConfigMap rule the API already has covers the read, and its comment now names this second user. Assisted-by: LLM Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
215 lines
7.8 KiB
Go
215 lines
7.8 KiB
Go
/*
|
|
Copyright 2026 The Cozystack 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 server_test
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
helmv2 "github.com/fluxcd/helm-controller/api/v2"
|
|
corev1 "k8s.io/api/core/v1"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
"k8s.io/apimachinery/pkg/types"
|
|
"k8s.io/apiserver/pkg/authentication/authenticator"
|
|
"k8s.io/apiserver/pkg/authentication/user"
|
|
"k8s.io/apiserver/pkg/authorization/authorizerfactory"
|
|
"k8s.io/apiserver/pkg/registry/rest"
|
|
genericapiserver "k8s.io/apiserver/pkg/server"
|
|
utilfeature "k8s.io/apiserver/pkg/util/feature"
|
|
restclient "k8s.io/client-go/rest"
|
|
basecompatibility "k8s.io/component-base/compatibility"
|
|
baseversion "k8s.io/component-base/version"
|
|
"sigs.k8s.io/controller-runtime/pkg/client"
|
|
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
|
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
|
|
|
|
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
|
|
"github.com/cozystack/cozystack/pkg/apiserver"
|
|
cozyserver "github.com/cozystack/cozystack/pkg/cmd/server"
|
|
"github.com/cozystack/cozystack/pkg/config"
|
|
applicationstorage "github.com/cozystack/cozystack/pkg/registry/apps/application"
|
|
)
|
|
|
|
var redisConfig = config.Resource{
|
|
Application: config.ApplicationConfig{Kind: "Redis", Singular: "redis", Plural: "redises"},
|
|
Release: config.ReleaseConfig{Prefix: "redis-"},
|
|
}
|
|
|
|
// startAppsServer serves the apps group through the real apiserver handler
|
|
// chain, with the application storage backed by a fake client. The kinds are
|
|
// registered on the process-wide apiserver.Scheme.
|
|
func startAppsServer(t *testing.T, rc *config.ResourceConfig, objects ...client.Object) (*httptest.Server, client.Client) {
|
|
t.Helper()
|
|
return serveApps(t, rc, false, objects...)
|
|
}
|
|
|
|
// startAppsServerWithUIDs is startAppsServer whose backing client assigns
|
|
// metadata.uid on create, as a real apiserver does. The fake client does not, and
|
|
// the generic patch handler treats a current object without a uid as missing, so
|
|
// without one a PATCH of an existing application is served as a create.
|
|
func startAppsServerWithUIDs(t *testing.T, rc *config.ResourceConfig, objects ...client.Object) (*httptest.Server, client.Client) {
|
|
t.Helper()
|
|
return serveApps(t, rc, true, objects...)
|
|
}
|
|
|
|
func serveApps(t *testing.T, rc *config.ResourceConfig, assignUIDs bool, objects ...client.Object) (*httptest.Server, client.Client) {
|
|
t.Helper()
|
|
if err := appsv1alpha1.RegisterDynamicTypes(apiserver.Scheme, rc); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
backing := runtime.NewScheme()
|
|
if err := helmv2.AddToScheme(backing); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := corev1.AddToScheme(backing); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
builder := fake.NewClientBuilder().WithScheme(backing).WithObjects(objects...)
|
|
if assignUIDs {
|
|
var uids atomic.Int64
|
|
builder = builder.WithInterceptorFuncs(interceptor.Funcs{
|
|
Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
|
|
if obj.GetUID() == "" {
|
|
obj.SetUID(types.UID(fmt.Sprintf("00000000-0000-0000-0000-%012d", uids.Add(1))))
|
|
}
|
|
return c.Create(ctx, obj, opts...)
|
|
},
|
|
})
|
|
}
|
|
cli := builder.Build()
|
|
|
|
cfg := genericapiserver.NewConfig(apiserver.Codecs)
|
|
cfg.Authorization.Authorizer = authorizerfactory.NewAlwaysAllowAuthorizer()
|
|
cfg.Authentication.Authenticator = authenticator.RequestFunc(func(*http.Request) (*authenticator.Response, bool, error) {
|
|
return &authenticator.Response{User: &user.DefaultInfo{Name: "test-user"}}, true, nil
|
|
})
|
|
cfg.ExternalAddress = "localhost:443"
|
|
cfg.LoopbackClientConfig = &restclient.Config{}
|
|
cfg.FeatureGate = utilfeature.DefaultMutableFeatureGate
|
|
if baseversion.DefaultKubeBinaryVersion != "" {
|
|
cfg.EffectiveVersion = basecompatibility.NewEffectiveVersionFromString(baseversion.DefaultKubeBinaryVersion, "", "")
|
|
}
|
|
cozyserver.ConfigureOpenAPI(cfg, cozyserver.KindSchemasFromConfig(rc), "test", "test")
|
|
srv, err := cfg.Complete(nil).New("watch-initial-events-test", genericapiserver.NewEmptyDelegate())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
storage := map[string]rest.Storage{}
|
|
for i := range rc.Resources {
|
|
storage[rc.Resources[i].Application.Plural] = applicationstorage.NewREST(cli, cli, cli, &rc.Resources[i])
|
|
}
|
|
if err := apiserver.InstallAppsAPIGroup(srv, storage); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv.PrepareRun()
|
|
ts := httptest.NewServer(srv.Handler)
|
|
t.Cleanup(ts.Close)
|
|
return ts, cli
|
|
}
|
|
|
|
// watchStream opens a watch with the given query, then creates and updates a
|
|
// release behind it, and returns the stream lines received within the timeout.
|
|
func watchStream(t *testing.T, ts *httptest.Server, cli client.Client, query string) []string {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
|
|
ts.URL+"/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/redises?"+query, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatalf("watch: %v", err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("watch: status %d", resp.StatusCode)
|
|
}
|
|
|
|
lines := make(chan string)
|
|
go func() {
|
|
defer close(lines)
|
|
sc := bufio.NewScanner(resp.Body)
|
|
for sc.Scan() {
|
|
lines <- sc.Text()
|
|
}
|
|
}()
|
|
|
|
hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{
|
|
Name: "redis-cache",
|
|
Namespace: "tenant-a",
|
|
Labels: map[string]string{
|
|
applicationstorage.ApplicationKindLabel: "Redis",
|
|
applicationstorage.ApplicationGroupLabel: appsv1alpha1.GroupName,
|
|
},
|
|
}}
|
|
if err := cli.Create(context.Background(), hr); err != nil {
|
|
t.Fatalf("create HelmRelease: %v", err)
|
|
}
|
|
// The storage sends a pending initial-events-end bookmark ahead of the
|
|
// first live event, so drive one.
|
|
hr.Annotations = map[string]string{"touched": "1"}
|
|
if err := cli.Update(context.Background(), hr); err != nil {
|
|
t.Fatalf("update HelmRelease: %v", err)
|
|
}
|
|
|
|
var out []string
|
|
for line := range lines {
|
|
out = append(out, line)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// A plain watch has SendInitialEvents defaulted on by the handler but no
|
|
// bookmarks; from k8s.io/apiserver v0.36 the handler panics if the storage
|
|
// answers it with the initial-events-end bookmark, so none may appear.
|
|
func TestWatchHandler_PlainWatchGetsNoInitialEventsEndBookmark(t *testing.T) {
|
|
ts, cli := startAppsServer(t, &config.ResourceConfig{Resources: []config.Resource{redisConfig}})
|
|
lines := watchStream(t, ts, cli, "watch=true")
|
|
sawModified := false
|
|
for _, l := range lines {
|
|
if strings.Contains(l, metav1.InitialEventsAnnotationKey) {
|
|
t.Fatalf("plain watch received the initial-events-end bookmark: %s", l)
|
|
}
|
|
sawModified = sawModified || strings.Contains(l, `"type":"MODIFIED"`)
|
|
}
|
|
if !sawModified {
|
|
t.Fatalf("plain watch saw no MODIFIED event, stream: %v", lines)
|
|
}
|
|
}
|
|
|
|
func TestWatchHandler_WatchListGetsInitialEventsEndBookmark(t *testing.T) {
|
|
ts, cli := startAppsServer(t, &config.ResourceConfig{Resources: []config.Resource{redisConfig}})
|
|
lines := watchStream(t, ts, cli, "watch=true&sendInitialEvents=true&allowWatchBookmarks=true&resourceVersionMatch=NotOlderThan")
|
|
for _, l := range lines {
|
|
if strings.Contains(l, `"type":"BOOKMARK"`) && strings.Contains(l, metav1.InitialEventsAnnotationKey) {
|
|
return
|
|
}
|
|
}
|
|
t.Fatalf("watch list received no initial-events-end bookmark, stream: %v", lines)
|
|
}
|