kubernetes: Graceful Node Shutdown does not update endpoints for terminating pods

What happened?

When graceful node shutdown is enabled, I expect that services are drained appropriately during pod shutdown (i.e. the same way that kubectl delete pod would work). However this doesn’t seem to be the case - the pod never enters the Terminating state according to kubectl and doesn’t get removed from the service endpoints until it enters the Completed or Failed state. This causes connection errors and lost requests in Cluster-routed services.

What did you expect to happen?

After pod termination starts, the EndpointSlice should be updated to have the pod that is terminating removed or marked terminating, even before the pod is fully shut down. This is what happens when a pod gets removed for any other reason (e.g. kubectl delete pod).

How can we reproduce it (as minimally and precisely as possible)?

You can see the repro at https://github.com/mikekap/vagrant-kubeadm-kubernetes/tree/graceful-shutdown-repro . The repro sets up a 2 node cluster with graceful shutdown enabled and a simple deployment/service.

Here is the deployment/service yaml pasted again
apiVersion: apps/v1
kind: Deployment
metadata:
  name: echo-deployment
spec:
  selector:
    matchLabels:
      app: echo
  replicas: 2
  template:
    metadata:
      labels:
        app: echo
    spec:
      containers:
      - name: echo
        image: mendhak/http-https-echo
        readinessProbe:
          httpGet:
            path: /healthz
            port: 8080
        lifecycle:
          preStop:
            exec:
              command: ["/bin/sh", "-c", "echo 'Begin shutdown' > /proc/1/fd/1; sleep 20; echo 'End shutdown' > /proc/1/fd/1; exit 0"]
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: echo
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080

To reproduce:

  • Run the deployment, preferably one pod on each node.
  • Run watch -n 1 'kubectl describe endpointslice my-service-5j2nw' in a separate terminal (you’ll need to figure out the right name unfortunately)
  • Use the virtualbox UI to send an ACPI shutdown to one of the nodes.

Within 20 seconds (the preStop hook duration), the EndpointSlice should be updated to have the pod that is terminating removed. This is what happens when a pod gets removed for any other reason (e.g. kubectl delete pod).

To ensure that everything else worked, you can reboot the node and see the journal logs (via something like journalctl -b -1) of the shutdown sequence triggering the kubelet graceful shutdown logic.

Anything else we need to know?

No response

Kubernetes version

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"25", GitVersion:"v1.25.2", GitCommit:"5835544ca568b757a8ecae5c153f317e5736700e", GitTreeState:"clean", BuildDate:"2022-09-21T14:33:49Z", GoVersion:"go1.19.1", Compiler:"gc", Platform:"darwin/amd64"}
Kustomize Version: v4.5.7
Server Version: version.Info{Major:"1", Minor:"26", GitVersion:"v1.26.3", GitCommit:"9e644106593f3f4aa98f8a84b23db5fa378900bd", GitTreeState:"clean", BuildDate:"2023-03-15T13:33:12Z", GoVersion:"go1.19.7", Compiler:"gc", Platform:"linux/amd64"}

Cloud provider

None

OS version

# On Linux:
$ cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04.2 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.2 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy
$ uname -a
Linux master-node 5.15.0-67-generic #74-Ubuntu SMP Wed Feb 22 14:14:39 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

Install tools

kubeadm

Container runtime (CRI) and version (if applicable)

Related plugins (CNI, CSI, …) and versions (if applicable)

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 10
  • Comments: 52 (49 by maintainers)

Most upvoted comments

As part of the exploration of this, I’ve created a design proposal for the solution that would address this - please read https://docs.google.com/document/d/1t25jgO_-LRHhjRXf4KJ5xY_t8BZYdapv7MDAxVGY6R8/edit?usp=sharing

(i.e. to try to salvage pods post node restart over letting the node start empty), but this choice is definitely user-hostile and controller-author hostile

