mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-21 12:13:55 +09:00
Reconcile the tap digest-pin change with #5071 (no-install-on-connect), now merged into main. Keep this branch's resetTapPinState, the verify-before-pull Trust text, and the index-README trust model, while adopting #5071's wording that installing (not tapping) runs charts and dropping the stale "re-registration" phrasing from the shared tap.go and rest.go comments. Conflicts resolved in cmd/cozypkg/cmd/tap.go, pkg/registry/core/tap/rest.go, and hack/packages-index/README.md. Assisted-by: LLM Signed-off-by: IvanHunters <xorokhotnikov@gmail.com>
578 lines
23 KiB
Go
578 lines
23 KiB
Go
// SPDX-License-Identifier: Apache-2.0
|
|
// Copyright 2025 The Cozystack Authors.
|
|
|
|
// Package tap serves the read-only, cluster-scoped Tap resource that powers the
|
|
// dashboard marketplace view. Each Tap is computed on read from a PackageSource
|
|
// and the ApplicationDefinitions attributable to it, using the apiserver's
|
|
// privileged dynamic client, so a tenant browsing the catalog needs no direct
|
|
// access to those resources and never sees a pull credential.
|
|
package tap
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"sort"
|
|
|
|
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
|
metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
|
"k8s.io/apimachinery/pkg/watch"
|
|
"k8s.io/apiserver/pkg/registry/rest"
|
|
"k8s.io/client-go/dynamic"
|
|
"k8s.io/klog/v2"
|
|
|
|
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
|
|
"github.com/cozystack/cozystack/internal/marketplace/collision"
|
|
"github.com/cozystack/cozystack/internal/marketplace/tapconst"
|
|
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
|
|
)
|
|
|
|
const singularName = "tap"
|
|
|
|
var (
|
|
_ rest.Lister = &REST{}
|
|
_ rest.Getter = &REST{}
|
|
_ rest.Watcher = &REST{}
|
|
_ rest.TableConvertor = &REST{}
|
|
_ rest.Scoper = &REST{}
|
|
_ rest.SingularNameProvider = &REST{}
|
|
_ rest.GracefulDeleter = &REST{}
|
|
_ rest.Creater = &REST{}
|
|
)
|
|
|
|
// REST implements the read-only Tap resource.
|
|
type REST struct {
|
|
dyn dynamic.Interface
|
|
gvr schema.GroupVersionResource
|
|
}
|
|
|
|
// NewREST builds the Tap REST storage from the apiserver's privileged dynamic
|
|
// client.
|
|
func NewREST(dyn dynamic.Interface) *REST {
|
|
return &REST{
|
|
dyn: dyn,
|
|
gvr: schema.GroupVersionResource{
|
|
Group: corev1alpha1.GroupName,
|
|
Version: "v1alpha1",
|
|
Resource: "taps",
|
|
},
|
|
}
|
|
}
|
|
|
|
func (*REST) NamespaceScoped() bool { return false }
|
|
func (*REST) New() runtime.Object { return &corev1alpha1.Tap{} }
|
|
func (*REST) NewList() runtime.Object {
|
|
return &corev1alpha1.TapList{}
|
|
}
|
|
func (*REST) Kind() string { return "Tap" }
|
|
func (r *REST) GroupVersionKind(_ schema.GroupVersion) schema.GroupVersionKind {
|
|
return r.gvr.GroupVersion().WithKind("Tap")
|
|
}
|
|
func (*REST) GetSingularName() string { return singularName }
|
|
func (*REST) Destroy() {}
|
|
|
|
// -----------------------------------------------------------------------------
|
|
// Lister / Getter
|
|
// -----------------------------------------------------------------------------
|
|
|
|
func (r *REST) List(ctx context.Context, _ *metainternal.ListOptions) (runtime.Object, error) {
|
|
pss, err := r.fetchPackageSources(ctx)
|
|
if err != nil {
|
|
return nil, apierrors.NewInternalError(fmt.Errorf("list PackageSources: %w", err))
|
|
}
|
|
idx := r.appDefIndex(ctx)
|
|
|
|
out := &corev1alpha1.TapList{
|
|
TypeMeta: metav1.TypeMeta{
|
|
APIVersion: corev1alpha1.SchemeGroupVersion.String(),
|
|
Kind: "TapList",
|
|
},
|
|
ListMeta: metav1.ListMeta{ResourceVersion: "0"},
|
|
}
|
|
materializedSources := map[string]bool{}
|
|
for _, ps := range pss {
|
|
out.Items = append(out.Items, buildTap(ps, idx))
|
|
if ref := ps.Spec.SourceRef; ref != nil && ref.Kind == "OCIRepository" && ref.Name != "" {
|
|
materializedSources[ref.Name] = true
|
|
}
|
|
}
|
|
// Surface tap sources with no materialized PackageSource yet (a connect in
|
|
// progress, or one blocked by a collision) so the pending or errored state
|
|
// shows in the dashboard instead of the tap silently never appearing.
|
|
if repos, err := r.listTapSources(ctx); err == nil {
|
|
for i := range repos {
|
|
name := repos[i].GetName()
|
|
if materializedSources[name] {
|
|
continue
|
|
}
|
|
out.Items = append(out.Items, buildPendingTap(name, repos[i].GetAnnotations()[tapconst.MaterializeErrorAnnotation]))
|
|
}
|
|
}
|
|
sort.Slice(out.Items, func(i, j int) bool { return out.Items[i].Name < out.Items[j].Name })
|
|
return out, nil
|
|
}
|
|
|
|
// listTapSources lists the labeled tap OCIRepositories in cozy-system.
|
|
func (r *REST) listTapSources(ctx context.Context) ([]unstructured.Unstructured, error) {
|
|
ul, err := r.dyn.Resource(gvrOCIRepos).Namespace("cozy-system").List(ctx, metav1.ListOptions{
|
|
LabelSelector: tapconst.Label + "=true",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return ul.Items, nil
|
|
}
|
|
|
|
func (r *REST) Get(ctx context.Context, name string, _ *metav1.GetOptions) (runtime.Object, error) {
|
|
u, err := r.dyn.Resource(gvrPackageSources).Get(ctx, name, metav1.GetOptions{})
|
|
if err != nil {
|
|
if apierrors.IsNotFound(err) {
|
|
// A tap connected but not yet materialized (a connect in progress, or
|
|
// one blocked by a collision) has an OCIRepository but no
|
|
// PackageSource. Surface it as a pending Tap so a detail view mirrors
|
|
// what List shows, instead of a 404 that hides the block reason.
|
|
if pending, ok := r.pendingTapByName(ctx, name); ok {
|
|
return pending, nil
|
|
}
|
|
return nil, apierrors.NewNotFound(r.gvr.GroupResource(), name)
|
|
}
|
|
return nil, apierrors.NewInternalError(fmt.Errorf("get PackageSource %q: %w", name, err))
|
|
}
|
|
var ps cozyv1alpha1.PackageSource
|
|
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, &ps); err != nil {
|
|
return nil, apierrors.NewInternalError(fmt.Errorf("decode PackageSource %q: %w", name, err))
|
|
}
|
|
idx := r.appDefIndex(ctx)
|
|
tap := buildTap(ps, idx)
|
|
return &tap, nil
|
|
}
|
|
|
|
// pendingTapByName finds a tap source (a labeled OCIRepository) whose own name
|
|
// is name and which has not materialized a PackageSource yet, returning it as a
|
|
// pending Tap. It mirrors the pending entries List emits and the orphan lookup
|
|
// Delete uses, so Get, List, and Delete agree on what a pending tap is.
|
|
func (r *REST) pendingTapByName(ctx context.Context, name string) (*corev1alpha1.Tap, bool) {
|
|
repos, err := r.listTapSources(ctx)
|
|
if err != nil {
|
|
return nil, false
|
|
}
|
|
for i := range repos {
|
|
if repos[i].GetName() != name {
|
|
continue
|
|
}
|
|
tap := buildPendingTap(name, repos[i].GetAnnotations()[tapconst.MaterializeErrorAnnotation])
|
|
return &tap, true
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
// -----------------------------------------------------------------------------
|
|
// Creater — connect a community tap (mirrors `cozypkg tap`)
|
|
//
|
|
// Create records the intent only: it creates the labeled Flux OCIRepository
|
|
// (with an optional pull-credential secretRef). The operator's tap materializer
|
|
// then pulls the artifact and creates the PackageSource(s), so the API never
|
|
// blocks a request on a registry pull. The returned Tap reflects that
|
|
// materialization is pending.
|
|
// -----------------------------------------------------------------------------
|
|
|
|
// createDryRun and deleteDryRun carry the caller's dry-run directive down to
|
|
// the backing write. The dynamic client takes the directive by value, so a
|
|
// request that reaches it without one performs the write for real: a
|
|
// --dry-run=server connect would create the Flux source and a dry-run
|
|
// disconnect would delete the PackageSource.
|
|
func createDryRun(opts *metav1.CreateOptions) []string {
|
|
if opts == nil {
|
|
return nil
|
|
}
|
|
return opts.DryRun
|
|
}
|
|
|
|
func deleteDryRun(opts *metav1.DeleteOptions) []string {
|
|
if opts == nil {
|
|
return nil
|
|
}
|
|
return opts.DryRun
|
|
}
|
|
|
|
func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, opts *metav1.CreateOptions) (runtime.Object, error) {
|
|
in, ok := obj.(*corev1alpha1.Tap)
|
|
if !ok {
|
|
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a Tap object, got %T", obj))
|
|
}
|
|
if in.Spec.URL == "" {
|
|
return nil, apierrors.NewBadRequest("spec.url is required to connect a tap")
|
|
}
|
|
target, err := parseConnectURL(in.Spec.URL, in.Spec.Tag)
|
|
if err != nil {
|
|
return nil, apierrors.NewBadRequest(err.Error())
|
|
}
|
|
if createValidation != nil {
|
|
if err := createValidation(ctx, obj); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
// A connect carries a tag, a digest, or both; an explicit digest is pinned
|
|
// here, while a tag-only source is pinned to a digest later by the operator.
|
|
refSpec := map[string]any{}
|
|
if target.Tag != "" {
|
|
refSpec["tag"] = target.Tag
|
|
}
|
|
if target.Digest != "" {
|
|
refSpec["digest"] = target.Digest
|
|
}
|
|
repo := &unstructured.Unstructured{Object: map[string]any{
|
|
"apiVersion": "source.toolkit.fluxcd.io/v1",
|
|
"kind": "OCIRepository",
|
|
"metadata": map[string]any{
|
|
"name": target.FluxSourceName,
|
|
"namespace": "cozy-system",
|
|
"labels": map[string]any{tapconst.Label: "true"},
|
|
"annotations": map[string]any{tapconst.NameAnnotation: target.FluxSourceName},
|
|
},
|
|
"spec": map[string]any{
|
|
"url": target.URL,
|
|
"interval": "5m0s",
|
|
"ref": refSpec,
|
|
},
|
|
}}
|
|
if in.Spec.SecretRef != "" {
|
|
_ = unstructured.SetNestedMap(repo.Object, map[string]any{"name": in.Spec.SecretRef}, "spec", "secretRef")
|
|
}
|
|
if in.Spec.Verify != nil {
|
|
verifySpec, err := buildVerifySpec(in.Spec.Verify)
|
|
if err != nil {
|
|
return nil, apierrors.NewBadRequest(err.Error())
|
|
}
|
|
_ = unstructured.SetNestedMap(repo.Object, verifySpec, "spec", "verify")
|
|
}
|
|
|
|
// Create the Flux source, idempotently: a repeat connect updates the
|
|
// existing source (new tag/secret) rather than erroring.
|
|
src := r.dyn.Resource(gvrOCIRepos).Namespace("cozy-system")
|
|
if _, err := src.Create(ctx, repo, metav1.CreateOptions{FieldManager: "cozystack-api", DryRun: createDryRun(opts)}); err != nil {
|
|
if !apierrors.IsAlreadyExists(err) {
|
|
return nil, apierrors.NewInternalError(fmt.Errorf("create Flux source for tap %s: %w", target.FluxSourceName, err))
|
|
}
|
|
cur, gerr := src.Get(ctx, target.FluxSourceName, metav1.GetOptions{})
|
|
if gerr != nil {
|
|
return nil, apierrors.NewInternalError(fmt.Errorf("update Flux source for tap %s: %w", target.FluxSourceName, gerr))
|
|
}
|
|
// Refuse to silently retarget: two repositories that share an org/repo
|
|
// path on different registry hosts derive the same name, so a blind
|
|
// update would repoint the first at the second. Require a disconnect
|
|
// first when the existing source points at a different URL.
|
|
if curURL, _, _ := unstructured.NestedString(cur.Object, "spec", "url"); curURL != "" && curURL != target.URL {
|
|
return nil, apierrors.NewConflict(r.gvr.GroupResource(), target.FluxSourceName,
|
|
fmt.Errorf("a different repository (%s) is already connected as %q; disconnect it before connecting %s", curURL, target.FluxSourceName, target.URL))
|
|
}
|
|
// Update the fields this API owns on the FETCHED object, so the operator's
|
|
// finalizer survives. Replace url, interval and ref from this connect, but
|
|
// PRESERVE a spec.verify or spec.secretRef set earlier (by this API or by
|
|
// an admin) when this connect does not carry its own: a repeat connect must
|
|
// never silently drop a signature-verification policy or a pull credential.
|
|
// Replacing the whole ref rather than merging it is deliberate: it drops the
|
|
// operator's prior digest pin so the newly requested tag re-resolves (the
|
|
// operator re-pins it). A connect that itself carries verify or a secret
|
|
// overrides the preserved one.
|
|
newSpec := map[string]any{}
|
|
if existingVerify, ok, _ := unstructured.NestedMap(cur.Object, "spec", "verify"); ok {
|
|
newSpec["verify"] = existingVerify
|
|
}
|
|
if existingSecret, ok, _ := unstructured.NestedMap(cur.Object, "spec", "secretRef"); ok {
|
|
newSpec["secretRef"] = existingSecret
|
|
}
|
|
for k, v := range repo.Object["spec"].(map[string]any) {
|
|
newSpec[k] = v
|
|
}
|
|
cur.Object["spec"] = newSpec
|
|
labels := cur.GetLabels()
|
|
if labels == nil {
|
|
labels = map[string]string{}
|
|
}
|
|
labels[tapconst.Label] = "true"
|
|
cur.SetLabels(labels)
|
|
ann := cur.GetAnnotations()
|
|
if ann == nil {
|
|
ann = map[string]string{}
|
|
}
|
|
ann[tapconst.NameAnnotation] = target.FluxSourceName
|
|
// Clear the materialized-revision annotation so a re-connect re-materializes
|
|
// (recovering a PackageSource removed out-of-band, the same recovery `cozypkg
|
|
// tap` performs), and the pinned-digest annotation so the operator re-pins
|
|
// the newly requested tag rather than treating the dropped pin as a user digest.
|
|
delete(ann, tapconst.MaterializedRevisionAnnotation)
|
|
delete(ann, tapconst.PinnedDigestAnnotation)
|
|
cur.SetAnnotations(ann)
|
|
if _, err := src.Update(ctx, cur, metav1.UpdateOptions{FieldManager: "cozystack-api", DryRun: createDryRun(opts)}); err != nil {
|
|
return nil, apierrors.NewInternalError(fmt.Errorf("update Flux source for tap %s: %w", target.FluxSourceName, err))
|
|
}
|
|
}
|
|
|
|
// Return catalog metadata only: never the url or the secret reference.
|
|
return &corev1alpha1.Tap{
|
|
TypeMeta: metav1.TypeMeta{APIVersion: corev1alpha1.SchemeGroupVersion.String(), Kind: "Tap"},
|
|
ObjectMeta: metav1.ObjectMeta{Name: target.FluxSourceName, ResourceVersion: "0"},
|
|
Spec: corev1alpha1.TapSpec{
|
|
Source: corev1alpha1.TapSource{Kind: "OCIRepository", Name: target.FluxSourceName},
|
|
Community: true,
|
|
Ready: false,
|
|
Message: "connecting: waiting for the artifact to be pulled and materialized",
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
// -----------------------------------------------------------------------------
|
|
// GracefulDeleter — disconnect a community tap (mirrors `cozypkg untap`)
|
|
// -----------------------------------------------------------------------------
|
|
|
|
func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, opts *metav1.DeleteOptions) (runtime.Object, bool, error) {
|
|
u, err := r.dyn.Resource(gvrPackageSources).Get(ctx, name, metav1.GetOptions{})
|
|
if err != nil {
|
|
if apierrors.IsNotFound(err) {
|
|
// A tap connected but not yet (or never) materialized has an
|
|
// OCIRepository but no PackageSource (name is then the source's own
|
|
// name). Fall back to removing that source so a pending or
|
|
// collision-blocked connect is still recoverable from the dashboard
|
|
// rather than orphaning a finalized OCIRepository.
|
|
return r.deleteOrphanTapSource(ctx, name, deleteDryRun(opts))
|
|
}
|
|
return nil, false, apierrors.NewInternalError(fmt.Errorf("get PackageSource %q: %w", name, err))
|
|
}
|
|
var ps cozyv1alpha1.PackageSource
|
|
if err := fromUnstructured(u, &ps); err != nil {
|
|
return nil, false, apierrors.NewInternalError(fmt.Errorf("decode PackageSource %q: %w", name, err))
|
|
}
|
|
// A tap is identified by its marker label, not a name prefix; official
|
|
// PackageSources (no label) are protected from disconnect.
|
|
if ps.GetLabels()[tapconst.Label] != "true" {
|
|
return nil, false, apierrors.NewForbidden(r.gvr.GroupResource(), name,
|
|
fmt.Errorf("%q is not a tapped repository; official sources are protected", name))
|
|
}
|
|
|
|
idx := r.appDefIndex(ctx)
|
|
tap := buildTap(ps, idx)
|
|
if deleteValidation != nil {
|
|
if err := deleteValidation(ctx, &tap); err != nil {
|
|
return nil, false, err
|
|
}
|
|
}
|
|
|
|
// Remove the tap-managed registration Package FIRST, so the repository's apps
|
|
// de-register from the catalog (deleting it garbage-collects the registration
|
|
// HelmReleases and their ApplicationDefinitions). It is deleted only when it
|
|
// belongs to THIS source (label AND source annotation): a Package a later tap
|
|
// created under a reused name, or a foreign Package, is left in place.
|
|
//
|
|
// Package before PackageSource is deliberate: if the Package delete fails, the
|
|
// PackageSource is still present, so a repeat disconnect re-enters this path
|
|
// and retries; deleting the PackageSource first would drop a repeat disconnect
|
|
// into deleteOrphanTapSource, which never revisits the Package, stranding it.
|
|
srcName := ""
|
|
if ps.Spec.SourceRef != nil {
|
|
srcName = ps.Spec.SourceRef.Name
|
|
}
|
|
if pu, err := r.dyn.Resource(gvrPackages).Get(ctx, name, metav1.GetOptions{}); err == nil {
|
|
// Delete only a managed registration Package (owned AND still at the auto
|
|
// default variant), the same predicate the materializer and untap use, so
|
|
// a user's pinned install is never removed by disconnect.
|
|
variant, _, _ := unstructured.NestedString(pu.Object, "spec", "variant")
|
|
if collision.ManagedRegistration(pu, srcName, variant) {
|
|
// UID + ResourceVersion preconditions: delete only this exact object,
|
|
// not one the user replaced or pinned in-place between Get and Delete.
|
|
uid := pu.GetUID()
|
|
rv := pu.GetResourceVersion()
|
|
delOpts := metav1.DeleteOptions{DryRun: deleteDryRun(opts), Preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &rv}}
|
|
// A conflict is tolerated here (unlike the operator's retry loop): the
|
|
// managed registration Package carries an ownerReference TO its
|
|
// PackageSource, and disconnect deletes that PackageSource next, so
|
|
// garbage collection reaps a Package this delete missed; a Package the
|
|
// user pinned in the gap has shed that ownerRef (pinRegistrationToUser)
|
|
// and is correctly spared.
|
|
if err := r.dyn.Resource(gvrPackages).Delete(ctx, name, delOpts); err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) {
|
|
return nil, false, apierrors.NewInternalError(fmt.Errorf("delete registration Package %q: %w", name, err))
|
|
}
|
|
}
|
|
} else if !apierrors.IsNotFound(err) {
|
|
return nil, false, apierrors.NewInternalError(fmt.Errorf("check registration Package %q: %w", name, err))
|
|
}
|
|
|
|
if err := r.dyn.Resource(gvrPackageSources).Delete(ctx, name, metav1.DeleteOptions{DryRun: deleteDryRun(opts)}); err != nil {
|
|
return nil, false, apierrors.NewInternalError(fmt.Errorf("delete PackageSource %q: %w", name, err))
|
|
}
|
|
|
|
// Remove the Flux source too, but only when no other PackageSource still
|
|
// references it. Installed Packages are intentionally left untouched.
|
|
if ref := ps.Spec.SourceRef; ref != nil && ref.Kind == "OCIRepository" && ref.Name != "" {
|
|
others, err := r.fetchPackageSources(ctx)
|
|
if err == nil && !anyOtherReferences(others, ref.Name, name) {
|
|
ns := ref.Namespace
|
|
if ns == "" {
|
|
ns = "cozy-system"
|
|
}
|
|
if err := r.dyn.Resource(gvrOCIRepos).Namespace(ns).Delete(ctx, ref.Name, metav1.DeleteOptions{DryRun: deleteDryRun(opts)}); err != nil && !apierrors.IsNotFound(err) {
|
|
klog.V(2).InfoS("tap disconnected but its OCIRepository could not be deleted", "source", ref.Name, "err", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
return &tap, true, nil
|
|
}
|
|
|
|
// deleteOrphanTapSource removes a tap whose OCIRepository exists but whose
|
|
// PackageSource has not been materialized. It matches the labeled OCIRepository
|
|
// carrying the tap-name annotation and deletes it.
|
|
func (r *REST) deleteOrphanTapSource(ctx context.Context, name string, dryRun []string) (runtime.Object, bool, error) {
|
|
list, err := r.dyn.Resource(gvrOCIRepos).Namespace("cozy-system").List(ctx, metav1.ListOptions{
|
|
LabelSelector: tapconst.Label + "=true",
|
|
})
|
|
if err != nil {
|
|
return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name)
|
|
}
|
|
for i := range list.Items {
|
|
item := &list.Items[i]
|
|
if item.GetAnnotations()[tapconst.NameAnnotation] != name {
|
|
continue
|
|
}
|
|
if err := r.dyn.Resource(gvrOCIRepos).Namespace("cozy-system").Delete(ctx, item.GetName(), metav1.DeleteOptions{DryRun: dryRun}); err != nil && !apierrors.IsNotFound(err) {
|
|
return nil, false, apierrors.NewInternalError(fmt.Errorf("delete tap source %q: %w", item.GetName(), err))
|
|
}
|
|
tap := &corev1alpha1.Tap{
|
|
TypeMeta: metav1.TypeMeta{APIVersion: corev1alpha1.SchemeGroupVersion.String(), Kind: "Tap"},
|
|
ObjectMeta: metav1.ObjectMeta{Name: name, ResourceVersion: "0"},
|
|
Spec: corev1alpha1.TapSpec{Community: true},
|
|
}
|
|
return tap, true, nil
|
|
}
|
|
return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name)
|
|
}
|
|
|
|
// fetchPackageSources lists the cluster-scoped PackageSources as typed objects.
|
|
func (r *REST) fetchPackageSources(ctx context.Context) ([]cozyv1alpha1.PackageSource, error) {
|
|
ul, err := r.dyn.Resource(gvrPackageSources).List(ctx, metav1.ListOptions{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]cozyv1alpha1.PackageSource, 0, len(ul.Items))
|
|
for i := range ul.Items {
|
|
var ps cozyv1alpha1.PackageSource
|
|
if err := fromUnstructured(&ul.Items[i], &ps); err != nil {
|
|
klog.V(2).InfoS("skipping undecodable PackageSource", "name", ul.Items[i].GetName(), "err", err)
|
|
continue
|
|
}
|
|
out = append(out, ps)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// appDefIndex lists ApplicationDefinitions and indexes them by chartRef name. A
|
|
// list failure is tolerated (the catalog degrades to taps with no packages)
|
|
// rather than failing the whole marketplace view.
|
|
func (r *REST) appDefIndex(ctx context.Context) map[string]cozyv1alpha1.ApplicationDefinition {
|
|
ul, err := r.dyn.Resource(gvrAppDefs).List(ctx, metav1.ListOptions{})
|
|
if err != nil {
|
|
klog.V(2).InfoS("could not list ApplicationDefinitions for tap catalog", "err", err)
|
|
return map[string]cozyv1alpha1.ApplicationDefinition{}
|
|
}
|
|
ads := make([]cozyv1alpha1.ApplicationDefinition, 0, len(ul.Items))
|
|
for i := range ul.Items {
|
|
var ad cozyv1alpha1.ApplicationDefinition
|
|
if err := fromUnstructured(&ul.Items[i], &ad); err != nil {
|
|
klog.V(2).InfoS("skipping undecodable ApplicationDefinition", "name", ul.Items[i].GetName(), "err", err)
|
|
continue
|
|
}
|
|
ads = append(ads, ad)
|
|
}
|
|
return indexAppDefsByChartRef(ads)
|
|
}
|
|
|
|
func fromUnstructured(u *unstructured.Unstructured, target any) error {
|
|
return runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, target)
|
|
}
|
|
|
|
// -----------------------------------------------------------------------------
|
|
// Watcher (one-shot): emit the current state once, then block until the client
|
|
// or server cancels, mirroring the Option resource. Closing the channel early
|
|
// makes the apiserver treat the watch as ended and reconnect in a tight loop.
|
|
// -----------------------------------------------------------------------------
|
|
|
|
func (r *REST) Watch(ctx context.Context, opts *metainternal.ListOptions) (watch.Interface, error) {
|
|
events := make(chan watch.Event)
|
|
pw := watch.NewProxyWatcher(events)
|
|
|
|
go func() {
|
|
defer pw.Stop()
|
|
listObj, err := r.List(ctx, opts)
|
|
if err == nil {
|
|
list := listObj.(*corev1alpha1.TapList)
|
|
for i := range list.Items {
|
|
select {
|
|
case events <- watch.Event{Type: watch.Added, Object: &list.Items[i]}:
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
} else {
|
|
klog.V(2).InfoS("tap watch: initial list failed", "err", err)
|
|
}
|
|
<-ctx.Done()
|
|
}()
|
|
|
|
return pw, nil
|
|
}
|
|
|
|
// -----------------------------------------------------------------------------
|
|
// TableConvertor
|
|
// -----------------------------------------------------------------------------
|
|
|
|
func (r *REST) ConvertToTable(_ context.Context, obj runtime.Object, _ runtime.Object) (*metav1.Table, error) {
|
|
row := func(t *corev1alpha1.Tap) metav1.TableRow {
|
|
return metav1.TableRow{
|
|
Cells: []any{t.Name, t.Spec.Source.Kind, t.Spec.Ready, len(t.Spec.Packages)},
|
|
Object: runtime.RawExtension{Object: t},
|
|
}
|
|
}
|
|
tbl := &metav1.Table{
|
|
TypeMeta: metav1.TypeMeta{APIVersion: "meta.k8s.io/v1", Kind: "Table"},
|
|
ColumnDefinitions: []metav1.TableColumnDefinition{
|
|
{Name: "NAME", Type: "string"},
|
|
{Name: "SOURCE", Type: "string"},
|
|
{Name: "READY", Type: "boolean"},
|
|
{Name: "PACKAGES", Type: "integer"},
|
|
},
|
|
}
|
|
switch v := obj.(type) {
|
|
case *corev1alpha1.TapList:
|
|
for i := range v.Items {
|
|
tbl.Rows = append(tbl.Rows, row(&v.Items[i]))
|
|
}
|
|
tbl.ResourceVersion = v.ResourceVersion
|
|
case *corev1alpha1.Tap:
|
|
tbl.Rows = append(tbl.Rows, row(v))
|
|
tbl.ResourceVersion = v.ResourceVersion
|
|
default:
|
|
return nil, notAcceptable{r.gvr.GroupResource(), fmt.Sprintf("unexpected %T", obj)}
|
|
}
|
|
return tbl, nil
|
|
}
|
|
|
|
type notAcceptable struct {
|
|
resource schema.GroupResource
|
|
message string
|
|
}
|
|
|
|
func (e notAcceptable) Error() string { return e.message }
|
|
func (e notAcceptable) Status() metav1.Status {
|
|
return metav1.Status{
|
|
Status: metav1.StatusFailure,
|
|
Code: http.StatusNotAcceptable,
|
|
Reason: metav1.StatusReason("NotAcceptable"),
|
|
Message: e.message,
|
|
}
|
|
}
|