The -autoupdate variant of the checker and status page images adds a launcher layer. The launcher runs the agent as a child process and keeps it on the platform's release: GET /agent/v1/update names the API's own release and the agent image for it, the launcher downloads the binary for its platform from the registry, accepts it only when the index is signed with a release key for exactly that version, swaps the agent gracefully and rolls back when the new release does not become ready or crashes right after starting. Agents never get ahead of the API, and installations on unreleased builds are not followed. CI pushes both variants and signs each index with RELEASE_SIGNING_KEY (minisign signature in a sha256-<digest>.minisig image next to it). The image builder moves to internal/agentimage; the API image job takes the build job's version so the API reports the release its agents are tagged with. Agents gain a version command. Closes #129 Closes #128 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
191 lines
6.0 KiB
Go
191 lines
6.0 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] == "version" {
|
|
fmt.Println(buildinfo.Version)
|
|
return
|
|
}
|
|
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, "/healthz")
|
|
}
|