8000 fix(chi): defer force restart while ClickHouse is starting by alex-zaitsev · Pull Request #2186 · Altinity/clickhouse-operator · GitHub
[go: up one dir, main page]

Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion pkg/controller/chi/worker-pod-retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package chi
import (
"context"
"strings"
"sync"
"time"

core "k8s.io/api/core/v1"
Expand All @@ -33,6 +34,38 @@ import (
// can't produce an immediate reconcile.
const stuckHostMinDelay = 5 * time.Second

// Retry a deferred startup even when onPodReady recovery is disabled or the
// readiness transition was missed. Coalesce retries per CHI generation.
const startupRestartRetryDelay = time.Minute

type startupRestartRetryKey struct {
uid string
generation int64
}

var startupRestartRetries sync.Map

func (w *worker) scheduleStartupRestartRetry(cr *api.ClickHouseInstallation) {
key := startupRestartRetryKey{uid: string(cr.UID), generation: cr.Generation}
if _, pending := startupRestartRetries.LoadOrStore(key, struct{}{}); pending {
return
}
c := w.c
// Capture only identity; a queued retry must not replay a stale spec or status.
identity := &api.ClickHouseInstallation{}
identity.Namespace, identity.Name = cr.Namespace, cr.Name
time.AfterFunc(startupRestartRetryDelay, func() {
startupRestartRetries.Delete(key)
current, err := c.GetCR(identity)
if err != nil || current == nil || string(current.UID) != key.uid ||
current.Generation != key.generation || current.Spec.Suspend.Value() ||
!shouldTriggerAutoRecovery(current) {
return
}
c.enqueueObject(cmd_queue.NewReconcileCHI(cmd_queue.ReconcileAdd, nil, current))
})
}

// stuckHostExtraDelay buffers threshold against apiserver/informer latency
// so the eventual reconcile observes an up-to-date LastTransitionTime.
const stuckHostExtraDelay = 2 * time.Second
Expand Down Expand Up @@ -155,7 +188,7 @@ func (w *worker) recoverCompletedReconcileOnPodNotReady(ctx context.Context, old
return
}

if !isPodReadyToNotReadyTransition(oldPod, newPod) {
if !isPodReadyToNotReadyTransition(oldPod, newPod) && !isPodStartupFinishedNotReady(oldPod, newPod) {
return
}

Expand Down Expand Up @@ -198,6 +231,13 @@ func (w *worker) recoverCompletedReconcileOnPodNotReady(ctx context.Context, old
})
}

// A pod can finish startup without becoming Ready; the earlier NotReady event
// may have been evaluated while startup was still protected.
func isPodStartupFinishedNotReady(oldPod, newPod *core.Pod) bool {
return podIsStarting(oldPod) && newPod != nil && !podIsStarting(newPod) &&
k8s.PodHasNotReadyContainers(newPod)
}

// shouldTriggerStuckHostRecovery reports whether the given CHI is a valid stuck-host
// recovery target: status is Completed and the CHI is not being deleted.
func shouldTriggerStuckHostRecovery(cr *api.ClickHouseInstallation) bool {
Expand Down
29 changes: 28 additions & 1 deletion pkg/controller/chi/worker-reconciler-chi.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ func (w *worker) reconcileCR(ctx context.Context, old, new *api.ClickHouseInstal
w.prepareMonitoring(new)
w.setHostStatusesPreliminary(ctx, new)

w.startupRestartDeferred.Store(false)
if err := w.reconcile(ctx, new); err != nil {
if errors.Is(err, common.ErrCRUDDeferred) {
// A deferral is a postponement, not a failure. The host-level branch already recorded
Expand All @@ -202,6 +203,9 @@ func (w *worker) reconcileCR(ctx context.Context, old, new *api.ClickHouseInstal
}
err = common.ErrCRUDAbort
w.markReconcileCompletedUnsuccessfully(ctx, new, err)
if w.startupRestartDeferred.Load() && !util.IsContextDone(ctx) {
w.scheduleStartupRestartRetry(raw)
}
if errors.Is(err, common.ErrCRUDAbort) {
metrics.CRReconcilesAborted(ctx, new)
}
Expand Down Expand Up @@ -722,7 +726,9 @@ func (w *worker) reconcileHostStatefulSet(ctx context.Context, host *api.Host, o
w.a.V(1).M(host).F().Info("Pod template changed - skipping software restart; StatefulSet rollout will restart the pod. Host: %s", host.GetName())
} else {
w.a.V(1).M(host).F().Info("Reconcile host STS force restart: %s", host.GetName())
_ = w.hostForceRestart(ctx, host, opts)
if err := w.hostForceRestart(ctx, host, opts); err != nil {
return err
}
// hostForceRestart's fallback path (hostScaleDown) overwrites DesiredStatefulSet
// with a shutdown spec via PrepareHostStatefulSetWithStatus(host, true). If we
// don't reset it back to the normal desired spec, the main ReconcileStatefulSet
Expand Down Expand Up @@ -842,7 +848,25 @@ func sameVolumeMounts(cur, desired []core.VolumeMount) bool {
return true
}

// deferForceRestartWhileStarting is checked before shutdown and again before
// scale-down, since a new container may have started in the meantime.
func (w *worker) deferForceRestartWhileStarting(ctx context.Context, host *api.Host) error {
if host.IsStopped() {
return nil
}
pod, err := w.c.kube.Pod().Get(ctx, host)
if !shouldDeferForceRestart(pod, err) {
return nil
}
w.startupRestartDeferred.Store(true)
w.a.V(1).M(host).F().Warning("Deferring force restart: ClickHouse is starting or pod startup state is unknown. Host: %s", host.GetName())
return common.ErrCRUDDeferred
}

func (w *worker) hostForceRestart(ctx context.Context, host *api.Host, opts *statefulset.ReconcileOptions) error {
if err := w.deferForceRestartWhileStarting(ctx, host); err != nil {
return err
}
w.a.V(1).M(host).F().Info("Reconcile host. Force restart: %s", host.GetName())

// A sustained-NotReady pod won't be healed by an in-place software restart: the
Expand All @@ -853,6 +877,9 @@ func (w *worker) hostForceRestart(ctx context.Context, host *api.Host, opts *sta
w.isPodSustainedNotReady(ctx, host, chop.Config().CompletedOnPodNotReadyThreshold())

if host.IsStopped() || stuckNotReady || (w.hostSoftwareRestart(ctx, host) != nil) {
if err := w.deferForceRestartWhileStarting(ctx, host); err != nil {
return err
}
_ = w.hostScaleDown(ctx, host, opts)
}

Expand Down
45 changes: 44 additions & 1 deletion pkg/controller/chi/worker-status-helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"time"

core "k8s.io/api/core/v1"
apiErrors "k8s.io/apimachinery/pkg/api/errors"

log "github.com/altinity/clickhouse-operator/pkg/announcer"
api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1"
Expand All @@ -27,6 +28,7 @@ import (
"github.com/altinity/clickhouse-operator/pkg/chop"
"github.com/altinity/clickhouse-operator/pkg/interfaces"
"github.com/altinity/clickhouse-operator/pkg/model/chi/config"
chiCreator "github.com/altinity/clickhouse-operator/pkg/model/chi/creator"
commonConfig "github.com/altinity/clickhouse-operator/pkg/model/common/config"
"github.com/altinity/clickhouse-operator/pkg/model/k8s"
"github.com/altinity/clickhouse-operator/pkg/util"
Expand Down Expand Up @@ -78,7 +80,7 @@ func (w *worker) isPodSustainedNotReady(ctx context.Context, host *api.Host, thr
// has a PodReady condition that is currently not True and whose LastTransitionTime
// is at least `threshold` in the past relative to `now`.
func podIsSustainedNotReady(pod *core.Pod, threshold time.Duration, now time.Time) bool {
if pod == nil || threshold <= 0 {
if pod == nil || threshold <= 0 || podIsStarting(pod) {
return false
}
for _, cond := range pod.Status.Conditions {
Expand Down Expand Up @@ -142,6 +144,47 @@ func podIsInKubeletFailureMode(pod *core.Pod) bool {
return false
}

// podIsStarting reports whether ClickHouse is still protected by its startup probe.
// A missing status is not evidence of a completed startup. Use the actual Pod spec
// (including custom ClickHouse container names), not the desired StatefulSet.
// Preserve recovery for known kubelet failure states and terminating/terminal pods.
func podIsStarting(pod *core.Pod) bool {
if pod == nil || podIsTerminating(pod) {
return false
}
if pod.Status.Phase == core.PodFailed || pod.Status.Phase == core.PodSucceeded {
return false
}
container, ok := chiCreator.PodSpecContainerGetClickHouse(&pod.Spec)
if !ok || container == nil || container.StartupProbe == nil {
return false
}
for _, status := range pod.Status.ContainerStatuses {
if status.Name != container.Name {
continue
}
if status.State.Terminated != nil {
return false
}
if status.State.Waiting != nil {
if _, failed := kubeletDrivenWaitingReasons[status.State.Waiting.Reason]; failed {
return false
}
}
return status.Started == nil || !*status.Started
}
return true
}

// shouldDeferForceRestart also protects the pod when its current state cannot
// be determined. A confirmed missing pod is safe to recover through the STS.
func shouldDeferForceRestart(pod *core.Pod, err error) bool {
if err != nil {
10000 return !apiErrors.IsNotFound(err)
}
return pod == nil || podIsStarting(pod)
}

func (w *worker) isPodStarted(ctx context.Context, host *api.Host) bool {
if pod, err := w.c.kube.Pod().Get(ctx, host); err == nil {
return k8s.PodHasAllContainersStarted(pod)
Expand Down
83 changes: 83 additions & 0 deletions pkg/controller/chi/worker-status-helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,14 @@ import (
"time"

"github.com/stretchr/testify/require"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
core "k8s.io/api/core/v1"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"

api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1"
"github.com/altinity/clickhouse-operator/pkg/controller/common"
a "github.com/altinity/clickhouse-operator/pkg/controller/common/announcer"
"github.com/altinity/clickhouse-operator/pkg/interfaces"
)

Expand Down Expand Up @@ -311,3 +315,82 @@ func TestIsHostHealthyForReconcileTreatsTerminatingPodAsUnhealthy(t *testing.T)
"a pod with deletionTimestamp must never count as a shard's healthy peer")
})
}

// A ClickHouse container with a startup probe is not safe to restart before it
// has passed the probe, even if the Pod is Running.
func startupProtectedPod() *core.Pod {
started := false
return &core.Pod{
Spec: core.PodSpec{Containers: []core.Container{
{Name: "clickhouse", StartupProbe: &core.Probe{}},
}},
Status: core.PodStatus{
Phase: core.PodRunning,
ContainerStatuses: []core.ContainerStatus{
{Name: "clickhouse", Started: &started, State: core.ContainerState{Running: &core.ContainerStateRunning{}}},
},
},
}
}

func TestPodIsStarting(t *testing.T) {
tests := []struct {
name string
change func(*core.Pod)
want bool
}{
{"running, startup pending", func(p *core.Pod) {}, true},
{"missing Started", func(p *core.Pod) { p.Status.ContainerStatuses[0].Started = nil }, true},
{"pending, no statuses", func(p *core.Pod) { p.Status.Phase = core.PodPending; p.Status.ContainerStatuses = nil }, true},
{"missing ClickHouse status", func(p *core.Pod) { p.Status.ContainerStatuses[0].Name = "sidecar" }, true},
{"custom container name", func(p *core.Pod) { p.Spec.Containers[0].Name = "server"; p.Status.ContainerStatuses[0].Name = "server" }, true},
{"started", func(p *core.Pod) { *p.Status.ContainerStatuses[0].Started = true }, false},
{"no startup probe", func(p *core.Pod) { p.Spec.Containers[0].StartupProbe = nil }, false},
{"sidecar starting", func(p *core.Pod) {
*p.Status.ContainerStatuses[0].Started = true
p.Spec.Containers = append(p.Spec.Containers, core.Container{Name: "sidecar", StartupProbe: &core.Probe{}})
}, false},
{"crash loop", func(p *core.Pod) {
p.Status.ContainerStatuses[0].State = core.ContainerState{Waiting: &core.ContainerStateWaiting{Reason: "CrashLoopBackOff"}}
}, false},
{"terminated container", func(p *core.Pod) {
p.Status.ContainerStatuses[0].State = core.ContainerState{Terminated: &core.ContainerStateTerminated{}}
}, false},
{"terminating pod", func(p *core.Pod) { now := meta.Now(); p.DeletionTimestamp = &now }, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pod := startupProtectedPod()
tt.change(pod)
require.Equal(t, tt.want, podIsStarting(pod))
})
}
}

func TestForceRestartDefersForStartup(t *testing.T) {
w, host := newHealthyPodWorker(startupProtectedPod())
w.a = a.NewAnnouncer(nil, nil)
// The fake only supports Pod.Get: reaching SQL shutdown or scale-down would
// panic. Verify the real force-restart entry point returns the deferral.
require.ErrorIs(t, w.hostForceRestart(context.Background(), host, nil), common.ErrCRUDDeferred)
require.True(t, w.startupRestartDeferred.Load())
}

func TestShouldDeferForceRestartUnknownPod(t *testing.T) {
require.True(t, shouldDeferForceRestart(nil, nil))
require.True(t, shouldDeferForceRestart(nil, apiErrors.NewServiceUnavailable("API unavailable")))
require.False(t, shouldDeferForceRestart(nil, apiErrors.NewNotFound(schema.GroupResource{Resource: "pods"}, "pod")))
}

func TestSustainedNotReadyRespectsStartupProbe(t *testing.T) {
now := time.Now()
pod := startupProtectedPod()
pod.Status.Conditions = []core.PodCondition{
{Type: core.PodReady, Status: core.ConditionFalse, LastTransitionTime: meta.NewTime(now.Add(-30 * time.Minute))},
}
require.False(t, podIsSustainedNotReady(pod, 5*time.Minute, now))
started := pod.DeepCopy()
*started.Status.ContainerStatuses[0].Started = true
require.True(t, podIsSustainedNotReady(started, 5*time.Minute, now))
require.True(t, isPodStartupFinishedNotReady(pod, started))
}
4 changes: 4 additions & 0 deletions pkg/controller/chi/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"context"
"errors"
"sync"
"sync/atomic"
"time"

core "k8s.io/api/core/v1"
Expand Down Expand Up @@ -68,6 +69,9 @@ type worker struct {
// without a restart. A reconcile replaces it. The restart policy is not cached.
reloadability *reconcileReloadability

// Set by host goroutines when a required restart is deferred for startup.
startupRestartDeferred atomic.Bool

start time.Time
}

Expand Down
0