Files
allmende/cmd/allmende/run.go
T
nilsandClaude Sonnet 5.5 0cfb59c469 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
2026-11-18 13:08:14 +01:00

317 lines
11 KiB
Go

package main
import (
"context"
"errors"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"slices"
"strings"
"syscall"
"time"
"git.stinnesbeck.com/nils/allmende/internal/api"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/inbox"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/p2p"
"git.stinnesbeck.com/nils/allmende/internal/places"
"git.stinnesbeck.com/nils/allmende/internal/store"
"git.stinnesbeck.com/nils/allmende/web"
)
const (
announceFirst = 10 * time.Second
announceInterval = 30 * time.Minute
certWarnBefore = 30 * 24 * time.Hour
)
func cmdRun(args []string) error {
fs := flag.NewFlagSet("run", flag.ExitOnError)
data := dataFlag(fs)
var regions, bootstrap, listen listFlag
fs.Var(&regions, "region", "region to replicate: a 3-character geohash (u1x) or a place name (\"Bonn\", \"Köln\"); repeatable")
fs.Var(&bootstrap, "bootstrap", "extra bootstrap peer: …/p2p/<id> or /dnsaddr/<name>; repeatable")
noDefaultBootstrap := fs.Bool("no-default-bootstrap", false,
"do not use the built-in bootstrap name "+p2p.DefaultBootstrap)
noDHT := fs.Bool("no-dht", false, "do not look for peers through the DHT")
public := fs.Bool("public", false,
"this node is reachable from the internet: serve the DHT and relay for nodes behind a NAT (for bootstrap nodes)")
var announceAddrs listFlag
fs.Var(&announceAddrs, "announce",
"address others should dial, when this node sits behind a router or in a container, e.g. /dns4/node.example.org/tcp/4001; repeatable")
fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)")
httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API")
noLoginLink := fs.Bool("no-login-link", false,
"do not print the owner sign-in link (it holds the admin token); use where the terminal is a log, e.g. in a container")
noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network")
difficulty := fs.Int("difficulty", listing.DefaultDifficulty,
"proof-of-work bits for listings; must match the rest of the network")
msgDifficulty := fs.Int("message-difficulty", message.DefaultDifficulty,
"proof-of-work bits for messages; must match the rest of the network")
maxNewThreads := fs.Int("max-new-threads", inbox.DefaultMaxNewThreads,
"how many new conversations each of your listings can start per day")
fs.Parse(args)
// Place names become region codes; say what each one turned into.
codes, notes, err := resolveRegions(regions, func() ([]places.Place, error) { return places.Load(web.Files()) })
if err != nil {
return err
}
for _, n := range notes {
fmt.Fprintln(os.Stderr, n)
}
regions = codes
// Regions the owner chose in the browser win over --region, which then only
// says where a node starts the first time.
saved, ok, err := loadRegions(*data)
if err != nil {
return err
}
if ok {
if len(regions) > 0 && !slices.Equal(regions, saved) {
slog.Info("using the regions chosen in the browser, not --region; delete "+regionsFile+" to use --region again",
"regions", saved)
}
regions = saved
}
// Without a region the node only helps others connect, until the owner
// chooses one in the browser (see the sign-in hint printed below).
if !*noDefaultBootstrap {
bootstrap = append(bootstrap, p2p.DefaultBootstrap)
}
dev, err := identity.LoadDevice(*data)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("%s is not set up yet: run 'allmende init' first", *data)
}
return err
}
until := time.Until(time.Unix(dev.Cert.ExpiresAt, 0))
renew := "run 'allmende recover' to renew it"
if _, err := os.Stat(filepath.Join(*data, noRecoveryFile)); err == nil {
renew = "this identity has no recovery phrase, so it cannot be renewed: start over with 'allmende init --no-phrase' on an empty data directory (a new identity, so update any DNS records that name this node)"
}
if until <= 0 {
return errors.New("this device's certificate has expired; " + renew)
}
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
if until < certWarnBefore {
log.Warn("device certificate expires soon; "+renew,
"expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
}
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{
Difficulty: *difficulty, MessageDifficulty: *msgDifficulty,
})
if err != nil {
return err
}
defer st.Close()
// 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{
Device: dev,
Store: st,
ListenAddrs: listen,
Bootstrap: bootstrap,
Regions: regions,
MDNS: !*noMDNS,
DHT: !*noDHT,
Public: *public,
Announce: announceAddrs,
PeerCache: filepath.Join(*data, peersFile),
Difficulty: *difficulty,
Logger: log,
MessageDifficulty: *msgDifficulty,
})
if err != nil {
return err
}
defer node.Close()
token := readToken(*data)
if token == "" {
log.Warn("no admin token found; publishing through the API is disabled")
}
in := &inbox.Inbox{
Store: st, Device: dev, Publisher: node,
Difficulty: *msgDifficulty, MaxNewThreads: *maxNewThreads,
}
handler := api.New(api.Config{
Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty,
MessageDifficulty: *msgDifficulty,
Inbox: in,
RegionKeeper: &regionKeeper{node: node, dir: *data},
})
ln, err := net.Listen("tcp", *httpAddr)
if err != nil {
return err
}
// Set before anything can call Collect (the server and the watcher below).
in.OnArrivals = arrivalNotice(ctx, log, st, ln.Addr().String())
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second, // publishing mines proof-of-work
IdleTimeout: 2 * time.Minute,
}
go func() {
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Error("http server", "err", err)
stop()
}
}()
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() {
log.Info("listening", "addr", a)
}
if host, _, _ := net.SplitHostPort(ln.Addr().String()); host != "127.0.0.1" && host != "::1" {
log.Warn("the HTTP API is reachable from other machines; put it behind TLS if it is public")
}
if *public {
name := strings.TrimPrefix(p2p.DefaultBootstrap, "/dnsaddr/")
if recs := bootstrapRecords(node.Addrs()); len(recs) > 0 {
fmt.Fprintf(os.Stderr, "\nBootstrap node. For fresh nodes to find it, publish these TXT records at _dnsaddr.%s:\n", name)
for _, r := range recs {
fmt.Fprintf(os.Stderr, " %s\n", r)
}
fmt.Fprintln(os.Stderr)
} else {
log.Warn("--public, but this node has no public address; a bootstrap node needs one (a server, or a forwarded port): publish dnsaddr=/ip4/<public ip>/tcp/<port>/p2p/<peer id>",
"peer_id", node.ID().String())
}
}
if token != "" {
// Printed to the terminal, not logged: the token must not end up in a
// log file. It sits in the URL fragment, which a browser never sends to
// a server; the page moves it into sessionStorage and removes it.
fmt.Fprint(os.Stderr, loginNotice(ln.Addr().String(), token, *noLoginLink, len(regions) == 0 && !*public, *data))
} else if len(regions) == 0 && !*public {
log.Warn("this node follows no region and has no admin token, so nobody can choose one: pass --region")
}
go announce(ctx, log, node, st, dev.Cert.Author)
go watchInbox(ctx, log, in)
go remindExpiring(ctx, log, st, dev.Cert.Author, ln.Addr().String())
<-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.
func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.Store, author string) {
timer := time.NewTimer(announceFirst)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
}
if revs, err := st.Revocations(ctx); err == nil {
for _, r := range revs {
if r.Author == author {
if err := node.PublishRevocation(ctx, r); err != nil {
log.Debug("announce revocation", "err", err)
}
}
}
}
if own, err := st.ByAuthor(ctx, author); err == nil {
for _, l := range own {
if err := node.Publish(ctx, l); err != nil {
log.Debug("announce listing", "id", l.ID, "err", err)
}
}
}
timer.Reset(announceInterval)
}
}
// loginNotice is what the node prints about signing in. With hide set (for a
// node whose terminal is a log, e.g. in a container) the link is left out and
// the notice only says where the token is.
func loginNotice(listenAddr, token string, hide, noRegions bool, dataDir string) string {
if hide {
return fmt.Sprintf("\nOwner login link not shown (--no-login-link). The token is in %s\n\n",
filepath.Join(dataDir, tokenFile))
}
s := fmt.Sprintf("\nOwner login (answer your inbox in the browser):\n %s\n\n", loginURL(listenAddr, token))
if noRegions {
s += "This node follows no region yet. Open the link above and choose where you want\nlistings from (and to publish) under \"My listings\" > \"Regions\".\n\n"
}
return s
}
// loginURL is the link that signs the owner in to the web UI.
func loginURL(listenAddr, token string) string {
return uiURL(listenAddr, "/login/"+token)
}
// uiURL is the address of a page of the web UI (route is the part after "#")
// as a browser on this machine can open it.
func uiURL(listenAddr, route string) string {
host, port, err := net.SplitHostPort(listenAddr)
if err != nil {
return "http://" + listenAddr + "/#" + route
}
// A wildcard address (0.0.0.0, ::) is not something a browser can open.
if ip := net.ParseIP(host); ip == nil || ip.IsUnspecified() {
host = "127.0.0.1"
}
// JoinHostPort brackets IPv6 addresses.
return "http://" + net.JoinHostPort(host, port) + "/#" + route
}