Files
Sebastian UnterschützandClaude Opus 5.5 6e2f8d0626 feat(statuspage): keep serving status pages while the api is down
Snapshots are persisted to UPTIME_STATUSPAGE_CACHE_DIR and loaded at
start, so pages survive restarts during an outage. Cached pages are
answered without waiting for the API, refreshed in the background and
served for as long as the API stays unreachable, with a notice once they
are older than five minutes. Only an explicit not found from the API
removes a page. Readiness no longer depends on the API when pages are
cached, the server starts without a reachable API, and certificates are
mirrored locally so HTTPS keeps working after a restart.

Closes #56

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 09:05:20 +01:00

168 lines
5.4 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() {
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.Common.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)
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
}