Kube as a project has chosen to not change default behavior over time so as to reduce “surprise” for existing users, and that puts a higher burden on new users (more new specific things to learn). Because we have existing users with large fleets in “forever” node environments, we can’t just delete the pods - it would be user-hostile and hostile to their non-controller automation.

I agree with you that this is surprising and I agree we should be finding a way to either improve graceful node shutdown via the KEP for GA or spawn a new KEP to formally define an a way to indicate workloads will be temporarily disrupted and endpoints should properly react (that’ll be new API surface area).

In the specific, we can’t rely on there being a parent controller because there are many scenarios where automation creates singular pods - all pods are mortal, but we try to avoid disrupting them unnecessarily (which is indeed surprising to users when they do get disrupted). A node restart is not a guarantee that a pod can’t happily continue running past that restart.

Would you happen to have an example of where this is used? I can’t claim to have run a lot of different things on kube, but I have never seen naked, unmanaged pods used for anything other than demos (i.e. kubectl run). Or is this more about recovering contents of emptyDir volumes and the like after a restart?

One issue here might be that if you want this to continue working as before graceful shutdown, the container might need to know if it has a chance of coming back. e.g. some sort of long-running distributed data crunching task would likely signal a “full disconnect” on a SIGTERM since that’s the deletion signal too.

More generally, I should clarify that graceful node shutdown is an an additive feature to Kubernetes - it added the concept of a node being shutdown with the intent that the node may not come back (i.e. to support spot nodes on cloud primarily). However, the default and historical behavior of Kubernetes is the exact opposite - nodes can go away and come back at any time and Kubernetes’ was designed to be resilient to all of those scenarios (so we’re paranoid about specific aspects of “stopping early” to avoid failing to restart things).

This is what I meant by “if this is a breaking change, IMO it’s worth doing.” This default does not match with the majority of kube clusters deployed today. Not to say the new default here should be to “break” the current behavior and prevent nodes from rejoining clusters entirely under their old identity – the breaking change would be to start with no pods after graceful restart.

Re: node controller disruption - David indicates there seems to be a bug in the controller that has prevented this from working ever, so can discount for now.

Re: your other code change

I tried to think about all the ways the linked fix could interact with the cluster, and I believe it corrects the issue you are seeing because of an unintended side effect of setting the state to be failed in the kubelet. However, I believe (but have not tested) breaks the expected behavior of the Kubelet allowing readiness probes to keep a pod in the serving rotation after it is marked deleted, so it works to fix your scenario but breaks others (please correct me if my review is inaccurate).

That sounds entirely right - we don’t use unready endpoints anywhere in our clusters so “breaking” it probably just doesn’t affect us. Your review seems accurate to me. Definitely happy to close this PR - I realized I was wrong in my diagnosis later in the thread here.

Re: this issue

My triage of this issue is that as described, “kubernetes is working as intended” in this case. There is a gap in that there is no recommendation for cloud-portable shutdown for workloads, but expecting delete pod semantics is a provider specific behavior that graceful shutdown does not provide today (it’s not an unreasonable ask, it’s just not supported by Kubernetes but is instead something provider specific).

The Kubernetes-portable behavior is to use the readiness endpoint to control being in rotation during graceful shutdown - being deleted is not required to be drained in a conformant distro today. So in the scenario you describe, your readiness endpoint should start returning false during your preStop hook if you want to be taken out of rotation fast.

