Orderly shutdown on SIGHUP too, forced exit when stuck; version in the image

SIGINT, SIGTERM and SIGHUP all shut the node down in order (SIGTERM is what a
Kubernetes pod termination sends). A second signal, or 20 seconds (below the
30 s Kubernetes grants), stops the process at once, so a stuck shutdown cannot
hang.

The binary knows its version (allmende version, and the 'node running' log
line); the image is built with the commit as version and 'make image' pushes it
tagged with that commit, refusing a dirty tree.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-18 13:08:14 +01:00
co-authored by Claude Sonnet 5.5
parent 7120959cb8
commit 0cfb59c469
5 changed files with 88 additions and 4 deletions
+2 -1
View File
@@ -23,7 +23,8 @@ WORKDIR /src
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
COPY . . COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/allmende ./cmd/allmende ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/allmende ./cmd/allmende
FROM alpine:3.22 FROM alpine:3.22
RUN adduser -D -u 10001 allmende && mkdir /data && chown allmende /data RUN adduser -D -u 10001 allmende && mkdir /data && chown allmende /data
+10 -1
View File
@@ -3,7 +3,7 @@ REGION ?= u1j# Bonn; several are allowed: make run REGION="u1j u1h" (u1h is Colo
DATA ?= DATA ?=
FLAGS := $(if $(DATA),--data $(DATA)) FLAGS := $(if $(DATA),--data $(DATA))
.PHONY: help build run init test vet web web-test e2e check clean docker .PHONY: help build run init test vet web web-test e2e check clean docker image
help: ## list the targets help: ## list the targets
@grep -E '^[a-z-]+:.*## ' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-10s %s\n", $$1, $$2}' @grep -E '^[a-z-]+:.*## ' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-10s %s\n", $$1, $$2}'
@@ -20,6 +20,15 @@ run: build ## run a node (default region Bonn): make run [REGION=u1j] [DATA=dir]
docker: ## build the container image (allmende:dev) docker: ## build the container image (allmende:dev)
docker build -t allmende:dev . docker build -t allmende:dev .
IMAGE ?= git.stinnesbeck.com/nils/allmende
image: ## build and push the image, tagged with the commit (clean tree only); prints the tag to put in k8s/base/kustomization.yaml
@test -z "$$(git status --porcelain)" || { echo "commit your changes first: the tag must name what is in the image"; exit 1; }
@tag=$$(git rev-parse --short HEAD) && \
docker build --build-arg VERSION=$$tag -t $(IMAGE):$$tag . && \
docker push $(IMAGE):$$tag && \
echo "pushed $(IMAGE):$$tag -> set newTag: $$tag in k8s/base/kustomization.yaml"
vet: ## go vet vet: ## go vet
go vet ./... go vet ./...
+6
View File
@@ -16,6 +16,10 @@ import (
"time" "time"
) )
// version is set at build time (-ldflags "-X main.version=<git sha>"); the
// container image carries the commit it was built from.
var version = "dev"
const ( const (
certLifetime = 365 * 24 * time.Hour certLifetime = 365 * 24 * time.Hour
@@ -49,6 +53,8 @@ func main() {
err = cmdRun(os.Args[2:]) err = cmdRun(os.Args[2:])
case "recover": case "recover":
err = cmdRecover(os.Args[2:]) err = cmdRecover(os.Args[2:])
case "version", "-v", "--version":
fmt.Println("allmende", version)
case "help", "-h", "--help": case "help", "-h", "--help":
fmt.Print(usage) fmt.Print(usage)
default: default:
+29 -2
View File
@@ -118,7 +118,9 @@ func cmdRun(args []string) error {
} }
defer st.Close() defer st.Close()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) // SIGTERM is what Kubernetes and 'docker stop' send; SIGHUP arrives when the
// terminal is closed. All three shut the node down in an orderly way.
ctx, stop := signal.NotifyContext(context.Background(), shutdownSignals...)
defer stop() defer stop()
node, err := p2p.New(ctx, p2p.Config{ node, err := p2p.New(ctx, p2p.Config{
@@ -177,7 +179,7 @@ func cmdRun(args []string) error {
} }
}() }()
log.Info("node running", log.Info("node running", "version", version,
"peer_id", node.ID().String(), "identity", dev.Cert.Author[:12]+"…", "peer_id", node.ID().String(), "identity", dev.Cert.Author[:12]+"…",
"regions", []string(regions), "http", ln.Addr().String()) "regions", []string(regions), "http", ln.Addr().String())
for _, a := range node.Addrs() { for _, a := range node.Addrs() {
@@ -216,11 +218,36 @@ func cmdRun(args []string) error {
<-ctx.Done() <-ctx.Done()
log.Info("shutting down") log.Info("shutting down")
forceExitOnSecondSignal(log, shutdownDeadline, os.Exit)
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() defer cancel()
return srv.Shutdown(shutdown) return srv.Shutdown(shutdown)
} }
// shutdownSignals end the node in an orderly way.
var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP}
// shutdownDeadline is how long an orderly shutdown may take. It stays below
// the 30 seconds Kubernetes waits by default before it kills the pod.
const shutdownDeadline = 20 * time.Second
// forceExitOnSecondSignal makes a stuck shutdown end anyway: on another signal
// (a second Ctrl+C) or when the deadline passes, the process exits with 1.
func forceExitOnSecondSignal(log *slog.Logger, deadline time.Duration, exit func(int)) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, shutdownSignals...)
go func() {
defer signal.Stop(sig)
select {
case <-sig:
log.Warn("second signal: stopping now")
case <-time.After(deadline):
log.Warn("shutdown is taking too long: stopping now", "after", deadline)
}
exit(1)
}()
}
// announce periodically re-gossips this identity's revocations and live // announce periodically re-gossips this identity's revocations and live
// listings. Gossip only reaches peers connected at that moment; this makes // listings. Gossip only reaches peers connected at that moment; this makes
// sure newcomers hear about them without waiting for a sync. // sure newcomers hear about them without waiting for a sync.
+41
View File
@@ -0,0 +1,41 @@
package main
import (
"io"
"log/slog"
"syscall"
"testing"
"time"
)
func quietLog() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func TestAStuckShutdownEndsAfterTheDeadline(t *testing.T) {
code := make(chan int, 1)
forceExitOnSecondSignal(quietLog(), 50*time.Millisecond, func(c int) { code <- c })
select {
case c := <-code:
if c != 1 {
t.Fatalf("exit code %d, want 1", c)
}
case <-time.After(2 * time.Second):
t.Fatal("the deadline did not end the process")
}
}
func TestASecondSignalEndsTheShutdownAtOnce(t *testing.T) {
code := make(chan int, 1)
forceExitOnSecondSignal(quietLog(), time.Minute, func(c int) { code <- c })
// Signals sent to our own process reach the handler registered above.
if err := syscall.Kill(syscall.Getpid(), syscall.SIGHUP); err != nil {
t.Fatal(err)
}
select {
case c := <-code:
if c != 1 {
t.Fatalf("exit code %d, want 1", c)
}
case <-time.After(2 * time.Second):
t.Fatal("a second signal did not end the process")
}
}