Skip to content
Open
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
14 changes: 12 additions & 2 deletions pkg/k8s/deployer.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ type Deployer struct {

exposer deployer.Exposer

autoscaledReplicas bool
autoscaledReplicas bool
requireReadyReplica bool
}

func NewDeployer(opts ...DeployerOpt) *Deployer {
Expand Down Expand Up @@ -141,6 +142,15 @@ func WithAutoscaledReplicas(autoscaledReplicas bool) DeployerOpt {
}
}

// WithRequireReadyReplica refuses a settled zero-replica Deployment during the
// readiness wait so callers holding a replica prove a pod of the new revision
// became ready before allowing scale-to-zero (#4118).
func WithRequireReadyReplica(require bool) DeployerOpt {
return func(d *Deployer) {
d.requireReadyReplica = require
}
}

func WithDeployerDecorator(decorator deployer.DeployDecorator) DeployerOpt {
return func(d *Deployer) {
d.decorator = decorator
Expand Down Expand Up @@ -332,7 +342,7 @@ func (d *Deployer) Deploy(ctx context.Context, f fn.Function) (fn.DeploymentResu
}
}

if err := WaitForDeploymentAvailable(ctx, clientset, namespace, f.Name, DefaultWaitingTimeout); err != nil {
if err := waitForDeploymentAvailable(ctx, clientset, namespace, f.Name, DefaultWaitingTimeout, !d.requireReadyReplica); err != nil {
return fn.DeploymentResult{}, fmt.Errorf("deployment did not become ready: %w", err)
}

Expand Down
26 changes: 23 additions & 3 deletions pkg/k8s/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@ import (
// controller has observed the current generation and reports all-zero
// counts: no pods are wanted, so none are required to be ready.
func WaitForDeploymentAvailable(ctx context.Context, clientset *kubernetes.Clientset, namespace, deploymentName string, timeout time.Duration) error {
return waitForDeploymentAvailable(ctx, clientset, namespace, deploymentName, timeout, true)
}

func waitForDeploymentAvailable(ctx context.Context, clientset *kubernetes.Clientset, namespace, deploymentName string, timeout time.Duration, allowZero bool) error {
return wait.PollUntilContextTimeout(ctx, 1*time.Second, timeout, true, func(ctx context.Context) (bool, error) {
deployment, err := clientset.AppsV1().Deployments(namespace).Get(ctx, deploymentName, metav1.GetOptions{})
if err != nil {
return false, err
}

return checkIfDeploymentIsAvailable(ctx, clientset, deployment)
return checkIfDeploymentAvailable(ctx, clientset, deployment, allowZero)
})
}

Expand Down Expand Up @@ -65,18 +69,34 @@ func WaitForServiceRemoved(ctx context.Context, clientset *kubernetes.Clientset,
}

func checkIfDeploymentIsAvailable(ctx context.Context, clientset *kubernetes.Clientset, deployment *appsv1.Deployment) (bool, error) {
return checkIfDeploymentAvailable(ctx, clientset, deployment, true)
}

func checkIfDeploymentAvailable(ctx context.Context, clientset *kubernetes.Clientset, deployment *appsv1.Deployment, allowZero bool) (bool, error) {
// Check if the deployment has the desired number of replicas
if deployment.Spec.Replicas == nil {
return false, fmt.Errorf("deployment %s has nil replicas", deployment.Name)
}

// Wait until the controller has observed the current spec generation so
// stale status (including ready pods from the previous revision after an
// image update) cannot satisfy the readiness check (#4118).
if deployment.Status.ObservedGeneration < deployment.Generation {
return false, nil
}

desiredReplicas := *deployment.Spec.Replicas

// Scalers can request zero replicas while readiness is being polled.
// Require reconciled status, including replicas from older ReplicaSets.
// Callers that hold a replica to verify the new revision ran set
// allowZero=false so a stale scale-to-zero keeps polling until the
// scaler brings a pod back (#4118).
if desiredReplicas == 0 {
return deployment.Status.ObservedGeneration >= deployment.Generation &&
deployment.Status.Replicas == 0 &&
if !allowZero {
return false, nil
}
return deployment.Status.Replicas == 0 &&
deployment.Status.UpdatedReplicas == 0 &&
deployment.Status.ReadyReplicas == 0 &&
deployment.Status.AvailableReplicas == 0 &&
Expand Down
33 changes: 33 additions & 0 deletions pkg/k8s/wait_poll_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,39 @@ func TestWaitForDeploymentAvailable_NonzeroReady(t *testing.T) {
}
}

func TestWaitForDeploymentAvailable_StaleNonzeroGeneration(t *testing.T) {
stale := waitDeployment(1)
stale.Generation = 8
stale.Status.ObservedGeneration = 7
reconciled := waitDeployment(1)
reconciled.Generation = 8
reconciled.Status.ObservedGeneration = 8

t.Run("waits until observedGeneration catches up", func(t *testing.T) {
api := &waitAPI{deployments: []*appsv1.Deployment{stale, reconciled}, activeAfter: 1}
if err := k8s.WaitForDeploymentAvailable(t.Context(), api.client(t), "ns", "fn", 5*time.Second); err != nil {
t.Fatal(err)
}
if got := api.deploymentReads.Load(); got != 2 {
t.Fatalf("deployment reads = %d, want 2", got)
}
if got := api.podReads.Load(); got != 1 {
t.Fatalf("pod reads = %d, want 1 (should skip stale generation)", got)
}
})

t.Run("times out when observedGeneration stays behind", func(t *testing.T) {
api := &waitAPI{deployments: []*appsv1.Deployment{stale}, activeAfter: 1}
err := k8s.WaitForDeploymentAvailable(t.Context(), api.client(t), "ns", "fn", 100*time.Millisecond)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("error = %v, want deadline exceeded", err)
}
if api.podReads.Load() != 0 {
t.Fatal("stale generation should not query pods")
}
})
}

func waitDeployment(replicas int32) *appsv1.Deployment {
return &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: "fn", Namespace: "ns", Generation: 7},
Expand Down
10 changes: 10 additions & 0 deletions pkg/k8s/wait_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,14 @@ func TestCheckIfDeploymentIsAvailable_ZeroReplicas(t *testing.T) {
t.Error("expected ready=false with an unavailable replica")
}
})

t.Run("reconciled zero is not ready when allowZero is false", func(t *testing.T) {
ready, err := checkIfDeploymentAvailable(ctx, nil, zeroDeployment(nil), false)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if ready {
t.Error("expected ready=false when allowZero=false")
}
})
}
88 changes: 67 additions & 21 deletions pkg/keda/deployer.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ import (

const (
KedaDeployerName = deployers.Keda

scalerHoldTimeout = 30 * time.Second
scalerRestoreTimeout = 30 * time.Second
)

type DeployerOpt func(*Deployer)
Expand All @@ -42,6 +45,7 @@ func NewDeployer(opts ...DeployerOpt) *Deployer {
// init with the kedaDeployerDecorator to have the correct deployer labels&annotations
k8s.WithDeployerDecorator(&kedaDeployerDecorator{}),
k8s.WithAutoscaledReplicas(true),
k8s.WithRequireReadyReplica(true),
),
}

