mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-05 14:42:05 +09:00
feat(credentials-migrate): hold releases until their deps roll out
Every application chart is copied out of the one cozystack-packages source, so all of them switch the moment the platform chart moves it, while cozystack-controller and the operators roll out on their own schedule. A Package dependsOn does not order that: tenant releases carry no dependsOn, and Flux only asks that a dependency be Ready, which it is on its old revision. On a live upgrade the old controller stripped the ClickHouse valuesFrom entries and the old redis-operator rolled the converted Redis pods its own way, locking clients out for minutes. --hold-until-rollout lets the hook record the images a Deployment runs and suspend every release of the kind; the finish Job resumes them, with their valuesFrom re-seeded, once each Deployment runs other images on all of its pods. Neither the old controller nor the old API touches spec.suspend. A hold that times out keeps the releases suspended and reports them left out, since running on the old chart is safer than a converted one the old components act on. Assisted-by: LLM Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
This commit is contained in:
4 files changed
+504
-4
No files matched your search
@@ -0,0 +1,225 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2"
|
||||
appsv1 "k8s.io/api/apps/v1"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
)
|
||||
|
||||
// HeldByAnnotation on a HelmRelease names the migration that suspended it
|
||||
// until the components the converted chart relies on have rolled out, so
|
||||
// only that suspension is lifted. It is not SuspendedByAnnotation: lifting a
|
||||
// hold must not pass for the forced upgrade a rotation still owes.
|
||||
const HeldByAnnotation = "credentials.cozystack.io/held-by-migration"
|
||||
|
||||
// Why the hold exists: every application chart is copied out of the one
|
||||
// cozystack-packages source, so all of them switch to the new version the
|
||||
// moment the platform chart moves that source, while the components they
|
||||
// depend on roll out on their own schedule. A Package dependsOn does not
|
||||
// order this: tenant releases carry no dependsOn, and Flux's dependsOn only
|
||||
// asks that the dependency be Ready, which a release still on its old
|
||||
// revision is. A converted chart that the old cozystack-controller or an old
|
||||
// operator acts on can lock clients out or roll the database the old way, so
|
||||
// the hook suspends the kind's releases and the finish Job resumes them once
|
||||
// those components run their new revision. Neither the old controller nor
|
||||
// the old cozystack-api touches spec.suspend.
|
||||
|
||||
// parseObjectKey reads a namespace/name pair.
|
||||
func parseObjectKey(s string) (types.NamespacedName, error) {
|
||||
ns, name, ok := strings.Cut(s, "/")
|
||||
if !ok || ns == "" || name == "" || strings.Contains(name, "/") {
|
||||
return types.NamespacedName{}, fmt.Errorf("%q is not namespace/name", s)
|
||||
}
|
||||
return types.NamespacedName{Namespace: ns, Name: name}, nil
|
||||
}
|
||||
|
||||
// templateImages is what a Deployment's pods run: the images of its pod
|
||||
// template, in order. An upgrade that crosses a conversion always changes the
|
||||
// image of a component the converted chart needs, so a change of this value
|
||||
// tells the new revision from the old one without knowing either tag.
|
||||
func templateImages(d *appsv1.Deployment) string {
|
||||
var imgs []string
|
||||
for _, c := range d.Spec.Template.Spec.InitContainers {
|
||||
imgs = append(imgs, c.Image)
|
||||
}
|
||||
for _, c := range d.Spec.Template.Spec.Containers {
|
||||
imgs = append(imgs, c.Image)
|
||||
}
|
||||
return strings.Join(imgs, ",")
|
||||
}
|
||||
|
||||
// rolledOut reports whether every pod of the Deployment runs its current
|
||||
// template and none of the previous one is left.
|
||||
func rolledOut(d *appsv1.Deployment) bool {
|
||||
want := int32(1)
|
||||
if d.Spec.Replicas != nil {
|
||||
want = *d.Spec.Replicas
|
||||
}
|
||||
s := d.Status
|
||||
return s.ObservedGeneration >= d.Generation &&
|
||||
s.UpdatedReplicas == want && s.Replicas == want && s.AvailableReplicas == want
|
||||
}
|
||||
|
||||
// recordRollouts keeps, for each Deployment the hold waits for, the images it
|
||||
// runs before the upgrade; an empty value stands for a Deployment that does
|
||||
// not exist yet. A rerun of the hook keeps the first record, which is the one
|
||||
// taken before anything switched.
|
||||
func (m *migrator) recordRollouts(ctx context.Context, st *state) error {
|
||||
for _, key := range m.o.holdRollouts {
|
||||
if _, ok := st.Rollouts[key]; ok {
|
||||
continue
|
||||
}
|
||||
nn, err := parseObjectKey(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := &appsv1.Deployment{}
|
||||
images := ""
|
||||
if err := m.c.Get(ctx, nn, d); err != nil {
|
||||
if !apierrors.IsNotFound(err) {
|
||||
return fmt.Errorf("read Deployment %s: %w", key, err)
|
||||
}
|
||||
} else {
|
||||
images = templateImages(d)
|
||||
}
|
||||
if st.Rollouts == nil {
|
||||
st.Rollouts = map[string]string{}
|
||||
}
|
||||
st.Rollouts[key] = images
|
||||
fmt.Printf("recorded Deployment %s on %q\n", key, images)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hold suspends a release until the recorded Deployments have rolled out. A
|
||||
// release already suspended is left as it is: either this hook held it on an
|
||||
// earlier run, or someone else suspended it, and that is not ours to lift.
|
||||
func (m *migrator) hold(ctx context.Context, hr *helmv2.HelmRelease) error {
|
||||
if len(m.o.holdRollouts) == 0 || hr.Spec.Suspend {
|
||||
return nil
|
||||
}
|
||||
patch := client.MergeFrom(hr.DeepCopy())
|
||||
hr.Spec.Suspend = true
|
||||
if hr.Annotations == nil {
|
||||
hr.Annotations = map[string]string{}
|
||||
}
|
||||
hr.Annotations[HeldByAnnotation] = strconv.Itoa(m.o.migration)
|
||||
if err := m.c.Patch(ctx, hr, patch); err != nil {
|
||||
return fmt.Errorf("hold until the new components run: %w", err)
|
||||
}
|
||||
fmt.Printf("%s/%s: suspended until %s roll out\n", hr.Namespace, hr.Name, strings.Join(m.o.holdRollouts, ", "))
|
||||
return nil
|
||||
}
|
||||
|
||||
// releaseHolds waits for every recorded Deployment to run a new revision,
|
||||
// then resumes the releases this migration held. Before resuming one it seeds
|
||||
// it again, which puts back the valuesFrom entries the old controller may
|
||||
// have stripped, so the first render of the converted chart carries them. If
|
||||
// a Deployment does not roll out in time the releases stay suspended and are
|
||||
// reported left out: their workloads keep running on the old chart, which is
|
||||
// safer than a converted chart the old components would act on.
|
||||
func (m *migrator) releaseHolds(ctx context.Context, st *state) error {
|
||||
if len(st.Rollouts) == 0 {
|
||||
return nil
|
||||
}
|
||||
mark := strconv.Itoa(m.o.migration)
|
||||
keys := make([]string, 0, len(st.Releases))
|
||||
for k, rec := range st.Releases {
|
||||
if !rec.Done {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var held []*helmv2.HelmRelease
|
||||
for _, key := range keys {
|
||||
ns, name, _ := strings.Cut(key, "/")
|
||||
hr := &helmv2.HelmRelease{}
|
||||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: ns, Name: name}, hr); err != nil {
|
||||
if apierrors.IsNotFound(err) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
if hr.Spec.Suspend && hr.Annotations[HeldByAnnotation] == mark {
|
||||
held = append(held, hr)
|
||||
}
|
||||
}
|
||||
if len(held) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := m.waitRollouts(ctx, st); err != nil {
|
||||
for _, hr := range held {
|
||||
m.skip(ctx, st, hr, fmt.Errorf("still suspended: %w; resume it by running this Job again once they have, or by removing %s and setting spec.suspend to false", err, HeldByAnnotation))
|
||||
}
|
||||
return errors.Join(err, m.saveState(ctx, st))
|
||||
}
|
||||
for _, hr := range held {
|
||||
key := hr.Namespace + "/" + hr.Name
|
||||
if err := m.seedRelease(ctx, hr); err != nil && !errors.Is(err, errUnresolvable) {
|
||||
return fmt.Errorf("%s: seed before resuming: %w", key, err)
|
||||
}
|
||||
patch := client.MergeFrom(hr.DeepCopy())
|
||||
hr.Spec.Suspend = false
|
||||
delete(hr.Annotations, HeldByAnnotation)
|
||||
if err := m.c.Patch(ctx, hr, patch); err != nil {
|
||||
return fmt.Errorf("%s: resume: %w", key, err)
|
||||
}
|
||||
delete(st.Skipped, key)
|
||||
fmt.Printf("%s: resumed\n", key)
|
||||
}
|
||||
return m.saveState(ctx, st)
|
||||
}
|
||||
|
||||
// waitRollouts waits until every recorded Deployment runs images other than
|
||||
// the recorded ones on all of its pods.
|
||||
func (m *migrator) waitRollouts(ctx context.Context, st *state) error {
|
||||
keys := make([]string, 0, len(st.Rollouts))
|
||||
for k := range st.Rollouts {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
deadline := m.now().Add(m.o.holdTimeout)
|
||||
for {
|
||||
var pending []string
|
||||
for _, key := range keys {
|
||||
nn, err := parseObjectKey(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := &appsv1.Deployment{}
|
||||
if err := m.c.Get(ctx, nn, d); err != nil {
|
||||
if !apierrors.IsNotFound(err) {
|
||||
return fmt.Errorf("read Deployment %s: %w", key, err)
|
||||
}
|
||||
pending = append(pending, key+" (absent)")
|
||||
continue
|
||||
}
|
||||
if templateImages(d) == st.Rollouts[key] {
|
||||
pending = append(pending, key+" (old revision)")
|
||||
continue
|
||||
}
|
||||
if !rolledOut(d) {
|
||||
pending = append(pending, key+" (rolling out)")
|
||||
}
|
||||
}
|
||||
if len(pending) == 0 {
|
||||
return nil
|
||||
}
|
||||
if m.now().After(deadline) {
|
||||
return fmt.Errorf("not rolled out to a new revision after %s: %s", m.o.holdTimeout, strings.Join(pending, ", "))
|
||||
}
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2"
|
||||
appsv1 "k8s.io/api/apps/v1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
|
||||
"github.com/cozystack/cozystack/pkg/credentials/account"
|
||||
)
|
||||
|
||||
const controllerKey = "cozy-system/cozystack-controller"
|
||||
|
||||
func controllerDeployment(image string, rolled bool) *appsv1.Deployment {
|
||||
one := int32(1)
|
||||
d := &appsv1.Deployment{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: "cozystack-controller", Namespace: "cozy-system", Generation: 2},
|
||||
Spec: appsv1.DeploymentSpec{
|
||||
Replicas: &one,
|
||||
Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "c", Image: image}}}},
|
||||
},
|
||||
Status: appsv1.DeploymentStatus{ObservedGeneration: 2, Replicas: 1, UpdatedReplicas: 1, AvailableReplicas: 1},
|
||||
}
|
||||
if !rolled {
|
||||
// The new ReplicaSet is up but the old pod is still there.
|
||||
d.Status.Replicas = 2
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// setDeployment replaces the controller Deployment, as its rollout would.
|
||||
func setDeployment(t *testing.T, m *migrator, image string, rolled bool) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
cur := &appsv1.Deployment{}
|
||||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "cozy-system", Name: "cozystack-controller"}, cur); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := controllerDeployment(image, rolled)
|
||||
cur.Spec = want.Spec
|
||||
if err := m.c.Update(ctx, cur); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur.Status = want.Status
|
||||
cur.Status.ObservedGeneration = cur.Generation
|
||||
if err := m.c.Status().Update(ctx, cur); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func getRelease(t *testing.T, m *migrator, name string) *helmv2.HelmRelease {
|
||||
t.Helper()
|
||||
hr := &helmv2.HelmRelease{}
|
||||
if err := m.c.Get(context.Background(), types.NamespacedName{Namespace: "tenant-foo", Name: name}, hr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return hr
|
||||
}
|
||||
|
||||
func TestSeedHoldsTheKindsReleasesAndRecordsTheRollout(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
hr := release(`{"users":{"web":{}}}`, "0.1.0", true)
|
||||
foreign := release(`{"users":{"web":{}}}`, "0.1.0", true)
|
||||
foreign.Name = "postgres-paused"
|
||||
foreign.Spec.Suspend = true
|
||||
m := newMigrator(t, hr, foreign, sourceSecret(map[string]string{"web": "hunter2"}), controllerDeployment("controller:v1.7.1", true))
|
||||
m.o.holdRollouts = stringFlags{controllerKey}
|
||||
if err := m.seed(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cur := getRelease(t, m, "postgres-orders")
|
||||
if !cur.Spec.Suspend || cur.Annotations[HeldByAnnotation] != "64" {
|
||||
t.Fatalf("release not held: suspend=%v annotations=%v", cur.Spec.Suspend, cur.Annotations)
|
||||
}
|
||||
if cur.Annotations[SuspendedByAnnotation] != "" {
|
||||
t.Fatal("a hold must not pass for a rotation's suspension")
|
||||
}
|
||||
// Someone else's suspension is neither claimed nor lifted later.
|
||||
if f := getRelease(t, m, "postgres-paused"); !f.Spec.Suspend || f.Annotations[HeldByAnnotation] != "" {
|
||||
t.Fatalf("foreign suspension changed: %+v", f.ObjectMeta.Annotations)
|
||||
}
|
||||
st, err := m.loadState(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Rollouts[controllerKey] != "controller:v1.7.1" {
|
||||
t.Fatalf("rollouts = %v", st.Rollouts)
|
||||
}
|
||||
|
||||
// A rerun of the hook keeps the record taken before anything switched.
|
||||
setDeployment(t, m, "controller:v1.8.0", false)
|
||||
if err := m.seed(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, _ = m.loadState(ctx); st.Rollouts[controllerKey] != "controller:v1.7.1" {
|
||||
t.Fatalf("rollouts after rerun = %v", st.Rollouts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedWithoutAHoldLeavesReleasesRunning(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
hr := release(`{"users":{"web":{}}}`, "0.1.0", true)
|
||||
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}))
|
||||
if err := m.seed(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cur := getRelease(t, m, "postgres-orders"); cur.Spec.Suspend {
|
||||
t.Fatal("a kind without --hold-until-rollout must not be suspended")
|
||||
}
|
||||
if st, _ := m.loadState(ctx); len(st.Rollouts) != 0 {
|
||||
t.Fatalf("rollouts = %v", st.Rollouts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishKeepsReleasesHeldUntilTheNewRevisionRollsOut(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
hr := release(`{"users":{"web":{}}}`, "0.1.0", true)
|
||||
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}), controllerDeployment("controller:v1.7.1", true))
|
||||
m.o.holdRollouts = stringFlags{controllerKey}
|
||||
if err := m.seed(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
image string
|
||||
rolled bool
|
||||
want string
|
||||
}{
|
||||
{"still the old revision", "controller:v1.7.1", true, "old revision"},
|
||||
{"the old pod is still running", "controller:v1.8.0", false, "rolling out"},
|
||||
} {
|
||||
setDeployment(t, m, c.image, c.rolled)
|
||||
err := m.finish(ctx)
|
||||
if err == nil || !strings.Contains(err.Error(), c.want) {
|
||||
t.Fatalf("%s: finish = %v, want an error naming %q", c.name, err, c.want)
|
||||
}
|
||||
if cur := getRelease(t, m, "postgres-orders"); !cur.Spec.Suspend || cur.Annotations[HeldByAnnotation] != "64" {
|
||||
t.Fatalf("%s: the release must stay held", c.name)
|
||||
}
|
||||
st, _ := m.loadState(ctx)
|
||||
if why := st.Skipped["tenant-foo/postgres-orders"]; !strings.Contains(why, "still suspended") {
|
||||
t.Fatalf("%s: skipped = %v", c.name, st.Skipped)
|
||||
}
|
||||
cm := &corev1.ConfigMap{}
|
||||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "cozy-system", Name: "credentials-migration-64"}, cm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cm.Labels[incompleteLabel] != "true" {
|
||||
t.Fatalf("%s: a held release must fire the incomplete alert", c.name)
|
||||
}
|
||||
if _, ok := m.secret(t, "postgres-orders-credentials"); !ok {
|
||||
t.Fatalf("%s: nothing may be retired while the release is held", c.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishResumesHeldReleasesWithTheirValuesFromOnceRolledOut(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
hr := release(`{"users":{"web":{}}}`, "0.1.0", true)
|
||||
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}), controllerDeployment("controller:v1.7.1", true))
|
||||
m.o.valuesPath = "_accounts"
|
||||
m.o.holdRollouts = stringFlags{controllerKey}
|
||||
if err := m.seed(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The old controller rebuilds valuesFrom and drops the account entries.
|
||||
cur := getRelease(t, m, "postgres-orders")
|
||||
patch := client.MergeFrom(cur.DeepCopy())
|
||||
cur.Spec.ValuesFrom = []helmv2.ValuesReference{{Kind: "Secret", Name: "cozystack-values"}}
|
||||
if err := m.c.Patch(ctx, cur, patch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
setDeployment(t, m, "controller:v1.8.0", true)
|
||||
// Resumed, but the chart has not switched yet: the release itself is
|
||||
// left out by the existing wait, not by the hold.
|
||||
err := m.finish(ctx)
|
||||
if err == nil || strings.Contains(err.Error(), "still suspended") {
|
||||
t.Fatalf("finish = %v", err)
|
||||
}
|
||||
cur = getRelease(t, m, "postgres-orders")
|
||||
if cur.Spec.Suspend || cur.Annotations[HeldByAnnotation] != "" {
|
||||
t.Fatalf("not resumed: suspend=%v annotations=%v", cur.Spec.Suspend, cur.Annotations)
|
||||
}
|
||||
want := account.ValuesFrom("postgres-orders.web.account", "_accounts", "web")
|
||||
if len(cur.Spec.ValuesFrom) != 2 || cur.Spec.ValuesFrom[1] != want {
|
||||
t.Fatalf("valuesFrom = %+v: the entries must be back before the first render", cur.Spec.ValuesFrom)
|
||||
}
|
||||
|
||||
// The chart switches; the conversion completes as before.
|
||||
cur.Status.History = helmv2.Snapshots{{Version: 2, ChartVersion: "0.2.0", Status: "deployed"}}
|
||||
if err := m.c.Status().Update(ctx, cur); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.finish(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, _ := m.loadState(ctx); !st.Releases["tenant-foo/postgres-orders"].Done || len(st.Skipped) != 0 {
|
||||
t.Fatalf("state = %+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishWaitsForADeploymentAbsentAtTheHook(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
hr := release(`{"users":{"web":{}}}`, "0.1.0", true)
|
||||
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}))
|
||||
m.o.holdRollouts = stringFlags{controllerKey}
|
||||
if err := m.seed(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, _ := m.loadState(ctx); st.Rollouts[controllerKey] != "" {
|
||||
t.Fatalf("rollouts = %v", st.Rollouts)
|
||||
}
|
||||
if err := m.finish(ctx); err == nil || !strings.Contains(err.Error(), "absent") {
|
||||
t.Fatalf("finish = %v", err)
|
||||
}
|
||||
if err := m.c.Create(ctx, controllerDeployment("controller:v1.8.0", true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = m.finish(ctx)
|
||||
if cur := getRelease(t, m, "postgres-orders"); cur.Spec.Suspend {
|
||||
t.Fatal("the release must be resumed once the Deployment exists and rolled out")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRefusesAMalformedHoldRollout(t *testing.T) {
|
||||
err := run([]string{"seed", "--migration=65", "--kind=ClickHouse", "--format=sha256", "--hold-until-rollout=cozystack-controller"})
|
||||
if err == nil || !strings.Contains(err.Error(), "--hold-until-rollout") {
|
||||
t.Fatalf("run = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2"
|
||||
fluxmeta "github.com/fluxcd/pkg/apis/meta"
|
||||
appsv1 "k8s.io/api/apps/v1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/equality"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
@@ -85,6 +86,8 @@ type options struct {
|
||||
stateNamespace string
|
||||
actor string
|
||||
timeout time.Duration
|
||||
holdRollouts stringFlags
|
||||
holdTimeout time.Duration
|
||||
}
|
||||
|
||||
type labelFlags map[string]string
|
||||
@@ -116,6 +119,9 @@ type state struct {
|
||||
// Skipped maps namespace/name to the reason and time it was left out on
|
||||
// the last run. A release leaves the map once a later run finishes it.
|
||||
Skipped map[string]string `json:"skipped,omitempty"`
|
||||
// Rollouts maps namespace/name of each Deployment the held releases wait
|
||||
// for to the images it ran when the hook recorded it.
|
||||
Rollouts map[string]string `json:"rollouts,omitempty"`
|
||||
}
|
||||
|
||||
type releaseState struct {
|
||||
@@ -153,6 +159,8 @@ func run(args []string) error {
|
||||
fs.StringVar(&o.stateNamespace, "state-namespace", "cozy-system", "namespace of the state ConfigMap")
|
||||
fs.StringVar(&o.actor, "actor", envOr("CREDENTIALS_MIGRATE_ACTOR", defaultActor), "who the record names for the migrated password")
|
||||
fs.DurationVar(&o.timeout, "timeout", 10*time.Minute, "finish: how long to wait per release for the switched chart to be Ready")
|
||||
fs.Var(&o.holdRollouts, "hold-until-rollout", "seed: Deployment, namespace/name, whose new revision the converted chart needs; the hook suspends every release of the kind and the finish Job resumes them once each such Deployment runs images other than the ones recorded now; repeatable")
|
||||
fs.DurationVar(&o.holdTimeout, "hold-timeout", time.Hour, "finish: how long to wait for the --hold-until-rollout Deployments before reporting the held releases left out")
|
||||
if err := fs.Parse(args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -164,6 +172,11 @@ func run(args []string) error {
|
||||
return fmt.Errorf("--rotate-key %q is not a --platform-key, and finish would delete it from the source Secret", k)
|
||||
}
|
||||
}
|
||||
for _, d := range o.holdRollouts {
|
||||
if _, err := parseObjectKey(d); err != nil {
|
||||
return fmt.Errorf("--hold-until-rollout: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
scheme := runtime.NewScheme()
|
||||
if err := corev1.AddToScheme(scheme); err != nil {
|
||||
@@ -172,6 +185,9 @@ func run(args []string) error {
|
||||
if err := helmv2.AddToScheme(scheme); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := appsv1.AddToScheme(scheme); err != nil {
|
||||
return err
|
||||
}
|
||||
c, err := client.New(ctrl.GetConfigOrDie(), client.Options{Scheme: scheme})
|
||||
if err != nil {
|
||||
return fmt.Errorf("build client: %w", err)
|
||||
@@ -214,6 +230,16 @@ func (m *migrator) seed(ctx context.Context) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(releases) > 0 {
|
||||
// Saved before any release is held, so the finish Job always knows
|
||||
// what it waits for before it resumes them.
|
||||
if err := m.recordRollouts(ctx, st); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.saveState(ctx, st); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i := range releases {
|
||||
hr := &releases[i]
|
||||
key := hr.Namespace + "/" + hr.Name
|
||||
@@ -230,10 +256,13 @@ func (m *migrator) seed(ctx context.Context) error {
|
||||
return fmt.Errorf("%s: %w", key, err)
|
||||
}
|
||||
m.skip(ctx, st, hr, err)
|
||||
continue
|
||||
} else {
|
||||
delete(st.Skipped, key)
|
||||
fmt.Printf("%s: recorded chart version %q\n", key, rec.ChartVersion)
|
||||
}
|
||||
if err := m.hold(ctx, hr); err != nil {
|
||||
return errors.Join(fmt.Errorf("%s: %w", key, err), m.saveState(ctx, st))
|
||||
}
|
||||
delete(st.Skipped, key)
|
||||
fmt.Printf("%s: recorded chart version %q\n", key, rec.ChartVersion)
|
||||
}
|
||||
return m.saveState(ctx, st)
|
||||
}
|
||||
@@ -245,6 +274,9 @@ func (m *migrator) finish(ctx context.Context) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.releaseHolds(ctx, st); err != nil {
|
||||
return err
|
||||
}
|
||||
keys := make([]string, 0, len(st.Releases))
|
||||
for k := range st.Releases {
|
||||
keys = append(keys, k)
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
helmv2 "github.com/fluxcd/helm-controller/api/v2"
|
||||
appsv1 "k8s.io/api/apps/v1"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
@@ -41,6 +42,9 @@ func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Obje
|
||||
if err := helmv2.AddToScheme(scheme); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := appsv1.AddToScheme(scheme); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).WithStatusSubresource(&helmv2.HelmRelease{})
|
||||
if funcs != nil {
|
||||
b = b.WithInterceptorFuncs(*funcs)
|
||||
@@ -49,7 +53,7 @@ func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Obje
|
||||
o := &options{
|
||||
migration: 64, kind: "Postgres", formatName: format.ScramSHA256, accountsPath: "users",
|
||||
labels: labelFlags{"cnpg.io/reload": "true"}, sourceSuffix: "-credentials",
|
||||
stateNamespace: "cozy-system", actor: "migration", timeout: -time.Second,
|
||||
stateNamespace: "cozy-system", actor: "migration", timeout: -time.Second, holdTimeout: -time.Second,
|
||||
}
|
||||
return &migrator{c: c, o: o, now: func() time.Time { return time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) }}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user