Files
uptimesebi/cmd/statuspage/main.go
T
Sebastian UnterschützandClaude Opus 5.5 a9f94fc492
ci / image (pull_request) Successful in 7m15s
ci / test (pull_request) Successful in 9m5s
ci / lint (pull_request) Successful in 14m17s
ci / build (pull_request) Successful in 15m59s
feat(agents): multi-arch checker and status page images on scratch
uptimesebi-checker and uptimesebi-statuspage for linux/amd64, arm64,
arm/v7 and arm/v6, from a Raspberry Pi Zero to servers. tools/image
assembles them from the cross-compiled binaries without Docker or
emulation: one layer on an empty base with the binary, a data volume
owned by the unprivileged user and a HEALTHCHECK running the new
`checker health` / `statuspage health` commands. The binaries embed time
zone data and fallback CA roots, so no base image ever needs updating.
CI pushes them with the same channel tags as the main image; releases
carry tarballs for all four platforms.

Refs #128

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 18:33:42 +01:00

187 lines
5.9 KiB
Go

// Command statuspage serves public status pages, including on customer
// domains. Like the checker it reads data only through the API.
package main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"time"
"github.com/caddyserver/certmagic"
"github.com/google/uuid"
"go.uber.org/zap"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
"git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
func main() {
if len(os.Args) == 2 && os.Args[1] == "health" {
if err := health(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
log, level := platform.NewLogger("statuspage")
// Route the standard log package and dependencies through the same handler.
slog.SetDefault(log)
if err := run(log, level); err != nil {
log.Error("exit", "error", err)
os.Exit(1)
}
}
func run(log *slog.Logger, level *slog.LevelVar) error {
cfg, err := config.Load[config.StatusPage]()
if err != nil {
return err
}
level.Set(cfg.LogLevel)
if err := cfg.Validate(); err != nil {
return err
}
ctx, stop := platform.SignalContext()
defer stop()
client := agentapi.NewClient(cfg.APIURL, cfg.Token, uuid.New(), buildinfo.Version)
if err := checkToken(ctx, client, log); err != nil {
return err
}
cacheDir, err := resolveCacheDir(cfg.CacheDir)
if err != nil {
return err
}
catalog, err := i18n.Load()
if err != nil {
return err
}
pages, err := statuspage.New(client, catalog, log, statuspage.Options{Hosts: cfg.Hosts, CacheDir: filepath.Join(cacheDir, "pages")})
if err != nil {
return err
}
apiProbe := func(ctx context.Context) error { _, err := client.Hello(ctx); return err }
health := platform.NewHealth(map[string]platform.Probe{
"pages": func(ctx context.Context) error { return pages.Ready(ctx, apiProbe) },
})
r := platform.NewRouter(log)
if err := platform.TrustProxies(r, cfg.TrustedProxies); err != nil {
return err
}
health.Register(r)
r.StaticFS("/static", web.Static())
pages.Mount(r)
go pages.Run(ctx)
if !cfg.TLS {
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
}
tlsConfig, challenges, err := certificates(ctx, cfg, client, pages, filepath.Join(cacheDir, "certs"), log)
if err != nil {
return err
}
https := platform.NewHTTPServer(cfg.TLSListen, r)
https.TLSConfig = tlsConfig
plain := platform.NewHTTPServer(cfg.Listen, challenges(redirectToHTTPS(r)))
errs := make(chan error, 2)
go func() { errs <- platform.Serve(ctx, log, plain, health, 5*time.Second, cfg.ShutdownTimeout) }()
go func() { errs <- platform.ServeTLS(ctx, log, https, health, 5*time.Second, cfg.ShutdownTimeout) }()
err = <-errs
stop()
return errors.Join(err, <-errs)
}
// certificates sets up on-demand ACME certificates stored through the API,
// shared by every instance of this status page server.
func certificates(ctx context.Context, cfg config.StatusPage, client *agentapi.Client, pages *statuspage.Server, certDir string, log *slog.Logger) (*tls.Config, func(http.Handler) http.Handler, error) {
var magic *certmagic.Config
cache := certmagic.NewCache(certmagic.CacheOptions{
GetConfigForCert: func(certmagic.Certificate) (*certmagic.Config, error) { return magic, nil },
})
magic = certmagic.New(cache, certmagic.Config{
Storage: statuspage.NewCertStorage(client, certDir),
OnDemand: &certmagic.OnDemandConfig{DecisionFunc: pages.AllowCertificate},
Logger: zap.NewNop(),
})
issuer := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{CA: cfg.ACMECA, Email: cfg.ACMEEmail, Agreed: true})
magic.Issuers = []certmagic.Issuer{issuer}
go func() {
<-ctx.Done()
cache.Stop()
}()
tc := magic.TLSConfig()
tc.NextProtos = append([]string{"h2", "http/1.1"}, tc.NextProtos...)
log.Info("tls enabled", "ca", cfg.ACMECA, "listen", cfg.TLSListen)
return tc, issuer.HTTPChallengeHandler, nil
}
// redirectToHTTPS sends page requests to HTTPS but keeps health checks on
// plain HTTP for load balancers and orchestrators.
func redirectToHTTPS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/healthz" || r.URL.Path == "/readyz" {
next.ServeHTTP(w, r)
return
}
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
host = r.Host
}
http.Redirect(w, r, "https://"+host+r.URL.RequestURI(), http.StatusMovedPermanently)
})
}
// checkToken rejects tokens of the wrong kind or revoked tokens, but starts
// anyway when the API is unreachable: cached pages must be served exactly
// when the rest of the system has trouble.
func checkToken(ctx context.Context, client *agentapi.Client, log *slog.Logger) error {
hctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
hello, err := client.Hello(hctx)
switch {
case errors.Is(err, agentapi.ErrUnauthorized):
return err
case err != nil:
log.Warn("api unreachable at start; serving cached pages", "error", err)
return nil
case hello.Kind != "statuspage":
return fmt.Errorf("token belongs to a %s agent, not a status page server", hello.Kind)
}
log.Info("connected to api", "agent", hello.Name)
return nil
}
func resolveCacheDir(dir string) (string, error) {
if dir != "" {
return dir, nil
}
base, err := os.UserCacheDir()
if err != nil {
return "", fmt.Errorf("no cache directory; set UPTIME_STATUSPAGE_CACHE_DIR: %w", err)
}
return filepath.Join(base, "uptimesebi-statuspage"), nil
}
// health probes the running statuspage in this container.
func health() error {
cfg, err := config.Load[config.StatusPage]()
if err != nil {
return err
}
return platform.ProbeLocal(context.Background(), cfg.Listen)
}