mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-04 14:12:07 +09:00
fix(backups): re-render the default backup objects when the S3 endpoint changes
The S3 endpoint the platform backups use is copied twice and neither
copy is refreshed. The COSI sidecar writes BucketInfo once per
BucketAccess, so the credentials Secret rendered from it keeps its
endpoint, and the Velero BSL and the default Strategy CRs keep whatever
endpoint the last render of backupstrategy-controller saw. The default
objects gate only acted on objects that were missing, so after a
publishing.host change every backup kept going to the old host with
nothing reporting it.
The gate now also forces a render when a copy is stale: the bucket's
<bucket>-system release when the credentials Secret's endpoint differs
from the COSI Secret it is rendered from, and backupstrategy-controller
when the endpoint an object was rendered with differs from the
credentials Secret's. That endpoint sits at a different path in every
kind, in some only as a bare host, so the chart stamps the rendered
value on each object as backups.cozystack.io/endpoint and the gate
compares that. Objects rendered before the annotation existed count as
stale until one forced render has gone through, which stamps it.
The COSI Secret itself still holds the endpoint the BucketAccess was
granted with; it follows a host change only once the BucketAccess is
re-granted.
Assisted-by: LLM
Signed-off-by: Alexey Artamonov <aleksei.artamonov@aenix.io>
(cherry picked from commit cd91138f33)
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
This commit is contained in:
1 parent
a14ad50b1e
commit
e8fef61fa1
21 files changed
+678
-36
No files matched your search
@@ -2,10 +2,12 @@ package backupcontroller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-logr/logr"
|
||||
@@ -91,6 +93,11 @@ const (
|
||||
// same lookup-gated template as the Strategy CRs, so it belongs to the
|
||||
// same existence check.
|
||||
defaultBackupStorageLocationName = "cozy-default"
|
||||
|
||||
// endpointAnnotation carries the S3 endpoint the chart rendered into the
|
||||
// object. The endpoint itself sits at a different path in every kind,
|
||||
// and in some only as a bare host, so the gate compares this instead.
|
||||
endpointAnnotation = "backups.cozystack.io/endpoint"
|
||||
)
|
||||
|
||||
var backupStorageLocationGVR = schema.GroupVersionResource{
|
||||
@@ -157,6 +164,14 @@ type DefaultObjectsGate struct {
|
||||
// then admin-managed and no release renders it, so there is nothing
|
||||
// to force.
|
||||
CredentialsHelmRelease types.NamespacedName
|
||||
// CredentialsCOSISecretName is the Secret the COSI sidecar writes for the
|
||||
// platform bucket's BucketAccess, in Config.SourceNamespace, from which
|
||||
// CredentialsHelmRelease renders the credentials Secret. The sidecar
|
||||
// writes it once per BucketAccess, so after a publishing.host change a
|
||||
// re-granted BucketAccess carries the new endpoint while the credentials
|
||||
// Secret keeps the old one; the gate compares the two. Empty disables
|
||||
// the comparison.
|
||||
CredentialsCOSISecretName string
|
||||
// VeleroNamespace is where the cozy-default BackupStorageLocation
|
||||
// lives. Empty skips the BSL check (velero.bslEnabled=false).
|
||||
VeleroNamespace string
|
||||
@@ -177,6 +192,11 @@ type DefaultObjectsGate struct {
|
||||
// MinForceInterval for no reason.
|
||||
lastForce time.Time
|
||||
lastCredentialsForce time.Time
|
||||
// renderForced records that a forced render of HelmRelease went through.
|
||||
// That render stamps endpointAnnotation on every object the chart
|
||||
// renders, so from then on an object without it (one rendered by a chart
|
||||
// that predates the annotation) is not counted as stale again.
|
||||
renderForced bool
|
||||
}
|
||||
|
||||
// errHelmReleaseSuspended reports that the target release has
|
||||
@@ -285,10 +305,10 @@ func (g *DefaultObjectsGate) checkAndLog(ctx context.Context, logger logr.Logger
|
||||
// The release named here is whichever one renders what is missing:
|
||||
// the credentials Secret comes from the bucket's <bucket>-system
|
||||
// release, everything else from this chart's own.
|
||||
logger.Info("forced a Helm upgrade to create missing default backup objects",
|
||||
logger.Info("forced a Helm upgrade to create missing or stale default backup objects",
|
||||
"helmRelease", g.forcedReleaseFor(missing).String(), "missing", missing)
|
||||
case len(missing) > 0:
|
||||
logger.Info("default backup objects still missing, no force issued on this tick",
|
||||
logger.Info("default backup objects still missing or stale, no force issued on this tick",
|
||||
"helmRelease", g.forcedReleaseFor(missing).String(), "missing", missing,
|
||||
"minForceInterval", g.MinForceInterval.String())
|
||||
default:
|
||||
@@ -302,7 +322,7 @@ func (g *DefaultObjectsGate) checkAndLog(ctx context.Context, logger logr.Logger
|
||||
// resolving the bucket name is a precondition for checking those at all.
|
||||
func (g *DefaultObjectsGate) forcedReleaseFor(missing []string) types.NamespacedName {
|
||||
credsKey := fmt.Sprintf("Secret/%s", g.Config.SourceSecretName)
|
||||
if len(missing) == 1 && missing[0] == credsKey && g.CredentialsHelmRelease.Name != "" {
|
||||
if len(missing) == 1 && (missing[0] == credsKey || strings.HasPrefix(missing[0], credsKey+" ")) && g.CredentialsHelmRelease.Name != "" {
|
||||
return g.CredentialsHelmRelease
|
||||
}
|
||||
return g.HelmRelease
|
||||
@@ -345,23 +365,95 @@ func (g *DefaultObjectsGate) Check(ctx context.Context) ([]string, bool, error)
|
||||
return g.reconcileCredentials(ctx)
|
||||
}
|
||||
|
||||
// The objects below are rendered from this Secret, so while it is stale
|
||||
// they would only be re-rendered with the same stale endpoint.
|
||||
stale, err := g.staleCredentials(ctx, src)
|
||||
if err != nil {
|
||||
defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc()
|
||||
return nil, false, err
|
||||
}
|
||||
if stale != "" {
|
||||
return g.force(ctx, g.CredentialsHelmRelease, &g.lastCredentialsForce, []string{stale})
|
||||
}
|
||||
|
||||
backupClass := &backupsv1alpha1.BackupClass{}
|
||||
if err := g.Client.Get(ctx, client.ObjectKey{Name: g.BackupClassName}, backupClass); err != nil {
|
||||
defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc()
|
||||
return nil, false, fmt.Errorf("get BackupClass %s: %w", g.BackupClassName, err)
|
||||
}
|
||||
|
||||
missing, err := g.missingObjects(ctx, backupClass)
|
||||
// With provisionBucket=false (no bucket release) the chart renders
|
||||
// backupStorage.endpoint rather than the Secret's, so the two may
|
||||
// legitimately differ and there is nothing to compare.
|
||||
want := ""
|
||||
if g.CredentialsHelmRelease.Name != "" {
|
||||
want = renderedEndpointFor(src.Data["endpoint"])
|
||||
}
|
||||
state, err := g.inspectObjects(ctx, backupClass, want)
|
||||
if err != nil {
|
||||
defaultObjectsCheckErrors.WithLabelValues(g.BackupClassName).Inc()
|
||||
return nil, false, err
|
||||
}
|
||||
defaultObjectsMissing.WithLabelValues(g.BackupClassName).Set(float64(len(missing)))
|
||||
if len(missing) == 0 {
|
||||
defaultObjectsMissing.WithLabelValues(g.BackupClassName).Set(float64(len(state.missing)))
|
||||
needed := append(state.missing, state.stale...)
|
||||
if len(needed) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
sort.Strings(needed)
|
||||
|
||||
return g.force(ctx, g.HelmRelease, &g.lastForce, missing)
|
||||
needed, forced, err := g.force(ctx, g.HelmRelease, &g.lastForce, needed)
|
||||
if forced {
|
||||
g.renderForced = true
|
||||
}
|
||||
return needed, forced, err
|
||||
}
|
||||
|
||||
// staleCredentials reports the credentials Secret, formatted for logs, when
|
||||
// its endpoint differs from the one in the COSI Secret it is rendered from,
|
||||
// comparing against what packages/system/bucket/templates/user-credentials.yaml
|
||||
// writes for it. The COSI Secret being absent (the BucketAccess is being
|
||||
// re-granted) leaves nothing to compare against and is not staleness.
|
||||
func (g *DefaultObjectsGate) staleCredentials(ctx context.Context, src *corev1.Secret) (string, error) {
|
||||
if g.CredentialsCOSISecretName == "" || g.CredentialsHelmRelease.Name == "" || g.CredentialsHelmRelease.Namespace == "" {
|
||||
return "", nil
|
||||
}
|
||||
cosi := &corev1.Secret{}
|
||||
key := types.NamespacedName{Namespace: g.Config.SourceNamespace, Name: g.CredentialsCOSISecretName}
|
||||
if err := g.Client.Get(ctx, key, cosi); err != nil {
|
||||
if apierrors.IsNotFound(err) {
|
||||
return "", nil
|
||||
}
|
||||
return "", fmt.Errorf("get COSI Secret %s: %w", key, err)
|
||||
}
|
||||
var info struct {
|
||||
Spec struct {
|
||||
SecretS3 struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
} `json:"secretS3"`
|
||||
} `json:"spec"`
|
||||
}
|
||||
if err := json.Unmarshal(cosi.Data["BucketInfo"], &info); err != nil {
|
||||
return "", fmt.Errorf("parse BucketInfo of COSI Secret %s: %w", key, err)
|
||||
}
|
||||
want := strings.TrimPrefix(strings.TrimPrefix(info.Spec.SecretS3.Endpoint, "https://"), "http://")
|
||||
have := string(src.Data["endpoint"])
|
||||
if have == want {
|
||||
return "", nil
|
||||
}
|
||||
return fmt.Sprintf("Secret/%s (endpoint %q, COSI Secret has %q)", g.Config.SourceSecretName, have, want), nil
|
||||
}
|
||||
|
||||
// renderedEndpointFor mirrors the "backupstrategy-controller.endpoint" helper
|
||||
// for a provisioned bucket: the credentials Secret's endpoint, trimmed, with
|
||||
// any scheme replaced by https://. It is the value the chart stamps as
|
||||
// endpointAnnotation. An empty endpoint makes the helper fall back to
|
||||
// backupStorage.endpoint, which the gate cannot see, so it returns "".
|
||||
func renderedEndpointFor(raw []byte) string {
|
||||
host := strings.TrimSpace(string(raw))
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
return "https://" + strings.TrimPrefix(strings.TrimPrefix(host, "https://"), "http://")
|
||||
}
|
||||
|
||||
// reconcileCredentials handles the one object the gate cannot check the same
|
||||
@@ -431,16 +523,42 @@ func (g *DefaultObjectsGate) force(ctx context.Context, target types.NamespacedN
|
||||
return missing, true, nil
|
||||
}
|
||||
|
||||
// missingObjects returns a sorted, de-duplicated list of the
|
||||
// defaultObjectsState is what inspectObjects found: the objects that do not
|
||||
// exist, and the existing ones rendered with an endpoint other than the one
|
||||
// the chart would render now.
|
||||
type defaultObjectsState struct {
|
||||
missing []string
|
||||
stale []string
|
||||
}
|
||||
|
||||
// staleEndpoint reports an existing object rendered with another endpoint
|
||||
// than want, formatted for logs. An empty want disables the comparison.
|
||||
func (g *DefaultObjectsGate) staleEndpoint(state *defaultObjectsState, key string, obj *unstructured.Unstructured, want string) {
|
||||
if want == "" {
|
||||
return
|
||||
}
|
||||
have, ok := obj.GetAnnotations()[endpointAnnotation]
|
||||
switch {
|
||||
case !ok:
|
||||
if !g.renderForced {
|
||||
state.stale = append(state.stale, key+" (no endpoint annotation)")
|
||||
}
|
||||
case have != want:
|
||||
state.stale = append(state.stale, fmt.Sprintf("%s (endpoint %q, want %q)", key, have, want))
|
||||
}
|
||||
}
|
||||
|
||||
// inspectObjects returns a sorted, de-duplicated list of the
|
||||
// "<kind>/<name>" objects the BackupClass references that do not exist,
|
||||
// plus the Velero BSL when a Velero namespace is configured.
|
||||
// plus the Velero BSL when a Velero namespace is configured, and the existing
|
||||
// ones whose endpointAnnotation differs from want.
|
||||
//
|
||||
// An unmappable group/kind (the CRD is not installed) is NOT reported as
|
||||
// missing: no Helm re-render can create an object whose CRD is absent, and
|
||||
// counting it would keep the gate forcing upgrades forever.
|
||||
func (g *DefaultObjectsGate) missingObjects(ctx context.Context, backupClass *backupsv1alpha1.BackupClass) ([]string, error) {
|
||||
func (g *DefaultObjectsGate) inspectObjects(ctx context.Context, backupClass *backupsv1alpha1.BackupClass, want string) (defaultObjectsState, error) {
|
||||
seen := map[string]struct{}{}
|
||||
var missing []string
|
||||
var state defaultObjectsState
|
||||
|
||||
for _, strategy := range backupClass.Spec.Strategies {
|
||||
name := strategy.StrategyRef.Name
|
||||
@@ -472,17 +590,18 @@ func (g *DefaultObjectsGate) missingObjects(ctx context.Context, backupClass *ba
|
||||
if meta.IsNoMatchError(err) {
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("map %s/%s: %w", group, kind, err)
|
||||
return defaultObjectsState{}, fmt.Errorf("map %s/%s: %w", group, kind, err)
|
||||
}
|
||||
// Strategy CRs are cluster-scoped; Namespace("") is correct for
|
||||
// both scopes on the dynamic client.
|
||||
_, err = g.Resource(mapping.Resource).Get(ctx, name, metav1.GetOptions{})
|
||||
obj, err := g.Resource(mapping.Resource).Get(ctx, name, metav1.GetOptions{})
|
||||
switch {
|
||||
case err == nil:
|
||||
g.staleEndpoint(&state, key, obj, want)
|
||||
case apierrors.IsNotFound(err):
|
||||
missing = append(missing, key)
|
||||
state.missing = append(state.missing, key)
|
||||
default:
|
||||
return nil, fmt.Errorf("get %s %s: %w", kind, name, err)
|
||||
return defaultObjectsState{}, fmt.Errorf("get %s %s: %w", kind, name, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -496,24 +615,26 @@ func (g *DefaultObjectsGate) missingObjects(ctx context.Context, backupClass *ba
|
||||
mapping, err := g.RESTMapping(schema.GroupKind{Group: backupStorageLocationGVR.Group, Kind: "BackupStorageLocation"})
|
||||
switch {
|
||||
case err == nil:
|
||||
_, getErr := g.Resource(mapping.Resource).Namespace(g.VeleroNamespace).Get(ctx, defaultBackupStorageLocationName, metav1.GetOptions{})
|
||||
key := fmt.Sprintf("BackupStorageLocation/%s", defaultBackupStorageLocationName)
|
||||
obj, getErr := g.Resource(mapping.Resource).Namespace(g.VeleroNamespace).Get(ctx, defaultBackupStorageLocationName, metav1.GetOptions{})
|
||||
switch {
|
||||
case getErr == nil:
|
||||
g.staleEndpoint(&state, key, obj, want)
|
||||
case apierrors.IsNotFound(getErr):
|
||||
missing = append(missing, fmt.Sprintf("BackupStorageLocation/%s", defaultBackupStorageLocationName))
|
||||
state.missing = append(state.missing, key)
|
||||
default:
|
||||
return nil, fmt.Errorf("get BackupStorageLocation %s: %w", defaultBackupStorageLocationName, getErr)
|
||||
return defaultObjectsState{}, fmt.Errorf("get BackupStorageLocation %s: %w", defaultBackupStorageLocationName, getErr)
|
||||
}
|
||||
case meta.IsNoMatchError(err):
|
||||
// Velero API not served (e.g. Velero uninstalled after bootstrap):
|
||||
// no Helm re-render can create the BSL, so it is not "missing".
|
||||
default:
|
||||
return nil, fmt.Errorf("map BackupStorageLocation: %w", err)
|
||||
return defaultObjectsState{}, fmt.Errorf("map BackupStorageLocation: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
sort.Strings(missing)
|
||||
return missing, nil
|
||||
sort.Strings(state.missing)
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// forceHelmRelease stamps BOTH reconcile.fluxcd.io/forceAt and
|
||||
|
||||
@@ -2,6 +2,8 @@ package backupcontroller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -18,6 +20,7 @@ import (
|
||||
k8stesting "k8s.io/client-go/testing"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
|
||||
|
||||
backupsv1alpha1 "github.com/cozystack/cozystack/api/backups/v1alpha1"
|
||||
)
|
||||
@@ -110,14 +113,60 @@ func cozyDefaultBackupClass() *backupsv1alpha1.BackupClass {
|
||||
}
|
||||
}
|
||||
|
||||
// renderedEndpoint is what the chart stamps on every default object for the
|
||||
// endpoint sourceSecret carries: the steady state after a render that saw it.
|
||||
const renderedEndpoint = "https://s3.example.com"
|
||||
|
||||
func strategyObject(kind, name string) *unstructured.Unstructured {
|
||||
u := &unstructured.Unstructured{}
|
||||
u.SetAPIVersion(strategyAPIGroup + "/v1alpha1")
|
||||
u.SetKind(kind)
|
||||
u.SetName(name)
|
||||
u.SetAnnotations(map[string]string{endpointAnnotation: renderedEndpoint})
|
||||
return u
|
||||
}
|
||||
|
||||
func withEndpoint(u *unstructured.Unstructured, endpoint string) *unstructured.Unstructured {
|
||||
u.SetAnnotations(map[string]string{endpointAnnotation: endpoint})
|
||||
return u
|
||||
}
|
||||
|
||||
// unannotated is an object rendered by a chart that predates the endpoint
|
||||
// annotation.
|
||||
func unannotated(u *unstructured.Unstructured) *unstructured.Unstructured {
|
||||
u.SetAnnotations(nil)
|
||||
return u
|
||||
}
|
||||
|
||||
// allDefaultObjects is every object cozy-default routes to, plus the BSL, as
|
||||
// the chart renders them for sourceSecret's endpoint.
|
||||
func allDefaultObjects() []runtime.Object {
|
||||
return []runtime.Object{
|
||||
strategyObject("CNPG", "cozy-default-cnpg"),
|
||||
strategyObject("MariaDB", "cozy-default-mariadb"),
|
||||
strategyObject("Etcd", "cozy-default-etcd"),
|
||||
strategyObject("Altinity", "cozy-default-altinity"),
|
||||
strategyObject("Velero", "cozy-default-velero-vminstance"),
|
||||
strategyObject("Velero", "cozy-default-velero-vmdisk"),
|
||||
bslObject(),
|
||||
}
|
||||
}
|
||||
|
||||
// cosiSecret is the Secret the COSI sidecar writes for the platform bucket's
|
||||
// BucketAccess, which user-credentials.yaml renders the credentials Secret
|
||||
// from. The BucketInfo document is one read off a live cluster, with the keys
|
||||
// and the host replaced.
|
||||
func cosiSecret(endpoint string) *corev1.Secret {
|
||||
bucketInfo := `{"metadata": {"name": "bc-b8e30337-1821-418f-a4dd-163e8016aaee", "creationTimestamp": null}, ` +
|
||||
`"spec": {"bucketName": "bucket-1a2b", "authenticationType": "KEY", ` +
|
||||
`"secretS3": {"endpoint": "` + endpoint + `", "region": "", "accessKeyID": "AK", "accessSecretKey": "SK"}, ` +
|
||||
`"secretAzure": null, "protocols": ["s3"]}}`
|
||||
return &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{Namespace: "tenant-root", Name: "bucket-cozy-backups-system"},
|
||||
Data: map[string][]byte{"BucketInfo": []byte(bucketInfo)},
|
||||
}
|
||||
}
|
||||
|
||||
func helmReleaseObject() *unstructured.Unstructured {
|
||||
u := &unstructured.Unstructured{}
|
||||
u.SetAPIVersion("helm.toolkit.fluxcd.io/v2")
|
||||
@@ -163,9 +212,10 @@ func newGate(t *testing.T, ctrlObjs []client.Object, dynObjs ...runtime.Object)
|
||||
Namespace: "tenant-root",
|
||||
Name: "bucket-cozy-backups-system",
|
||||
},
|
||||
VeleroNamespace: "cozy-velero",
|
||||
MinForceInterval: 5 * time.Minute,
|
||||
now: func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) },
|
||||
CredentialsCOSISecretName: "bucket-cozy-backups-system",
|
||||
VeleroNamespace: "cozy-velero",
|
||||
MinForceInterval: 5 * time.Minute,
|
||||
now: func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) },
|
||||
}
|
||||
g.Interface = dyn
|
||||
g.RESTMapper = gateRESTMapper()
|
||||
@@ -193,6 +243,7 @@ func bslObject() *unstructured.Unstructured {
|
||||
u.SetKind("BackupStorageLocation")
|
||||
u.SetNamespace("cozy-velero")
|
||||
u.SetName(defaultBackupStorageLocationName)
|
||||
u.SetAnnotations(map[string]string{endpointAnnotation: renderedEndpoint})
|
||||
return u
|
||||
}
|
||||
|
||||
@@ -259,7 +310,7 @@ func TestCheckForcesWhenObjectsMissing(t *testing.T) {
|
||||
// the cluster.
|
||||
func TestCheckNoopWhenAllPresent(t *testing.T) {
|
||||
g, dyn := newGate(t,
|
||||
[]client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()},
|
||||
[]client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.example.com"), cozyDefaultBackupClass()},
|
||||
helmReleaseObject(),
|
||||
strategyObject("CNPG", "cozy-default-cnpg"),
|
||||
strategyObject("MariaDB", "cozy-default-mariadb"),
|
||||
@@ -550,10 +601,11 @@ func TestMissingObjectsIgnoresUnmappedKinds(t *testing.T) {
|
||||
bslObject(),
|
||||
)
|
||||
|
||||
missing, err := g.missingObjects(context.Background(), bc)
|
||||
state, err := g.inspectObjects(context.Background(), bc, "")
|
||||
if err != nil {
|
||||
t.Fatalf("missingObjects: %v", err)
|
||||
t.Fatalf("inspectObjects: %v", err)
|
||||
}
|
||||
missing := state.missing
|
||||
if len(missing) != 0 {
|
||||
t.Fatalf("missing = %v, want none (unmapped kind must be ignored)", missing)
|
||||
}
|
||||
@@ -579,10 +631,11 @@ func TestMissingObjectsSkipsVeleroWhenNamespaceEmpty(t *testing.T) {
|
||||
)
|
||||
g.VeleroNamespace = ""
|
||||
|
||||
missing, err := g.missingObjects(context.Background(), bc)
|
||||
state, err := g.inspectObjects(context.Background(), bc, "")
|
||||
if err != nil {
|
||||
t.Fatalf("missingObjects: %v", err)
|
||||
t.Fatalf("inspectObjects: %v", err)
|
||||
}
|
||||
missing := state.missing
|
||||
if len(missing) != 0 {
|
||||
t.Fatalf("missing = %v, want none when Velero is disabled", missing)
|
||||
}
|
||||
@@ -630,10 +683,11 @@ func TestMissingObjectsSkipsBSLWhenVeleroAPIAbsent(t *testing.T) {
|
||||
}
|
||||
g.RESTMapper = m
|
||||
|
||||
missing, err := g.missingObjects(context.Background(), bc)
|
||||
state, err := g.inspectObjects(context.Background(), bc, "")
|
||||
if err != nil {
|
||||
t.Fatalf("missingObjects: %v", err)
|
||||
t.Fatalf("inspectObjects: %v", err)
|
||||
}
|
||||
missing := state.missing
|
||||
if len(missing) != 0 {
|
||||
t.Fatalf("missing = %v, want none when the Velero API is absent", missing)
|
||||
}
|
||||
@@ -744,3 +798,330 @@ func TestCheckToleratesAbsentHelmRelease(t *testing.T) {
|
||||
t.Error("objects should still be reported as missing")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckForcesCredentialsReleaseWhenEndpointStale covers the credentials
|
||||
// Secret outliving the endpoint it was rendered from. The COSI sidecar writes
|
||||
// BucketInfo once per BucketAccess, so a re-granted BucketAccess (after a
|
||||
// publishing.host change) carries the new endpoint while the credentials
|
||||
// Secret <bucket>-system rendered earlier keeps the old one: the Secret
|
||||
// exists, so the missing-Secret path never fires, and every consumer keeps
|
||||
// the dead host.
|
||||
func TestCheckForcesCredentialsReleaseWhenEndpointStale(t *testing.T) {
|
||||
objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...)
|
||||
g, dyn := newGate(t,
|
||||
[]client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.new.example.com"), cozyDefaultBackupClass()},
|
||||
objs...,
|
||||
)
|
||||
|
||||
missing, forced, err := g.Check(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Check: %v", err)
|
||||
}
|
||||
if !forced {
|
||||
t.Fatal("expected the bucket release forced while its credentials Secret carries a stale endpoint")
|
||||
}
|
||||
if len(missing) != 1 || !strings.HasPrefix(missing[0], "Secret/bucket-cozy-backups-system-credentials") {
|
||||
t.Fatalf("missing = %v, want the credentials Secret", missing)
|
||||
}
|
||||
if ann := credentialsForceAnnotations(t, dyn); ann["reconcile.fluxcd.io/forceAt"] == "" {
|
||||
t.Errorf("bucket release not forced: %v", ann)
|
||||
}
|
||||
// The objects were rendered from the stale Secret and agree with it;
|
||||
// re-rendering them before the Secret is fixed would bake the old
|
||||
// endpoint in again.
|
||||
if ann := forceAnnotations(t, dyn); len(ann) != 0 {
|
||||
t.Errorf("own HelmRelease forced while the credentials Secret is stale: %v", ann)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckCredentialsEndpointComparison pins the comparison against what
|
||||
// user-credentials.yaml writes for a given BucketInfo endpoint (the scheme
|
||||
// stripped, nothing else), so a Secret the chart rendered from the current
|
||||
// BucketInfo never counts as stale and the bucket release is not forced on
|
||||
// every throttle window.
|
||||
func TestCheckCredentialsEndpointComparison(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cosi string
|
||||
wantForce bool
|
||||
}{
|
||||
{"https scheme stripped", "https://s3.example.com", false},
|
||||
{"http scheme stripped", "http://s3.example.com", false},
|
||||
{"bare host", "s3.example.com", false},
|
||||
{"other host", "https://s3.new.example.com", true},
|
||||
{"other port", "https://s3.example.com:8443", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...)
|
||||
g, dyn := newGate(t,
|
||||
[]client.Object{sourceSecret("bucket-1a2b"), cosiSecret(tc.cosi), cozyDefaultBackupClass()},
|
||||
objs...,
|
||||
)
|
||||
if _, _, err := g.Check(context.Background()); err != nil {
|
||||
t.Fatalf("Check: %v", err)
|
||||
}
|
||||
forced := credentialsForceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"] != ""
|
||||
if forced != tc.wantForce {
|
||||
t.Fatalf("bucket release forced = %v, want %v", forced, tc.wantForce)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckSkipsCredentialsComparisonWithoutCOSISecret covers the window in
|
||||
// which the BucketAccess is being re-granted: the COSI Secret is gone and
|
||||
// there is nothing to compare against, which is not evidence of staleness.
|
||||
func TestCheckSkipsCredentialsComparisonWithoutCOSISecret(t *testing.T) {
|
||||
objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...)
|
||||
g, dyn := newGate(t,
|
||||
[]client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()},
|
||||
objs...,
|
||||
)
|
||||
|
||||
missing, forced, err := g.Check(context.Background())
|
||||
if err != nil || forced || len(missing) != 0 {
|
||||
t.Fatalf("missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err)
|
||||
}
|
||||
if ann := credentialsForceAnnotations(t, dyn); len(ann) != 0 {
|
||||
t.Errorf("bucket release forced with no COSI Secret to compare against: %v", ann)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckSkipsCredentialsComparisonWhenUnconfigured pins both switches that
|
||||
// turn the comparison off: no COSI Secret name, and no bucket release (external
|
||||
// S3, where the Secret is admin-managed and no BucketInfo backs it).
|
||||
func TestCheckSkipsCredentialsComparisonWhenUnconfigured(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
apply func(g *DefaultObjectsGate)
|
||||
}{
|
||||
{"no COSI Secret name", func(g *DefaultObjectsGate) { g.CredentialsCOSISecretName = "" }},
|
||||
{"no bucket release", func(g *DefaultObjectsGate) { g.CredentialsHelmRelease = types.NamespacedName{} }},
|
||||
{"no bucket release name", func(g *DefaultObjectsGate) { g.CredentialsHelmRelease.Name = "" }},
|
||||
{"no bucket release namespace", func(g *DefaultObjectsGate) { g.CredentialsHelmRelease.Namespace = "" }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...)
|
||||
g, dyn := newGate(t,
|
||||
[]client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.new.example.com"), cozyDefaultBackupClass()},
|
||||
objs...,
|
||||
)
|
||||
tc.apply(g)
|
||||
// The real API server rejects a Get with an empty name; the fake
|
||||
// answers NotFound, which would hide a lookup of an unset name.
|
||||
g.Client = interceptor.NewClient(g.Client.(client.WithWatch), interceptor.Funcs{
|
||||
Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
|
||||
if key.Name == "" {
|
||||
return errors.New("resource name may not be empty")
|
||||
}
|
||||
return c.Get(ctx, key, obj, opts...)
|
||||
},
|
||||
})
|
||||
missing, forced, err := g.Check(context.Background())
|
||||
if err != nil || forced || len(missing) != 0 {
|
||||
t.Fatalf("missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err)
|
||||
}
|
||||
if ann := credentialsForceAnnotations(t, dyn); len(ann) != 0 {
|
||||
t.Errorf("bucket release forced with the comparison disabled: %v", ann)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckReportsMalformedCOSISecret pins that a COSI Secret the gate cannot
|
||||
// read is an error the check counts, not a silent "not stale".
|
||||
func TestCheckReportsMalformedCOSISecret(t *testing.T) {
|
||||
defaultObjectsCheckErrors.Reset()
|
||||
bad := cosiSecret("")
|
||||
bad.Data["BucketInfo"] = []byte("{not json")
|
||||
objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...)
|
||||
g, _ := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), bad, cozyDefaultBackupClass()}, objs...)
|
||||
|
||||
if _, forced, err := g.Check(context.Background()); err == nil || forced {
|
||||
t.Fatalf("forced = %v, err = %v; want an error", forced, err)
|
||||
}
|
||||
if got := testutil.ToFloat64(defaultObjectsCheckErrors.WithLabelValues("cozy-default")); got != 1 {
|
||||
t.Fatalf("check errors = %v, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckForcesOwnReleaseWhenObjectEndpointStale is the second half of a
|
||||
// publishing.host change: the credentials Secret now carries the new
|
||||
// endpoint, but the BSL and the default Strategies baked the old one at the
|
||||
// last render of this chart and nothing re-renders them, so every backup
|
||||
// keeps going to the dead host.
|
||||
func TestCheckForcesOwnReleaseWhenObjectEndpointStale(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
stale *unstructured.Unstructured
|
||||
key string
|
||||
}{
|
||||
{"strategy", strategyObject("CNPG", "cozy-default-cnpg"), "CNPG/cozy-default-cnpg"},
|
||||
{"BSL", bslObject(), "BackupStorageLocation/cozy-default"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var objs []runtime.Object
|
||||
for _, o := range allDefaultObjects() {
|
||||
u := o.(*unstructured.Unstructured)
|
||||
if u.GetKind() == tc.stale.GetKind() && u.GetName() == tc.stale.GetName() {
|
||||
withEndpoint(u, "https://s3.old.example.com")
|
||||
}
|
||||
objs = append(objs, u)
|
||||
}
|
||||
objs = append(objs, helmReleaseObject(), credentialsHelmReleaseObject())
|
||||
g, dyn := newGate(t,
|
||||
[]client.Object{sourceSecret("bucket-1a2b"), cosiSecret("https://s3.example.com"), cozyDefaultBackupClass()},
|
||||
objs...,
|
||||
)
|
||||
|
||||
missing, forced, err := g.Check(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Check: %v", err)
|
||||
}
|
||||
if !forced {
|
||||
t.Fatal("expected this chart's release forced while an object carries a stale endpoint")
|
||||
}
|
||||
if len(missing) != 1 || !strings.HasPrefix(missing[0], tc.key+" ") {
|
||||
t.Fatalf("missing = %v, want only %s", missing, tc.key)
|
||||
}
|
||||
if ann := forceAnnotations(t, dyn); ann["reconcile.fluxcd.io/forceAt"] == "" {
|
||||
t.Errorf("own HelmRelease not forced: %v", ann)
|
||||
}
|
||||
if ann := credentialsForceAnnotations(t, dyn); len(ann) != 0 {
|
||||
t.Errorf("bucket release forced for a stale object: %v", ann)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckIgnoresObjectEndpointOnExternalS3 pins that the comparison is off
|
||||
// when no bucket release is configured: with provisionBucket=false the chart
|
||||
// renders backupStorage.endpoint, not the Secret's, so the two legitimately
|
||||
// differ and forcing would loop every MinForceInterval.
|
||||
func TestCheckIgnoresObjectEndpointOnExternalS3(t *testing.T) {
|
||||
objs := []runtime.Object{helmReleaseObject()}
|
||||
for _, o := range allDefaultObjects() {
|
||||
objs = append(objs, withEndpoint(o.(*unstructured.Unstructured), "https://minio.example.internal:9000"))
|
||||
}
|
||||
g, dyn := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, objs...)
|
||||
g.CredentialsHelmRelease = types.NamespacedName{}
|
||||
|
||||
missing, forced, err := g.Check(context.Background())
|
||||
if err != nil || forced || len(missing) != 0 {
|
||||
t.Fatalf("missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err)
|
||||
}
|
||||
if ann := forceAnnotations(t, dyn); len(ann) != 0 {
|
||||
t.Errorf("own HelmRelease forced on external S3: %v", ann)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckIgnoresObjectEndpointWithoutSecretEndpoint covers a credentials
|
||||
// Secret with no endpoint key: the chart then renders its values fallback,
|
||||
// which the gate cannot reproduce, so there is nothing to compare against.
|
||||
func TestCheckIgnoresObjectEndpointWithoutSecretEndpoint(t *testing.T) {
|
||||
src := sourceSecret("bucket-1a2b")
|
||||
delete(src.Data, "endpoint")
|
||||
objs := append([]runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}, allDefaultObjects()...)
|
||||
g, dyn := newGate(t, []client.Object{src, cozyDefaultBackupClass()}, objs...)
|
||||
|
||||
if _, forced, err := g.Check(context.Background()); err != nil || forced {
|
||||
t.Fatalf("forced = %v, err = %v; want a no-op", forced, err)
|
||||
}
|
||||
if ann := forceAnnotations(t, dyn); len(ann) != 0 {
|
||||
t.Errorf("own HelmRelease forced with no endpoint to compare against: %v", ann)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckForcesOnceForUnannotatedObjects covers objects rendered by a chart
|
||||
// that predates the endpoint annotation. Their endpoint is unknown, so they
|
||||
// are treated as stale until one forced render has gone through, which stamps
|
||||
// the annotation. A force that did not go through (throttled) does not count,
|
||||
// and once one has, an object still without the annotation (one the chart
|
||||
// does not render) must not force again every MinForceInterval.
|
||||
func TestCheckForcesOnceForUnannotatedObjects(t *testing.T) {
|
||||
base := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||
objs := []runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}
|
||||
for _, o := range allDefaultObjects() {
|
||||
objs = append(objs, unannotated(o.(*unstructured.Unstructured)))
|
||||
}
|
||||
g, dyn := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, objs...)
|
||||
g.lastForce = base.Add(-time.Minute)
|
||||
g.now = func() time.Time { return base }
|
||||
|
||||
if missing, forced, err := g.Check(context.Background()); err != nil || forced || len(missing) != 7 {
|
||||
t.Fatalf("throttled Check: missing = %v, forced = %v, err = %v; want 7 reported, none forced", missing, forced, err)
|
||||
}
|
||||
|
||||
g.now = func() time.Time { return base.Add(5 * time.Minute) }
|
||||
if _, forced, err := g.Check(context.Background()); err != nil || !forced {
|
||||
t.Fatalf("first unthrottled Check: forced = %v, err = %v; want forced", forced, err)
|
||||
}
|
||||
first := forceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"]
|
||||
|
||||
g.now = func() time.Time { return base.Add(time.Hour) }
|
||||
missing, forced, err := g.Check(context.Background())
|
||||
if err != nil || forced || len(missing) != 0 {
|
||||
t.Fatalf("after the forced render: missing = %v, forced = %v, err = %v; want a no-op", missing, forced, err)
|
||||
}
|
||||
if again := forceAnnotations(t, dyn)["reconcile.fluxcd.io/forceAt"]; again != first {
|
||||
t.Errorf("forced again for unannotated objects: %q, then %q", first, again)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckStillForcesStaleAfterUnannotatedForce pins that the once-only
|
||||
// treatment covers the missing annotation alone: an annotation that names the
|
||||
// wrong endpoint still forces after that.
|
||||
func TestCheckStillForcesStaleAfterUnannotatedForce(t *testing.T) {
|
||||
objs := []runtime.Object{helmReleaseObject(), credentialsHelmReleaseObject()}
|
||||
for _, o := range allDefaultObjects() {
|
||||
objs = append(objs, withEndpoint(o.(*unstructured.Unstructured), "https://s3.old.example.com"))
|
||||
}
|
||||
g, _ := newGate(t, []client.Object{sourceSecret("bucket-1a2b"), cozyDefaultBackupClass()}, objs...)
|
||||
g.renderForced = true
|
||||
|
||||
if _, forced, err := g.Check(context.Background()); err != nil || !forced {
|
||||
t.Fatalf("forced = %v, err = %v; want forced", forced, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenderedEndpointMatchesTheChart pins renderedEndpointFor to the
|
||||
// "backupstrategy-controller.endpoint" helper, which the chart stamps as the
|
||||
// annotation: trim, strip a scheme, force https://. Any divergence makes the
|
||||
// gate see every object as stale and force this release forever.
|
||||
func TestRenderedEndpointMatchesTheChart(t *testing.T) {
|
||||
for _, tc := range []struct{ in, want string }{
|
||||
{"s3.example.com", "https://s3.example.com"},
|
||||
{"s3.example.com\n", "https://s3.example.com"},
|
||||
{" s3.example.com ", "https://s3.example.com"},
|
||||
{"https://s3.example.com", "https://s3.example.com"},
|
||||
{"http://s3.example.com:8333", "https://s3.example.com:8333"},
|
||||
{"s3.example.com/prefix/", "https://s3.example.com/prefix/"},
|
||||
// No endpoint in the Secret: the chart renders its values fallback,
|
||||
// which the gate cannot reproduce, so it compares nothing.
|
||||
{"", ""},
|
||||
} {
|
||||
if got := renderedEndpointFor([]byte(tc.in)); got != tc.want {
|
||||
t.Errorf("renderedEndpointFor(%q) = %q, want %q", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestForcedReleaseForNamesTheStaleCredentialsRelease pins the release the
|
||||
// log line names: a stale credentials Secret is repaired by the bucket
|
||||
// release, like a missing one, and everything else by this chart's own.
|
||||
func TestForcedReleaseForNamesTheStaleCredentialsRelease(t *testing.T) {
|
||||
g, _ := newGate(t, nil)
|
||||
for _, tc := range []struct {
|
||||
missing []string
|
||||
want types.NamespacedName
|
||||
}{
|
||||
{[]string{"Secret/bucket-cozy-backups-system-credentials"}, g.CredentialsHelmRelease},
|
||||
{[]string{`Secret/bucket-cozy-backups-system-credentials (endpoint "s3.old", COSI Secret has "s3.new")`}, g.CredentialsHelmRelease},
|
||||
{[]string{"Secret/bucket-cozy-backups-system-credentials-other"}, g.HelmRelease},
|
||||
{[]string{`CNPG/cozy-default-cnpg (endpoint "https://s3.old", want "https://s3.new")`}, g.HelmRelease},
|
||||
} {
|
||||
if got := g.forcedReleaseFor(tc.missing); got != tc.want {
|
||||
t.Errorf("forcedReleaseFor(%v) = %v, want %v", tc.missing, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user