A few points here:

  • Most tactically, this page needs a serious caveat that readiness probes are load-bearing for shutdown - you need a lame duck mode or similar. A simple sleep in a preStop hook won’t work anymore (or doesn’t already, but graceful shutdown is not GA).
  • This stance probably defeats the purpose of KEP-3960. “This enhancement aims to provide a more straightforward way to manage graceful [pod] shutdowns.” It cannot fulfill that in a world where lame duck mode is required. The only real way I could see keeping it is saying “graceful NODE shutdown does not mean graceful POD shutdown” but that sounds ridiculous and even the graceful shutdown KEP says “Gracefully terminate all … pods.”
  • This stance is against the “motivation” of the graceful shutdown KEP - which was to REDUCE the variety of behaviors of processes that kube manages. https://github.com/kubernetes/enhancements/blob/master/keps/sig-node/2000-graceful-node-shutdown/README.md#motivation : “Users and cluster administrators expect that pods will adhere to expected pod lifecycle including pod termination.”
  • Ultimately this is your decision (i.e. to try to salvage pods post node restart over letting the node start empty), but this choice is definitely user-hostile and controller-author hostile. Kubelet-led evictions are all corner cases (e.g. node shutdown, resource exhaustion eviction, etc) and nobody will test these. The decision to divide “pod shutdown” and “container shutdown” does not help the majority of users: e.g. the sleep preStop hook is fundamentally broken in cloud clusters under these assumptions.
  • Regardless of the outcome, thank you @smarterclayton for the in-depth explanations and rationale.

So zooming out:

GracefulShutdown by itself does not say whether the node is coming back or not - that’s the responsibility of the agent that “owns” the node (cloud provider, human admin, vm orchestrator, whatever) to determine whether the node is coming back or not. So using graceful shutdown by itself can make no decision on whether to delete the pods or not, only to correctly represent that the pod is shutting down and being not ready.

GracefulShutdown was not intended to replace a controlled drain operation on the node. If the use case described here is assuming that graceful shutdown will guarantee that pods are terminated, that is not generally true and not the design we intended for GracefulShutdown. Any “set delete timestamp” action would have to be opt in and probably not the responsibility of the kubelet generally - the responsibility today belongs to the initiator of the “node going away permanently” action (cloud provider, orchestrator, human) and I could argue it should stay there.

I think we can say that GracefulShutdown is intended to end the processes of pods as best effort within a specific timeframe and report the status of those pods appropriately. At minimum, the pods should be described as non ready, and the containers should be described as stopped with terminal exit codes and/or phase (RestartAlways pods should be left in running phase, because there was no signal that the node is not coming back). But it is best effort - it cannot guarantee due to being part of a distributed system that those status updates will propagate.

The remaining question is whether the node is doing a good enough job during graceful shutdown. I think the answer given this thread is “no” - I would expect the following (as i commented on the other bug):

  1. Pod deletion and pod readiness are orthogonal, they should be kept orthogonal
  2. When the kubelet shuts down a pod gracefully for any reason (including deletion, static pod update, graceful node shutdown) the kubelet should continue to run readiness probes until a readiness check is “not ready” or the container stops, then the kubelet should stop readiness probes and not restart them until the container is started again a. if the container has no readiness probe, the ready state should go to False after the prestop completes
  3. The kubelet should aggressively attempt to report the most important status transitions during graceful shutdown, prioritizing ready -> false and container -> stop. This is challenging today because the kubelet status loop is single threaded, but we have discussed improving it.
  4. The initiator of node graceful shutdown is responsible for deciding whether the pod will never come back - if so invoke pod deletion before or concurrent with node graceful shutdown.

Anything I’m missing? Does this match everyone’s experience and expectations?

Double check that your service has a sigterm handler that sets the readiness endpoint to false. Some of the behavior described on this ticket is expected behavior. If the readiness endpoint is never set to false, then the pod is expected to stay ready until the entire lifecycle is terminated.

Because of a bug(#124648), readiness probe doesn’t work during pod termination triggered in kubelet such as eviction and node shutdown. This may be one of reasons why an endpoint is not updated early.

@rphillips I don’t think this is specced behavior: readiness probes auto-fail when pods start shutdown normally. See this page: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes

Note: If you want to be able to drain requests when the Pod is deleted, you do not necessarily need a readiness probe; on deletion, the Pod automatically puts itself into an unready state regardless of whether the readiness probe exists. The Pod remains in the unready state while it waits for the containers in the Pod to stop.