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
This commit is contained in:
1 parent
20664dd5dd
commit
6e2f8d0626
12 files changed
+660
-214
No files matched your search
@@ -1,15 +1,26 @@
|
||||
// Package statuspage serves public status pages from snapshots fetched
|
||||
// through the agent API. It keeps a short in-memory cache and keeps serving
|
||||
// the last snapshot for a while if the API is unreachable, so a page stays
|
||||
// up during the incidents it is meant to report.
|
||||
// through the agent API.
|
||||
//
|
||||
// A status page has to stay up during the incidents it reports, including
|
||||
// an outage of the API itself. Every snapshot is therefore kept in memory
|
||||
// and on disk, requests are answered from that copy without waiting for the
|
||||
// API, known pages are refreshed in the background, and the last known state
|
||||
// is served for as long as the API stays unreachable, survives restarts and
|
||||
// is marked as outdated once it ages. Only an explicit "not found" from the
|
||||
// API removes a page.
|
||||
package statuspage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -22,8 +33,11 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// freshFor is how long a snapshot is used without asking the API.
|
||||
freshFor = 30 * time.Second
|
||||
staleFor = 10 * time.Minute
|
||||
// staleNoticeAfter is when visitors are told the state may be outdated.
|
||||
staleNoticeAfter = 5 * time.Minute
|
||||
refreshInterval = 30 * time.Second
|
||||
)
|
||||
|
||||
// Source fetches snapshots; *agentapi.Client implements it.
|
||||
@@ -39,27 +53,107 @@ type Server struct {
|
||||
// ownHosts are the hosts that serve pages by slug; any other host is
|
||||
// looked up as a custom domain.
|
||||
ownHosts map[string]bool
|
||||
now func() time.Time
|
||||
// dir persists snapshots; empty keeps them in memory only.
|
||||
dir string
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string]entry
|
||||
mu sync.Mutex
|
||||
cache map[string]entry
|
||||
refreshing map[string]bool
|
||||
}
|
||||
|
||||
// entry is one cached page, also its on-disk form.
|
||||
type entry struct {
|
||||
snap agentapi.PageSnapshot
|
||||
missing bool
|
||||
fetched time.Time
|
||||
Key string `json:"key"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Slug string `json:"slug,omitempty"`
|
||||
Snap agentapi.PageSnapshot `json:"snapshot"`
|
||||
Fetched time.Time `json:"fetched"`
|
||||
}
|
||||
|
||||
// New returns a Server. ownHosts lists the host names of the default
|
||||
// domain, e.g. "status.example.com"; requests to other hosts are matched
|
||||
// against verified custom domains.
|
||||
func New(src Source, catalog *i18n.Catalog, log *slog.Logger, ownHosts []string) *Server {
|
||||
s := &Server{src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, now: time.Now, cache: map[string]entry{}}
|
||||
for _, h := range ownHosts {
|
||||
// Options configure a Server.
|
||||
type Options struct {
|
||||
// Hosts are the host names of the default domain, e.g.
|
||||
// "status.example.com"; requests to other hosts are matched against
|
||||
// verified custom domains.
|
||||
Hosts []string
|
||||
// CacheDir persists snapshots across restarts. Empty disables
|
||||
// persistence, which loses all pages on restart.
|
||||
CacheDir string
|
||||
}
|
||||
|
||||
// New returns a Server and loads snapshots persisted in o.CacheDir.
|
||||
func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Server, error) {
|
||||
s := &Server{
|
||||
src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir,
|
||||
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{},
|
||||
}
|
||||
for _, h := range o.Hosts {
|
||||
s.ownHosts[strings.ToLower(h)] = true
|
||||
}
|
||||
return s
|
||||
if s.dir != "" {
|
||||
if err := os.MkdirAll(s.dir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.loadDisk(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Server) loadDisk() error {
|
||||
files, err := filepath.Glob(filepath.Join(s.dir, "*.json"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range files {
|
||||
raw, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var e entry
|
||||
if err := json.Unmarshal(raw, &e); err != nil || e.Key == "" {
|
||||
s.log.Warn("ignoring unreadable cached page", "file", f, "error", err)
|
||||
continue
|
||||
}
|
||||
s.cache[e.Key] = e
|
||||
}
|
||||
if len(s.cache) > 0 {
|
||||
s.log.Info("loaded cached status pages", "count", len(s.cache))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) fileFor(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return filepath.Join(s.dir, hex.EncodeToString(sum[:16])+".json")
|
||||
}
|
||||
|
||||
// persist writes atomically so a crash never leaves a truncated snapshot.
|
||||
func (s *Server) persist(e entry) {
|
||||
if s.dir == "" {
|
||||
return
|
||||
}
|
||||
raw, err := json.Marshal(e)
|
||||
if err == nil {
|
||||
tmp := s.fileFor(e.Key) + ".tmp"
|
||||
if err = os.WriteFile(tmp, raw, 0o600); err == nil {
|
||||
err = os.Rename(tmp, s.fileFor(e.Key))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Warn("persisting status page failed", "page", e.Key, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) forget(key string) {
|
||||
s.mu.Lock()
|
||||
delete(s.cache, key)
|
||||
s.mu.Unlock()
|
||||
if s.dir != "" {
|
||||
_ = os.Remove(s.fileFor(key))
|
||||
}
|
||||
}
|
||||
|
||||
// Mount registers the page routes.
|
||||
@@ -67,6 +161,19 @@ func (s *Server) Mount(r *gin.Engine) {
|
||||
r.NoRoute(s.serve)
|
||||
}
|
||||
|
||||
// Ready reports whether the server can answer visitors: either the API is
|
||||
// reachable or pages are cached. A status page server must not drop out of
|
||||
// the load balancer just because the API is down.
|
||||
func (s *Server) Ready(ctx context.Context, apiProbe func(context.Context) error) error {
|
||||
s.mu.Lock()
|
||||
cached := len(s.cache)
|
||||
s.mu.Unlock()
|
||||
if cached > 0 {
|
||||
return nil
|
||||
}
|
||||
return apiProbe(ctx)
|
||||
}
|
||||
|
||||
// IsCustomDomain reports whether host is served as a custom domain.
|
||||
func (s *Server) IsCustomDomain(host string) bool {
|
||||
return !s.ownHosts[hostOnly(host)]
|
||||
@@ -99,45 +206,98 @@ func (s *Server) serve(c *gin.Context) {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
key = "slug:" + slug
|
||||
host = ""
|
||||
key, host = "slug:"+slug, ""
|
||||
}
|
||||
snap, ok := s.snapshot(c.Request.Context(), key, host, slug)
|
||||
e, ok := s.lookup(c.Request.Context(), key, host, slug)
|
||||
if !ok {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var staleSince time.Time
|
||||
if s.now().Sub(e.Fetched) > staleNoticeAfter {
|
||||
staleSince = e.Fetched
|
||||
}
|
||||
l := s.catalog.Match(c.GetHeader("Accept-Language"))
|
||||
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
|
||||
c.Header("Cache-Control", "public, max-age=30")
|
||||
c.Header("Content-Language", l.Lang())
|
||||
web.Render(c, http.StatusOK, web.PublicStatusPage(snap, web.PublicAssets{CSSHref: "/static/dist/app.css"}))
|
||||
web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap, web.PublicAssets{CSSHref: "/static/dist/app.css", StaleSince: staleSince}))
|
||||
}
|
||||
|
||||
func (s *Server) snapshot(ctx context.Context, key, host, slug string) (agentapi.PageSnapshot, bool) {
|
||||
now := s.now()
|
||||
// lookup answers from the cache whenever possible and refreshes in the
|
||||
// background; only unknown pages wait for the API.
|
||||
func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) {
|
||||
s.mu.Lock()
|
||||
e, cached := s.cache[key]
|
||||
s.mu.Unlock()
|
||||
if cached && now.Sub(e.fetched) < freshFor {
|
||||
return e.snap, !e.missing
|
||||
if cached {
|
||||
if s.now().Sub(e.Fetched) >= freshFor {
|
||||
go s.refresh(context.WithoutCancel(ctx), key, host, slug)
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
return s.fetch(ctx, key, host, slug)
|
||||
}
|
||||
|
||||
func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) {
|
||||
snap, err := s.src.Page(ctx, host, slug)
|
||||
switch {
|
||||
case err == nil:
|
||||
e = entry{snap: snap, fetched: now}
|
||||
case errors.Is(err, agentapi.ErrNotFound):
|
||||
e = entry{missing: true, fetched: now}
|
||||
default:
|
||||
if cached && now.Sub(e.fetched) < staleFor {
|
||||
s.log.WarnContext(ctx, "serving stale status page", "page", key, "error", err)
|
||||
return e.snap, !e.missing
|
||||
}
|
||||
s.log.ErrorContext(ctx, "fetching status page failed", "page", key, "error", err)
|
||||
return agentapi.PageSnapshot{}, false
|
||||
s.forget(key)
|
||||
return entry{}, false
|
||||
case err != nil:
|
||||
s.log.WarnContext(ctx, "fetching status page failed", "page", key, "error", err)
|
||||
s.mu.Lock()
|
||||
e, ok := s.cache[key]
|
||||
s.mu.Unlock()
|
||||
return e, ok
|
||||
}
|
||||
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now()}
|
||||
s.mu.Lock()
|
||||
s.cache[key] = e
|
||||
s.mu.Unlock()
|
||||
return e.snap, !e.missing
|
||||
s.persist(e)
|
||||
return e, true
|
||||
}
|
||||
|
||||
// refresh fetches key unless another refresh of it is running.
|
||||
func (s *Server) refresh(ctx context.Context, key, host, slug string) {
|
||||
s.mu.Lock()
|
||||
if s.refreshing[key] {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.refreshing[key] = true
|
||||
s.mu.Unlock()
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
delete(s.refreshing, key)
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
s.fetch(ctx, key, host, slug)
|
||||
}
|
||||
|
||||
// Run keeps every known page fresh until ctx ends, so pages stay current
|
||||
// even without visitors and the cache is warm when the API goes away.
|
||||
func (s *Server) Run(ctx context.Context) {
|
||||
tick := time.NewTicker(refreshInterval)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
s.mu.Lock()
|
||||
entries := make([]entry, 0, len(s.cache))
|
||||
for _, e := range s.cache {
|
||||
entries = append(entries, e)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, e := range entries {
|
||||
s.refresh(ctx, e.Key, e.Host, e.Slug)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -17,53 +18,92 @@ import (
|
||||
)
|
||||
|
||||
type fakeSource struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
err error
|
||||
delay time.Duration
|
||||
pages map[string]agentapi.PageSnapshot
|
||||
}
|
||||
|
||||
func (f *fakeSource) Page(_ context.Context, host, slug string) (agentapi.PageSnapshot, error) {
|
||||
func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) {
|
||||
f.mu.Lock()
|
||||
f.calls++
|
||||
if f.err != nil {
|
||||
return agentapi.PageSnapshot{}, f.err
|
||||
err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false
|
||||
if _, exists := f.pages[host+"|"+slug]; exists {
|
||||
ok = true
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if delay > 0 {
|
||||
select {
|
||||
case <-time.After(delay):
|
||||
case <-ctx.Done():
|
||||
return p, ctx.Err()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return agentapi.PageSnapshot{}, err
|
||||
}
|
||||
p, ok := f.pages[host+"|"+slug]
|
||||
if !ok {
|
||||
return p, agentapi.ErrNotFound
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func newTest(t *testing.T) (*Server, *fakeSource, *gin.Engine, *time.Time) {
|
||||
func (f *fakeSource) set(fn func(*fakeSource)) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
fn(f)
|
||||
}
|
||||
|
||||
func (f *fakeSource) callCount() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.calls
|
||||
}
|
||||
|
||||
type harness struct {
|
||||
srv *Server
|
||||
src *fakeSource
|
||||
r *gin.Engine
|
||||
now *time.Time
|
||||
}
|
||||
|
||||
func newHarness(t *testing.T, src *fakeSource, dir string, now *time.Time) harness {
|
||||
t.Helper()
|
||||
cat, err := i18n.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := &fakeSource{pages: map[string]agentapi.PageSnapshot{
|
||||
"|acme": {Title: "Acme status", Status: agentapi.PageOperational},
|
||||
"status.acme.test|": {Title: "Acme on own domain", Status: agentapi.PageOutage},
|
||||
}}
|
||||
s := New(src, cat, slog.New(slog.DiscardHandler), []string{"status.example.test"})
|
||||
now := time.Now()
|
||||
s.now = func() time.Time { return now }
|
||||
s, err := New(src, cat, slog.New(slog.DiscardHandler), Options{Hosts: []string{"status.example.test"}, CacheDir: dir})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.now = func() time.Time { return *now }
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
s.Mount(r)
|
||||
return s, src, r, &now
|
||||
return harness{srv: s, src: src, r: r, now: now}
|
||||
}
|
||||
|
||||
func get(r http.Handler, host, path string) (int, string) {
|
||||
func newSource() *fakeSource {
|
||||
return &fakeSource{pages: map[string]agentapi.PageSnapshot{
|
||||
"|acme": {Title: "Acme status", Status: agentapi.PageOperational},
|
||||
"status.acme.test|": {Title: "Acme on own domain", Status: agentapi.PageOutage},
|
||||
}}
|
||||
}
|
||||
|
||||
func (h harness) get(host, path string) (int, string) {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.Host = host
|
||||
req.Header.Set("Accept-Language", "de")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
h.r.ServeHTTP(w, req)
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
|
||||
func TestRouting(t *testing.T) {
|
||||
_, _, r, _ := newTest(t)
|
||||
now := time.Now()
|
||||
h := newHarness(t, newSource(), t.TempDir(), &now)
|
||||
tests := []struct {
|
||||
host, path string
|
||||
want int
|
||||
@@ -78,27 +118,103 @@ func TestRouting(t *testing.T) {
|
||||
{"other.test", "/", 404, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
code, body := get(r, tt.host, tt.path)
|
||||
code, body := h.get(tt.host, tt.path)
|
||||
if code != tt.want || !strings.Contains(body, tt.contains) {
|
||||
t.Errorf("GET %s%s = %d (contains %q: %t), want %d", tt.host, tt.path, code, tt.contains, strings.Contains(body, tt.contains), tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheAndStaleFallback(t *testing.T) {
|
||||
_, src, r, now := newTest(t)
|
||||
get(r, "status.example.test", "/acme")
|
||||
get(r, "status.example.test", "/acme")
|
||||
if src.calls != 1 {
|
||||
t.Errorf("source calls within freshness window = %d, want 1", src.calls)
|
||||
// TestSurvivesAPIOutageAndRestart is the reason this package keeps state:
|
||||
// the page must stay up while the API is down, also across restarts.
|
||||
func TestSurvivesAPIOutageAndRestart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now()
|
||||
h := newHarness(t, newSource(), dir, &now)
|
||||
if code, _ := h.get("status.example.test", "/acme"); code != 200 {
|
||||
t.Fatalf("first GET = %d", code)
|
||||
}
|
||||
src.err = errors.New("api down")
|
||||
*now = now.Add(time.Minute)
|
||||
if code, body := get(r, "status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") {
|
||||
t.Errorf("GET with API down = %d, want stale page", code)
|
||||
|
||||
down := &fakeSource{err: errors.New("connection refused")}
|
||||
now = now.Add(time.Minute)
|
||||
restarted := newHarness(t, down, dir, &now)
|
||||
if code, body := restarted.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
|
||||
t.Errorf("GET after restart with API down = %d, want cached page without stale notice", code)
|
||||
}
|
||||
*now = now.Add(time.Hour)
|
||||
if code, _ := get(r, "status.example.test", "/acme"); code != 404 {
|
||||
t.Errorf("GET with API down long after = %d, want 404", code)
|
||||
if err := restarted.srv.Ready(context.Background(), func(context.Context) error { return errors.New("api down") }); err != nil {
|
||||
t.Errorf("Ready() with cached pages and API down = %v, want ready", err)
|
||||
}
|
||||
|
||||
now = now.Add(72 * time.Hour)
|
||||
code, body := restarted.get("status.example.test", "/acme")
|
||||
if code != 200 || !strings.Contains(body, "Live-Aktualisierung") {
|
||||
t.Errorf("GET three days into the outage = %d, want cached page with stale notice", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadyWithoutCacheNeedsAPI(t *testing.T) {
|
||||
now := time.Now()
|
||||
h := newHarness(t, newSource(), t.TempDir(), &now)
|
||||
if err := h.srv.Ready(context.Background(), func(context.Context) error { return errors.New("api down") }); err == nil {
|
||||
t.Error("Ready() with empty cache and API down = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedPagesDoNotWaitForAPI(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, t.TempDir(), &now)
|
||||
h.get("status.example.test", "/acme")
|
||||
|
||||
src.set(func(f *fakeSource) { f.delay = 5 * time.Second })
|
||||
now = now.Add(time.Minute)
|
||||
start := time.Now()
|
||||
if code, _ := h.get("status.example.test", "/acme"); code != 200 {
|
||||
t.Fatalf("GET = %d", code)
|
||||
}
|
||||
if took := time.Since(start); took > time.Second {
|
||||
t.Errorf("GET with a hanging API took %v, want an immediate cached answer", took)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackgroundRefresh(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, t.TempDir(), &now)
|
||||
h.get("status.example.test", "/acme")
|
||||
src.set(func(f *fakeSource) {
|
||||
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Renamed", Status: agentapi.PageOperational}
|
||||
})
|
||||
|
||||
now = now.Add(time.Minute)
|
||||
h.get("status.example.test", "/acme") // served from cache, triggers refresh
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
_, body := h.get("status.example.test", "/acme")
|
||||
if strings.Contains(body, "Renamed") {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("cached page was not refreshed in the background")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeletedPageDisappears(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, dir, &now)
|
||||
h.get("status.example.test", "/acme")
|
||||
src.set(func(f *fakeSource) { delete(f.pages, "|acme") })
|
||||
now = now.Add(time.Minute)
|
||||
h.srv.refresh(context.Background(), "slug:acme", "", "acme")
|
||||
if code, _ := h.get("status.example.test", "/acme"); code != 404 {
|
||||
t.Errorf("GET after the API reported the page gone = %d, want 404", code)
|
||||
}
|
||||
restarted := newHarness(t, &fakeSource{err: errors.New("down")}, dir, &now)
|
||||
if code, _ := restarted.get("status.example.test", "/acme"); code != 404 {
|
||||
t.Errorf("GET after restart = %d, want 404 (removed from disk too)", code)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/caddyserver/certmagic"
|
||||
@@ -13,15 +15,43 @@ import (
|
||||
)
|
||||
|
||||
// CertStorage keeps certmagic's certificates and locks in the API, so every
|
||||
// instance of a status page server shares them without a database.
|
||||
// instance of a status page server shares them without a database. Values
|
||||
// are mirrored to a local directory and read from there when the API is
|
||||
// unreachable, so HTTPS keeps working after a restart during an outage.
|
||||
type CertStorage struct {
|
||||
c *agentapi.Client
|
||||
c *agentapi.Client
|
||||
dir string
|
||||
}
|
||||
|
||||
var _ certmagic.Storage = CertStorage{}
|
||||
|
||||
// NewCertStorage returns storage backed by c.
|
||||
func NewCertStorage(c *agentapi.Client) CertStorage { return CertStorage{c: c} }
|
||||
// NewCertStorage returns storage backed by c, mirrored to dir unless dir is
|
||||
// empty.
|
||||
func NewCertStorage(c *agentapi.Client, dir string) CertStorage { return CertStorage{c: c, dir: dir} }
|
||||
|
||||
// local maps a storage key to a file below dir. Keys come from certmagic,
|
||||
// but are cleaned anyway so they cannot point outside dir.
|
||||
func (s CertStorage) local(key string) string {
|
||||
if s.dir == "" {
|
||||
return ""
|
||||
}
|
||||
clean := filepath.Clean("/" + key)
|
||||
return filepath.Join(s.dir, filepath.FromSlash(clean))
|
||||
}
|
||||
|
||||
func (s CertStorage) mirror(key string, value []byte) {
|
||||
if p := s.local(key); p != "" {
|
||||
if os.MkdirAll(filepath.Dir(p), 0o700) == nil {
|
||||
_ = os.WriteFile(p, value, 0o600)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unreachable reports errors that mean the API could not answer, as
|
||||
// opposed to answers such as "not found".
|
||||
func unreachable(err error) bool {
|
||||
return err != nil && !errors.Is(err, agentapi.ErrNotFound) && !errors.Is(err, agentapi.ErrLocked)
|
||||
}
|
||||
|
||||
func notExist(err error) error {
|
||||
if errors.Is(err, agentapi.ErrNotFound) {
|
||||
@@ -32,23 +62,43 @@ func notExist(err error) error {
|
||||
|
||||
// Store implements certmagic.Storage.
|
||||
func (s CertStorage) Store(ctx context.Context, key string, value []byte) error {
|
||||
return s.c.StoragePut(ctx, key, value)
|
||||
if err := s.c.StoragePut(ctx, key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mirror(key, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Load implements certmagic.Storage.
|
||||
func (s CertStorage) Load(ctx context.Context, key string) ([]byte, error) {
|
||||
v, err := s.c.StorageGet(ctx, key)
|
||||
return v, notExist(err)
|
||||
switch {
|
||||
case err == nil:
|
||||
s.mirror(key, v)
|
||||
return v, nil
|
||||
case unreachable(err) && s.local(key) != "":
|
||||
if local, lerr := os.ReadFile(s.local(key)); lerr == nil {
|
||||
return local, nil
|
||||
}
|
||||
}
|
||||
return nil, notExist(err)
|
||||
}
|
||||
|
||||
// Delete implements certmagic.Storage.
|
||||
func (s CertStorage) Delete(ctx context.Context, key string) error {
|
||||
if p := s.local(key); p != "" {
|
||||
_ = os.RemoveAll(p)
|
||||
}
|
||||
return notExist(s.c.StorageDelete(ctx, key))
|
||||
}
|
||||
|
||||
// Exists implements certmagic.Storage.
|
||||
func (s CertStorage) Exists(ctx context.Context, key string) bool {
|
||||
_, err := s.c.StorageStat(ctx, key)
|
||||
if unreachable(err) && s.local(key) != "" {
|
||||
_, lerr := os.Stat(s.local(key))
|
||||
return lerr == nil
|
||||
}
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@@ -64,6 +114,11 @@ func (s CertStorage) List(ctx context.Context, path string, recursive bool) ([]s
|
||||
// Stat implements certmagic.Storage.
|
||||
func (s CertStorage) Stat(ctx context.Context, key string) (certmagic.KeyInfo, error) {
|
||||
info, err := s.c.StorageStat(ctx, key)
|
||||
if unreachable(err) && s.local(key) != "" {
|
||||
if fi, lerr := os.Stat(s.local(key)); lerr == nil {
|
||||
return certmagic.KeyInfo{Key: key, Modified: fi.ModTime(), Size: fi.Size(), IsTerminal: !fi.IsDir()}, nil
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return certmagic.KeyInfo{}, notExist(err)
|
||||
}
|
||||
@@ -100,12 +155,16 @@ func (s CertStorage) Unlock(ctx context.Context, name string) error {
|
||||
// demand: only for the default hosts and for verified custom domains of
|
||||
// pages this server may serve. Anything else would let strangers make us
|
||||
// request certificates for arbitrary names.
|
||||
//
|
||||
// Names with a cached page are allowed without asking the API, so existing
|
||||
// certificates can be loaded after a restart while the API is down.
|
||||
func (s *Server) AllowCertificate(ctx context.Context, name string) error {
|
||||
if s.ownHosts[hostOnly(name)] {
|
||||
host := hostOnly(name)
|
||||
if s.ownHosts[host] {
|
||||
return nil
|
||||
}
|
||||
if _, err := s.src.Page(ctx, hostOnly(name), ""); err != nil {
|
||||
return fmt.Errorf("no status page for %s: %w", name, err)
|
||||
if _, ok := s.lookup(ctx, "host:"+host, host, ""); !ok {
|
||||
return fmt.Errorf("no status page for %s", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user