diff --git a/Dockerfile b/Dockerfile index 90c76fe..67995c9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -23,7 +23,8 @@ WORKDIR /src COPY go.mod go.sum ./ RUN go mod download 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 RUN adduser -D -u 10001 allmende && mkdir /data && chown allmende /data diff --git a/Makefile b/Makefile index 7b71b60..4194c6f 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ REGION ?= u1j# Bonn; several are allowed: make run REGION="u1j u1h" (u1h is Colo 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 @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 -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 go vet ./... diff --git a/cmd/allmende/main.go b/cmd/allmende/main.go index 1328398..f60445b 100644 --- a/cmd/allmende/main.go +++ b/cmd/allmende/main.go @@ -16,6 +16,10 @@ import ( "time" ) +// version is set at build time (-ldflags "-X main.version="); the +// container image carries the commit it was built from. +var version = "dev" + const ( certLifetime = 365 * 24 * time.Hour @@ -49,6 +53,8 @@ func main() { err = cmdRun(os.Args[2:]) case "recover": err = cmdRecover(os.Args[2:]) + case "version", "-v", "--version": + fmt.Println("allmende", version) case "help", "-h", "--help": fmt.Print(usage) default: diff --git a/cmd/allmende/run.go b/cmd/allmende/run.go index 90081b0..d53c177 100644 --- a/cmd/allmende/run.go +++ b/cmd/allmende/run.go @@ -118,7 +118,9 @@ func cmdRun(args []string) error { } 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() 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]+"…", "regions", []string(regions), "http", ln.Addr().String()) for _, a := range node.Addrs() { @@ -216,11 +218,36 @@ func cmdRun(args []string) error { <-ctx.Done() log.Info("shutting down") + forceExitOnSecondSignal(log, shutdownDeadline, os.Exit) shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() 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 // listings. Gossip only reaches peers connected at that moment; this makes // sure newcomers hear about them without waiting for a sync. diff --git a/cmd/allmende/shutdown_test.go b/cmd/allmende/shutdown_test.go new file mode 100644 index 0000000..76ae294 --- /dev/null +++ b/cmd/allmende/shutdown_test.go @@ -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") + } +}