Expand Down Expand Up @@ -102,7 +106,7 @@ func (k *kedaDeployerDecorator) UpdateLabels(function fn.Function, labels map[st
return labels
}

func (d *Deployer) Deploy(ctx context.Context, f fn.Function) (fn.DeploymentResult, error) {
func (d *Deployer) Deploy(ctx context.Context, f fn.Function) (_ fn.DeploymentResult, err error) {
triggers := triggers(f)
if len(triggers) == 0 {
// triggers(f) only returns empty when scale.keda is present with an
Expand Down Expand Up @@ -290,6 +294,35 @@ func (d *Deployer) Deploy(ctx context.Context, f fn.Function) (fn.DeploymentResu
}
}

// A scaler at min 0 can scale the Deployment away before the readiness
// wait sees the new revision. Hold min 1 until the ensure* calls below
// set the configured minimum again (#4118).
held, err := setScalerMin(ctx, httpScaledObjectClientset, dynClient, scalerNamespace, f.Name, wantKafka, 0, 1)
if err != nil {
return fn.DeploymentResult{}, fmt.Errorf("failed to hold a replica for function %q: %w", f.Name, err)
}
restoreHold := held
if held {
defer func() {
if err == nil || !restoreHold {
return
}
// Bounded, so an unresponsive API server cannot hang a failed deploy.
rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), scalerRestoreTimeout)
defer cancel()
if _, rerr := setScalerMin(rctx, httpScaledObjectClientset, dynClient, scalerNamespace, f.Name, wantKafka, 1, 0); rerr != nil {
err = fmt.Errorf("%w (also failed to restore scale-to-zero: %v)", err, rerr)
}
}()
// The add-on copies the HTTPScaledObject minimum into a ScaledObject of
// the same name asynchronously, and KEDA scales from that one.
if wantHTTP {
if err = WaitForScaledObjectMinReplicas(ctx, dynClient, scalerNamespace, f.Name, 1, scalerHoldTimeout); err != nil {
return fn.DeploymentResult{}, fmt.Errorf("failed waiting for the held replica of function %q: %w", f.Name, err)
}
}
}

// execute raw deployment deployer
deployResult, err := d.Deployer.Deploy(ctx, f)
if err != nil {
Expand Down Expand Up @@ -325,16 +358,17 @@ func (d *Deployer) Deploy(ctx context.Context, f fn.Function) (fn.DeploymentResu
annotations := deployer.GenerateCommonAnnotations(f, d.decorator, false, KedaDeployerName)

target := deployTarget{
clientset: k8sClientset,
dynClient: dynClient,
ref: ref,
deployment: deployment,
appService: appService,
labels: labels,
annotations: annotations,
minScale: minScale,
maxScale: maxScale,
scale: f.Scale,
clientset: k8sClientset,
dynClient: dynClient,
ref: ref,
deployment: deployment,
appService: appService,
labels: labels,
annotations: annotations,
minScale: minScale,
maxScale: maxScale,
scale: f.Scale,
onScalerReconciled: func() { restoreHold = false },
}

if d.exposer != nil && fn.ActiveExpose(f.Expose) {
Expand Down Expand Up @@ -402,6 +436,7 @@ func (d *Deployer) Deploy(ctx context.Context, f fn.Function) (fn.DeploymentResu
if err := ensureScaledObject(ctx, dynClient, so); err != nil {
return fn.DeploymentResult{}, fmt.Errorf("failed to ensure ScaledObject: %w", err)
}
restoreHold = false
}

if !needsAuth {
Expand Down Expand Up @@ -466,16 +501,17 @@ func (d *Deployer) validateExposure(f fn.Function, exposeRefusal error) error {
// choosing a path: the clients, the function's placement, replica bounds,
// and the live objects the HSO hangs off
type deployTarget struct {
clientset kubernetes.Interface
dynClient dynamic.Interface
ref deployer.ExposureRef
deployment *v1.Deployment
appService *corev1.Service
labels map[string]string
annotations map[string]string
minScale int32
maxScale int32
scale *fn.ScaleOptions
clientset kubernetes.Interface
dynClient dynamic.Interface
ref deployer.ExposureRef
deployment *v1.Deployment
appService *corev1.Service
labels map[string]string
annotations map[string]string
minScale int32
maxScale int32
scale *fn.ScaleOptions
onScalerReconciled func()
}

// bridgeHosts are the cluster-local names the HSO registers for f: requests
Expand Down Expand Up @@ -785,6 +821,9 @@ func ensureHTTPScaledObject(ctx context.Context, t deployTarget, hosts []string)
if _, err := httpScaledObjectClientset.HttpV1alpha1().HTTPScaledObjects(expected.Namespace).Create(ctx, expected, metav1.CreateOptions{}); err != nil {
return fmt.Errorf("failed to create HTTPScaledObject: %w", err)
}
if t.onScalerReconciled != nil {
t.onScalerReconciled()
}

if err := WaitForHTTPScaledObjectAvailable(ctx, httpScaledObjectClientset, t.ref.FunctionNamespace, expected.Name, k8s.DefaultWaitingTimeout); err != nil {
return fmt.Errorf("HTTPScaledObject did not become ready: %w", err)
Expand All @@ -804,6 +843,9 @@ func ensureHTTPScaledObject(ctx context.Context, t deployTarget, hosts []string)
if _, err = httpScaledObjectClientset.HttpV1alpha1().HTTPScaledObjects(expected.Namespace).Update(ctx, expected, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("failed to update HTTPScaledObject: %w", err)
}
if t.onScalerReconciled != nil {
t.onScalerReconciled()
}

if err := WaitForHTTPScaledObjectAvailable(ctx, httpScaledObjectClientset, t.ref.FunctionNamespace, expected.Name, k8s.DefaultWaitingTimeout); err != nil {
return fmt.Errorf("HTTPScaledObject did not become ready: %w", err)
Expand All @@ -812,6 +854,10 @@ func ensureHTTPScaledObject(ctx context.Context, t deployTarget, hosts []string)
return nil
}

if t.onScalerReconciled != nil {
t.onScalerReconciled()
}

return nil
}

Expand Down
Loading
Loading