Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
673e93f4bb | ||
|
|
2054660625 | ||
|
|
4d03a86614 | ||
|
|
dc2e21f964 | ||
|
|
f3d0a4c844 | ||
|
|
fcf615dce7 | ||
|
|
4e9a198b2f | ||
|
|
c0239e15bb | ||
|
|
20874a5a87 | ||
|
|
135209fe79 |
No files matched your search
@@ -44,6 +44,11 @@ UPTIME_TEST_REDIS_URL=redis://localhost:6379/15
|
||||
# Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs).
|
||||
# UPTIME_TRUSTED_PROXIES=10.0.0.0/8
|
||||
|
||||
# How long a region with monitors may have no live checker before the
|
||||
# platform's admins (platform regions) or the organization's owners (own
|
||||
# regions) get an email; 0 switches it off.
|
||||
# UPTIME_REGION_ALERT_AFTER=5m
|
||||
|
||||
# Data retention (0 keeps forever). Raw results feed charts up to 24h, the
|
||||
# hourly aggregate 7d and 30d, the daily aggregate up to a year; resolved
|
||||
# incidents follow the daily aggregate.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
[](https://git.zb-server.de/ZB-Server/uptimesebi/actions?workflow=ci.yaml) · License: AGPL-3.0-only
|
||||
|
||||
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
|
||||
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. A region whose checkers are gone is left out rather than holding the monitor up, and its admins are told. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
|
||||
|
||||
It is built for teams and hosting providers: organizations with members, roles and SSO, run either as a shared cloud service or self-hosted.
|
||||
|
||||
@@ -159,7 +159,7 @@ Run as many API, checker and status page instances as you need; they share no lo
|
||||
| Hybrid | hosted | at the customer | at the customer |
|
||||
| Self-hosted | at the customer | at the customer | at the customer |
|
||||
|
||||
Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks.
|
||||
Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks. Status page servers fetch every page they serve every five minutes, so each one is cached before its first visit and keeps being served while the API is unreachable. Once one of an organization's own status page servers has connected, only its own servers serve its pages; the platform's no longer do.
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
@@ -92,6 +92,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
go srv.RunScheduler(ctx)
|
||||
go srv.RunNotifier(ctx)
|
||||
go srv.RunHousekeeping(ctx)
|
||||
go srv.RunRegionWatch(ctx)
|
||||
go srv.RunHeartbeats(ctx)
|
||||
|
||||
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
|
||||
|
||||
@@ -125,6 +125,11 @@ func (c *Client) WithHTTPClient(hc *http.Client) *Client {
|
||||
func (c *Client) Instance() uuid.UUID { return c.instance }
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
|
||||
return c.doWith(ctx, method, path, nil, in, out)
|
||||
}
|
||||
|
||||
// doWith is do with extra request headers.
|
||||
func (c *Client) doWith(ctx context.Context, method, path string, header http.Header, in, out any) error {
|
||||
var body io.Reader
|
||||
if in != nil {
|
||||
b, err := json.Marshal(in)
|
||||
@@ -142,6 +147,9 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error
|
||||
req.Header.Set(VersionHeader, fmt.Sprint(Version))
|
||||
req.Header.Set(InstanceHeader, c.instance.String())
|
||||
req.Header.Set(ReleaseHeader, c.release)
|
||||
for k, v := range header {
|
||||
req.Header[k] = v
|
||||
}
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -152,6 +160,8 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error
|
||||
return ErrUnauthorized
|
||||
case resp.StatusCode == http.StatusNotFound:
|
||||
return ErrNotFound
|
||||
case resp.StatusCode == http.StatusNotModified:
|
||||
return ErrNotModified
|
||||
case resp.StatusCode >= 300:
|
||||
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
|
||||
return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg))
|
||||
|
||||
@@ -2,6 +2,9 @@ package agentapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -348,19 +351,57 @@ func (s PageSnapshot) LegalDocByKind(kind string) (LegalDoc, bool) {
|
||||
return LegalDoc{}, false
|
||||
}
|
||||
|
||||
// PageRef names a page a status page server serves: by Slug on its own
|
||||
// hosts and, when Host is set, by that verified custom domain.
|
||||
type PageRef struct {
|
||||
Slug string `json:"slug"`
|
||||
Host string `json:"host,omitempty"`
|
||||
}
|
||||
|
||||
// Pages lists every page this status page server serves, so it can keep
|
||||
// them all cached before anyone visits.
|
||||
func (c *Client) Pages(ctx context.Context) ([]PageRef, error) {
|
||||
var out struct {
|
||||
Pages []PageRef `json:"pages"`
|
||||
}
|
||||
err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out)
|
||||
return out.Pages, err
|
||||
}
|
||||
|
||||
// ErrNotFound means no published page matches.
|
||||
var ErrNotFound = errors.New("agentapi: not found")
|
||||
|
||||
// ErrNotModified means the page still matches the checksum sent.
|
||||
var ErrNotModified = errors.New("agentapi: not modified")
|
||||
|
||||
// Checksum identifies the content of s, leaving out when it was generated.
|
||||
func (s PageSnapshot) Checksum() string {
|
||||
s.GeneratedAt = time.Time{}
|
||||
raw, _ := json.Marshal(s)
|
||||
sum := sha256.Sum256(raw)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Page fetches the published page for a custom domain host, or for slug if
|
||||
// host is empty.
|
||||
func (c *Client) Page(ctx context.Context, host, slug string) (PageSnapshot, error) {
|
||||
return c.PageIfChanged(ctx, host, slug, "")
|
||||
}
|
||||
|
||||
// PageIfChanged is Page, but answers ErrNotModified instead of sending the
|
||||
// page again when it still has the checksum given.
|
||||
func (c *Client) PageIfChanged(ctx context.Context, host, slug, checksum string) (PageSnapshot, error) {
|
||||
q := url.Values{}
|
||||
if host != "" {
|
||||
q.Set("host", host)
|
||||
} else {
|
||||
q.Set("slug", slug)
|
||||
}
|
||||
var h http.Header
|
||||
if checksum != "" {
|
||||
h = http.Header{"If-None-Match": {`"` + checksum + `"`}}
|
||||
}
|
||||
var p PageSnapshot
|
||||
err := c.do(ctx, http.MethodGet, "/pages?"+q.Encode(), nil, &p)
|
||||
err := c.doWith(ctx, http.MethodGet, "/pages?"+q.Encode(), h, nil, &p)
|
||||
return p, err
|
||||
}
|
||||
@@ -41,6 +41,7 @@ func (s *Server) mountAgentAPI(r gin.IRouter) {
|
||||
g.GET("/update", s.agentUpdate)
|
||||
sp := g.Group("", requireAgentKind("statuspage"))
|
||||
sp.GET("/pages", s.agentPage)
|
||||
sp.GET("/pages/index", s.agentPageIndex)
|
||||
sp.GET("/storage", s.storageGet)
|
||||
sp.PUT("/storage", s.storagePut)
|
||||
sp.DELETE("/storage", s.storageDelete)
|
||||
|
||||
@@ -48,6 +48,9 @@ func TestConsent(t *testing.T) {
|
||||
if !strings.Contains(versions, "privacy:") || !strings.Contains(versions, "terms:") || !strings.Contains(form, `name="consent" required`) {
|
||||
t.Fatalf("sign-up form lacks the consent box: versions %q", versions)
|
||||
}
|
||||
if !strings.Contains(form, "</a> and the <a") {
|
||||
t.Error("the consent text runs the documents' names into the words between them")
|
||||
}
|
||||
signup := func(consent bool, versions string) (int, map[string]any) {
|
||||
return e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{
|
||||
"email": uniq("n") + "@example.test", "password": password, "consent": consent, "consent_versions": versions,
|
||||
|
||||
+51
-7
@@ -21,6 +21,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
@@ -91,7 +92,14 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
v.Ranges = rangeOptions(c, data.rng, earliest, data.now)
|
||||
for _, m := range data.rows {
|
||||
v.Counts[m.Status]++
|
||||
if m.Unchecked {
|
||||
v.Unchecked++
|
||||
}
|
||||
}
|
||||
for id, since := range s.regionsWithoutChecker(c.Request.Context(), data.usedRegions) {
|
||||
v.DeadRegions = append(v.DeadRegions, web.DeadRegion{Name: data.regionOf[id].Name, Since: since.Local().Format("2006-01-02 15:04")})
|
||||
}
|
||||
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
||||
}
|
||||
@@ -214,6 +222,8 @@ type monitorData struct {
|
||||
firstRegion map[uuid.UUID]map[string]time.Time
|
||||
// statuses are the organization's own incident statuses.
|
||||
statuses customStatuses
|
||||
// usedRegions are the regions the enabled monitors are checked from.
|
||||
usedRegions []uuid.UUID
|
||||
}
|
||||
|
||||
// loadFirstData finds when monitors and their regions first reported. The
|
||||
@@ -366,6 +376,13 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
for _, a := range assigned {
|
||||
regionsOf[a.MonitorID] = append(regionsOf[a.MonitorID], a.RegionID)
|
||||
}
|
||||
for _, m := range monitors {
|
||||
if m.Enabled {
|
||||
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
d.usedRegions = slices.Compact(d.usedRegions)
|
||||
latestOf := map[uuid.UUID]map[string]store.LatestResultsRow{}
|
||||
for _, l := range latest {
|
||||
if latestOf[l.MonitorID] == nil {
|
||||
@@ -393,9 +410,18 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
}
|
||||
var latencies []int32
|
||||
failing, reported := 0, 0
|
||||
// A region that has not reported for longer than the evaluator
|
||||
// waits is unknown, whatever its last result said; passive monitors
|
||||
// judge their own lateness.
|
||||
staleBefore := now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
|
||||
for _, key := range keys {
|
||||
rs := web.RegionStatus{Name: d.regionNameString(key), Status: web.StatusUnknown, Detail: "–"}
|
||||
if l, ok := latestOf[m.ID][key]; ok {
|
||||
l, ok := latestOf[m.ID][key]
|
||||
if ok && !check.Passive(check.Type(m.Type)) && l.Time.Before(staleBefore) {
|
||||
rs.Detail = i18n.T(ctx, "monitors.no_data_since", "Time", l.Time.Format("15:04"))
|
||||
ok = false
|
||||
}
|
||||
if ok {
|
||||
reported++
|
||||
rs.Detail = l.Time.Format("15:04:05")
|
||||
if l.Ok {
|
||||
@@ -421,6 +447,8 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
row.Status = web.StatusDown
|
||||
case reported == 0:
|
||||
row.Status = web.StatusUnknown
|
||||
// Nobody is checking it, unless it is too new to have results.
|
||||
row.Unchecked = !check.Passive(check.Type(m.Type)) && m.CreatedAt.Before(staleBefore)
|
||||
case failing > 0:
|
||||
row.Status = web.StatusDegraded
|
||||
default:
|
||||
@@ -1016,19 +1044,31 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
|
||||
return web.ChannelsPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func (s *Server) pageURL(p store.StatusPage) string {
|
||||
// pageURL is where p is reachable, or empty when only the organization's
|
||||
// own status page servers serve it, at an address the platform does not
|
||||
// know.
|
||||
func (s *Server) pageURL(p store.StatusPage, ownServers bool) string {
|
||||
if p.CustomDomain != nil && p.DomainVerifiedAt != nil {
|
||||
return "https://" + *p.CustomDomain + "/"
|
||||
}
|
||||
if ownServers {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
|
||||
}
|
||||
|
||||
func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.StatusPage
|
||||
var (
|
||||
rows []store.StatusPage
|
||||
own bool
|
||||
)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListStatusPages(ctx)
|
||||
if rows, err = q.ListStatusPages(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -1041,7 +1081,7 @@ func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me
|
||||
}
|
||||
v.Pages = append(v.Pages, web.PageRow{
|
||||
ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published,
|
||||
URL: s.pageURL(r), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil,
|
||||
URL: s.pageURL(r, own), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil,
|
||||
})
|
||||
}
|
||||
return web.StatusPagesPage(page, me, v), nil
|
||||
@@ -1059,6 +1099,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
pageGroups []store.StatusPageGroup
|
||||
orgGroups []store.MonitorGroup
|
||||
monitors []store.Monitor
|
||||
own bool
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
@@ -1074,7 +1115,10 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
if orgGroups, err = q.ListGroups(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
monitors, err = q.ListMonitors(ctx)
|
||||
if monitors, err = q.ListMonitors(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -1089,7 +1133,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
Published: row.Published, ShowDetails: row.ShowComponentDetails,
|
||||
Suspended: row.SuspendedAt != nil, SuspendedReason: row.SuspendedReason,
|
||||
Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
|
||||
URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
|
||||
URL: s.pageURL(row, own), OwnServers: own, Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
|
||||
HasOrgGroups: len(orgGroups) > 0,
|
||||
}
|
||||
if v.DomainRecord != nil {
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// LookupTXT lets tests replace DNS lookups for domain verification.
|
||||
var LookupTXT = &lookupTXT
|
||||
|
||||
@@ -17,3 +24,9 @@ func DocumentedRoutes() []string {
|
||||
|
||||
// OpenAPI builds the OpenAPI document.
|
||||
func OpenAPI() map[string]any { return buildOpenAPI("https://uptime.example") }
|
||||
|
||||
// WatchRegionsOf runs the region watch for the regions given only, so
|
||||
// tests are not slowed down by the regions other tests left behind.
|
||||
func (s *Server) WatchRegionsOf(ctx context.Context, now time.Time, ids ...uuid.UUID) error {
|
||||
return s.watchRegions(ctx, now, ids)
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// A region whose checkers have all gone leaves its monitors unchecked:
|
||||
// they neither go down nor alert. The region watch tells those who run the
|
||||
// region, the platform's admins for platform regions and the owners for an
|
||||
// organization's own, once it has had no live checker for
|
||||
// UPTIME_REGION_ALERT_AFTER, and again when one is back. Every replica runs
|
||||
// it; Redis decides which one sends.
|
||||
|
||||
const (
|
||||
regionWatchEvery = 30 * time.Second
|
||||
// regionWatchTTL bounds the state of a region; one dead for longer is
|
||||
// announced again.
|
||||
regionWatchTTL = 30 * 24 * time.Hour
|
||||
)
|
||||
|
||||
func keyRegionDeadSince(id uuid.UUID) string { return "regionwatch:since:" + id.String() }
|
||||
func keyRegionAlerted(id uuid.UUID) string { return "regionwatch:alerted:" + id.String() }
|
||||
|
||||
// RunRegionWatch watches the regions until ctx ends.
|
||||
func (s *Server) RunRegionWatch(ctx context.Context) {
|
||||
if s.cfg.RegionAlertAfter <= 0 {
|
||||
return
|
||||
}
|
||||
tick := time.NewTicker(regionWatchEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.WatchRegions(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "watching regions failed", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WatchRegions checks every region with checkers and enabled monitors once.
|
||||
func (s *Server) WatchRegions(ctx context.Context, now time.Time) error {
|
||||
return s.watchRegions(ctx, now, nil)
|
||||
}
|
||||
|
||||
// watchRegions is WatchRegions limited to only, unless only is nil.
|
||||
func (s *Server) watchRegions(ctx context.Context, now time.Time, only []uuid.UUID) error {
|
||||
var regions []store.RegionsToWatchRow
|
||||
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
regions, err = q.RegionsToWatch(ctx)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range regions {
|
||||
if only != nil && !slices.Contains(only, r.ID) {
|
||||
continue
|
||||
}
|
||||
live, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if live > 0 {
|
||||
since, _ := s.rdb.GetDel(ctx, keyRegionDeadSince(r.ID)).Time()
|
||||
// Only the replica that clears the alert announces the return.
|
||||
if n, err := s.rdb.Del(ctx, keyRegionAlerted(r.ID)).Result(); err == nil && n > 0 {
|
||||
s.mailRegion(ctx, r, since, now, false)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := s.rdb.SetNX(ctx, keyRegionDeadSince(r.ID), now, regionWatchTTL).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
since, err := s.rdb.Get(ctx, keyRegionDeadSince(r.ID)).Time()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if now.Sub(since) < s.cfg.RegionAlertAfter {
|
||||
continue
|
||||
}
|
||||
if first, err := s.rdb.SetNX(ctx, keyRegionAlerted(r.ID), 1, regionWatchTTL).Result(); err == nil && first {
|
||||
if !s.mailRegion(ctx, r, since, now, true) {
|
||||
// Tried again on the next round.
|
||||
s.rdb.Del(ctx, keyRegionAlerted(r.ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// regionsWithoutChecker returns since when each of ids has had no live
|
||||
// checker, for those the watch found without one.
|
||||
func (s *Server) regionsWithoutChecker(ctx context.Context, ids []uuid.UUID) map[uuid.UUID]time.Time {
|
||||
out := map[uuid.UUID]time.Time{}
|
||||
for _, id := range ids {
|
||||
since, err := s.rdb.Get(ctx, keyRegionDeadSince(id)).Time()
|
||||
if err == nil {
|
||||
out[id] = since
|
||||
} else if !errors.Is(err, redis.Nil) {
|
||||
s.log.WarnContext(ctx, "reading region watch failed", "region", id, "error", err)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// mailRegion tells the admins or the owners that r has no live checker
|
||||
// since since, or, when down is false, that it has one again. It reports
|
||||
// false if the mail could not be sent and should be tried again.
|
||||
func (s *Server) mailRegion(ctx context.Context, r store.RegionsToWatchRow, since, now time.Time, down bool) bool {
|
||||
if s.smtp == nil {
|
||||
return true
|
||||
}
|
||||
var to []string
|
||||
link := "/admin"
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if r.OrgID == nil {
|
||||
to, err = q.AdminEmails(ctx)
|
||||
} else {
|
||||
link = "/settings/regions"
|
||||
to, err = q.OrgOwnerEmails(ctx, *r.OrgID)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil || len(to) == 0 {
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "finding whom to tell about a region failed", "region", r.ID, "error", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
l := s.catalog.Match("")
|
||||
data := map[string]any{
|
||||
"Region": r.Name, "Org": deref(r.OrgName), "Link": s.ticketLink(link),
|
||||
"Since": since.UTC().Format("2006-01-02 15:04 MST"),
|
||||
"Minutes": int(now.Sub(since).Minutes()),
|
||||
}
|
||||
kind := "email.region_back"
|
||||
if down {
|
||||
kind = "email.region_down"
|
||||
}
|
||||
if since.IsZero() {
|
||||
data["Since"], data["Minutes"] = "–", 0
|
||||
}
|
||||
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T(kind+".subject", data), Body: l.T(kind+".body", data)}); err != nil {
|
||||
s.log.WarnContext(ctx, "mail about a region failed", "region", r.ID, "error", err)
|
||||
return false
|
||||
}
|
||||
s.log.InfoContext(ctx, "told about a region", "region", r.ID, "down", down, "recipients", len(to))
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
|
||||
)
|
||||
|
||||
func TestUncheckedMonitorsAndRegionsWithoutChecker(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) {
|
||||
c.SMTPURL, c.SignupVerify, c.RegionAlertAfter = mail.URL(), "off", 3*time.Minute
|
||||
})
|
||||
ctx := context.Background()
|
||||
owner := e.browser(t)
|
||||
ownerEmail := "o@" + uniq("rw") + ".test"
|
||||
owner.signup(ownerEmail, uniq("rw-"))
|
||||
// An organization's own region: its owners hear about it.
|
||||
regionName := uniq("Office ")
|
||||
_, reg := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": regionName})
|
||||
region := reg["id"].(string)
|
||||
regionID := uuid.MustParse(region)
|
||||
st, agent := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": region})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create agent = %d %v", st, agent)
|
||||
}
|
||||
tok := agent["token"].(string)
|
||||
mailed := func(to, want string) {
|
||||
t.Helper()
|
||||
waitFor(t, 5*time.Second, "a mail saying "+want, func() bool {
|
||||
for _, m := range mail.Messages() {
|
||||
if strings.Contains(strings.Join(m.To, ","), to) && strings.Contains(m.Data, want) && strings.Contains(m.Data, regionName) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
// A monitor whose only region last reported ten minutes ago is not
|
||||
// up: nobody is checking it.
|
||||
_, mon := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://example.test", "interval_seconds": 60, "regions": []string{region}})
|
||||
id := mon["id"].(string)
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `UPDATE monitors SET created_at = now() - interval '1 hour' WHERE id = $1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, $4, true, 10)`,
|
||||
org, id, region, uuid.New())
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _, dash := owner.page("/")
|
||||
for _, want := range []string{"not being checked", "1 monitor is not being checked"} {
|
||||
if !strings.Contains(dash, want) {
|
||||
t.Errorf("dashboard lacks %q", want)
|
||||
}
|
||||
}
|
||||
if _, _, detail := owner.page("/monitors/" + id); !strings.Contains(detail, "no data since") || !strings.Contains(detail, "1 monitor is not being checked") {
|
||||
t.Error("the monitor page does not say the region has no recent data")
|
||||
}
|
||||
|
||||
// On a status page it shows as unknown, not as operational.
|
||||
slug := uniq("rw-")
|
||||
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": id}}})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
|
||||
snap, err := e.statuspageClient(t, &org).Page(ctx, "", slug)
|
||||
if err != nil || len(snap.Sections) != 1 || snap.Sections[0].Components[0].Status != agentapi.PageUnknown {
|
||||
t.Errorf("status page = %+v, %v; want the component unknown", snap.Sections, err)
|
||||
}
|
||||
|
||||
// The region has a checker but no live instance: the watch notes it at
|
||||
// once and tells the owners once it has lasted.
|
||||
now := time.Now()
|
||||
if err := e.api.WatchRegionsOf(ctx, now, regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, dash := owner.page("/"); !strings.Contains(dash, "Region "+regionName+" has had no active checker since") {
|
||||
t.Error("the dashboard does not name the region without a checker")
|
||||
}
|
||||
if err := e.api.WatchRegionsOf(ctx, now.Add(5*time.Minute), regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mailed(ownerEmail, "has no active checker")
|
||||
sent := len(mail.Messages())
|
||||
if err := e.api.WatchRegionsOf(ctx, now.Add(10*time.Minute), regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if n := countMails(mail.Messages()[sent:], regionName); n != 0 {
|
||||
t.Errorf("the region was announced %d more times", n)
|
||||
}
|
||||
|
||||
// A checker coming back is announced too.
|
||||
e.startChecker(t, tok)
|
||||
waitFor(t, 15*time.Second, "the checker to count as live", func() bool {
|
||||
_ = e.api.WatchRegionsOf(ctx, time.Now(), regionID)
|
||||
for _, m := range mail.Messages() {
|
||||
if strings.Contains(m.Data, "is checking again") && strings.Contains(m.Data, regionName) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
if _, _, dash := owner.page("/"); strings.Contains(dash, "Region "+regionName+" has had no active checker") {
|
||||
t.Error("the dashboard still names the region")
|
||||
}
|
||||
}
|
||||
|
||||
func countMails(ms []notifytest.Message, about string) int {
|
||||
n := 0
|
||||
for _, m := range ms {
|
||||
if strings.Contains(m.Data, about) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -22,6 +22,8 @@ import (
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
@@ -127,7 +129,18 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
failing := map[uuid.UUID]int{}
|
||||
reported := map[uuid.UUID]int{}
|
||||
latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{}
|
||||
// A region that has not reported for longer than the evaluator waits
|
||||
// is unknown, whatever its last result said.
|
||||
staleBefore := map[uuid.UUID]time.Time{}
|
||||
for _, m := range listed {
|
||||
if !check.Passive(check.Type(m.MonitorType)) {
|
||||
staleBefore[m.MonitorID] = now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
|
||||
}
|
||||
}
|
||||
for _, l := range latest {
|
||||
if cut, ok := staleBefore[l.MonitorID]; ok && l.Time.Before(cut) {
|
||||
continue
|
||||
}
|
||||
reported[l.MonitorID]++
|
||||
if !l.Ok {
|
||||
failing[l.MonitorID]++
|
||||
@@ -346,14 +359,22 @@ func (s *Server) agentPage(c *gin.Context) {
|
||||
fail(c, http.StatusBadRequest, "invalid_input")
|
||||
return
|
||||
}
|
||||
var page store.StatusPage
|
||||
var (
|
||||
page store.StatusPage
|
||||
own bool
|
||||
)
|
||||
a := agentOf(c)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug})
|
||||
if page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug}); err != nil || a.OrgID != nil {
|
||||
return err
|
||||
}
|
||||
own, err = q.OrgServesOwnPages(ctx, &page.OrgID)
|
||||
return err
|
||||
})
|
||||
a := agentOf(c)
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && a.OrgID != nil && *a.OrgID != page.OrgID) {
|
||||
// The platform's servers leave the pages of organizations that serve
|
||||
// them on their own servers to those.
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && (own || a.OrgID != nil && *a.OrgID != page.OrgID)) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
@@ -366,9 +387,37 @@ func (s *Server) agentPage(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
// The server sends the checksum of its copy; an unchanged page is not
|
||||
// sent again.
|
||||
etag := `"` + snap.Checksum() + `"`
|
||||
c.Header("ETag", etag)
|
||||
if c.GetHeader("If-None-Match") == etag {
|
||||
c.Status(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, snap)
|
||||
}
|
||||
|
||||
// agentPageIndex lists the pages the status page server serves.
|
||||
func (s *Server) agentPageIndex(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ServablePagesRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ServablePages(ctx, agentOf(c).OrgID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]agentapi.PageRef, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"pages": out})
|
||||
}
|
||||
|
||||
type statusPageRequest struct {
|
||||
Slug string `json:"slug" binding:"required,max=63"`
|
||||
Title string `json:"title" binding:"required,max=200"`
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -95,6 +96,12 @@ func TestStatusPages(t *testing.T) {
|
||||
snap.Sections[1].Components[0].Name != "Public API" {
|
||||
t.Errorf("snapshot = %+v, want degraded page with the Public API in outage", snap)
|
||||
}
|
||||
if _, err := platform.PageIfChanged(context.Background(), "", slug, snap.Checksum()); !errors.Is(err, agentapi.ErrNotModified) {
|
||||
t.Errorf("PageIfChanged(current checksum) error = %v, want not modified", err)
|
||||
}
|
||||
if again, err := platform.PageIfChanged(context.Background(), "", slug, "stale"); err != nil || again.Title != "Acme Status" {
|
||||
t.Errorf("PageIfChanged(stale checksum) = %v, %v", again.Title, err)
|
||||
}
|
||||
raw, _ := json.Marshal(snap)
|
||||
for _, secret := range []string{up.URL, down.URL, "unexpected status"} {
|
||||
if strings.Contains(string(raw), secret) {
|
||||
@@ -192,6 +199,37 @@ func TestStatusPages(t *testing.T) {
|
||||
st, body = editor.do("PUT", "/api/v1/org/statuspages/"+second, map[string]any{"slug": "x-second", "title": "x"})
|
||||
expect(t, "edit page out of scope", st, body, http.StatusNotFound, "not_found")
|
||||
})
|
||||
|
||||
t.Run("own servers replace the platform's", func(t *testing.T) {
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
own := e.statuspageClient(t, &org)
|
||||
lists := func(c *agentapi.Client) bool {
|
||||
t.Helper()
|
||||
refs, err := c.Pages(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return slices.ContainsFunc(refs, func(r agentapi.PageRef) bool { return r.Slug == slug && r.Host != "" })
|
||||
}
|
||||
if _, err := platform.Page(context.Background(), "", slug); err != nil || !lists(platform) {
|
||||
t.Fatalf("platform server before the own one connected: %v", err)
|
||||
}
|
||||
if _, err := own.Hello(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := platform.Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
|
||||
t.Errorf("platform server still gets the page: %v", err)
|
||||
}
|
||||
if snap, err := own.Page(context.Background(), "", slug); err != nil || snap.Title != "Acme Status" {
|
||||
t.Errorf("own server Page() = %v, %v", snap.Title, err)
|
||||
}
|
||||
if lists(platform) || !lists(own) {
|
||||
t.Error("the page lists do not follow who serves the page")
|
||||
}
|
||||
if _, _, html := owner.page("/statuspages/" + pageID); !strings.Contains(html, "own status page servers serve its pages") {
|
||||
t.Error("the editor does not say who serves the pages")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func editorEmail(b *browser) string {
|
||||
|
||||
@@ -101,7 +101,10 @@ type API struct {
|
||||
// AgentImage is the image name agents are installed and updated from;
|
||||
// "-checker" or "-statuspage" is appended. Change it for a mirror.
|
||||
AgentImage string `env:"UPTIME_AGENT_IMAGE" envDefault:"git.zb-server.de/zb-server/uptimesebi"`
|
||||
Retention Retention
|
||||
// RegionAlertAfter is how long a region with monitors may have no live
|
||||
// checker before its admins or owners are told; 0 disables it.
|
||||
RegionAlertAfter time.Duration `env:"UPTIME_REGION_ALERT_AFTER" envDefault:"5m"`
|
||||
Retention Retention
|
||||
}
|
||||
|
||||
// Retention sets how long data is kept. Zero keeps it forever.
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
// Package evaluate turns per-region check results into a monitor state.
|
||||
//
|
||||
// A monitor goes down only when every region it is assigned to has failed
|
||||
// the configured number of times in a row and reported recently. A region
|
||||
// without recent results counts as unknown and keeps the monitor up: one
|
||||
// checker losing its network must not page anyone. Any successful region
|
||||
// A monitor goes down when every region it is assigned to that reported
|
||||
// recently has failed the configured number of times in a row: one region
|
||||
// failing while another succeeds is the checker's problem, not the
|
||||
// target's. A region without recent results counts as unknown and is left
|
||||
// out, so a dead region neither keeps a monitor up nor takes it down; with
|
||||
// every region unknown nothing is judged at all. Any successful region
|
||||
// brings the monitor back up.
|
||||
//
|
||||
// The state lives in Redis and each observation is applied by one Lua
|
||||
@@ -53,9 +55,9 @@ type Observation struct {
|
||||
Regions []string
|
||||
}
|
||||
|
||||
// staleAfter is how old a region's last result may be before the region
|
||||
// StaleAfter is how old a region's last result may be before the region
|
||||
// counts as unknown.
|
||||
func staleAfter(interval time.Duration) time.Duration {
|
||||
func StaleAfter(interval time.Duration) time.Duration {
|
||||
return max(3*interval, 2*time.Minute)
|
||||
}
|
||||
|
||||
@@ -86,12 +88,17 @@ if state == 'down' then
|
||||
end
|
||||
return 'none'
|
||||
end
|
||||
local reporting = 0
|
||||
for i = 7, #ARGV do
|
||||
local r = ARGV[i]
|
||||
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
|
||||
local seen = tonumber(redis.call('HGET', key, 'a:' .. r) or '0')
|
||||
if fails < need or seen < stale then return 'none' end
|
||||
if seen >= stale then
|
||||
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
|
||||
if fails < need then return 'none' end
|
||||
reporting = reporting + 1
|
||||
end
|
||||
end
|
||||
if reporting == 0 then return 'none' end
|
||||
redis.call('HSET', key, 'state', 'down')
|
||||
return 'down'
|
||||
`)
|
||||
@@ -113,7 +120,7 @@ func (e *Evaluator) Observe(ctx context.Context, o Observation) (Transition, err
|
||||
if o.OK {
|
||||
ok = "1"
|
||||
}
|
||||
stale := e.now().Add(-staleAfter(o.Interval)).UnixMilli()
|
||||
stale := e.now().Add(-StaleAfter(o.Interval)).UnixMilli()
|
||||
args := []any{o.Region, ok, o.At.UnixMilli(), max(o.Confirmations, 1), stale, int(stateTTL.Seconds())}
|
||||
for _, r := range o.Regions {
|
||||
args = append(args, r)
|
||||
|
||||
@@ -55,9 +55,9 @@ func play(t *testing.T, e *Evaluator, now *time.Time, regions []string, confirma
|
||||
func TestDownOnlyWhenAllRegionsFail(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
play(t, e, now, []string{"eu", "us"}, 2, []step{
|
||||
{"eu", false, None},
|
||||
{"eu", false, None}, // eu confirmed down, us has not reported
|
||||
{"us", true, None},
|
||||
{"eu", false, None},
|
||||
{"eu", false, None}, // eu confirmed down, us still fine
|
||||
{"us", false, None},
|
||||
{"eu", false, None},
|
||||
{"us", false, Down}, // both regions failed twice in a row
|
||||
@@ -79,7 +79,7 @@ func TestSingleRegionWithConfirmations(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestSilentRegionBlocksAlert(t *testing.T) {
|
||||
func TestSilentRegionIsLeftOut(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
id := uuid.New()
|
||||
obs := func(region string, ok bool) Transition {
|
||||
@@ -92,12 +92,27 @@ func TestSilentRegionBlocksAlert(t *testing.T) {
|
||||
}
|
||||
return got
|
||||
}
|
||||
obs("us", false)
|
||||
// us stops reporting for longer than three intervals.
|
||||
obs("us", true)
|
||||
// us stops reporting for longer than three intervals: the failures of
|
||||
// eu alone decide.
|
||||
*now = now.Add(5 * time.Minute)
|
||||
if got := obs("eu", false); got != None {
|
||||
t.Errorf("eu failure with us silent = %v, want none", got)
|
||||
if got := obs("eu", false); got != Down {
|
||||
t.Errorf("eu failure with us silent = %v, want down", got)
|
||||
}
|
||||
// us reporting a success again brings the monitor back up.
|
||||
*now = now.Add(time.Second)
|
||||
if got := obs("us", true); got != Up {
|
||||
t.Errorf("us success after the outage = %v, want up", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportingRegionStillVetoes(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
play(t, e, now, []string{"eu", "us"}, 1, []step{
|
||||
{"us", true, None},
|
||||
{"eu", false, None}, // us reported recently and was fine
|
||||
{"eu", false, None},
|
||||
})
|
||||
}
|
||||
|
||||
func TestOutOfOrderResultIgnored(t *testing.T) {
|
||||
|
||||
@@ -516,6 +516,10 @@
|
||||
"console.totp_missing_action": "Jetzt einrichten",
|
||||
"email.opened.body": "{{.Monitor}} ({{.Target}}) ist in allen Regionen nicht erreichbar seit {{.Since}}.\n\nLetzte Fehler:\n{{.Cause}}\n\nDu erhältst diese Nachricht, weil ein Benachrichtigungskanal deiner Organisation diese Adresse nutzt.",
|
||||
"email.opened.subject": "[DOWN] {{.Monitor}}",
|
||||
"email.region_back.body": "Region {{.Region}} hat wieder einen aktiven Checker; seit {{.Since}} hatte sie keinen. Überfällige Prüfungen laufen sofort.\n\n{{.Link}}",
|
||||
"email.region_back.subject": "Region {{.Region}} prüft wieder",
|
||||
"email.region_down.body": "Region {{.Region}} hat seit {{.Minutes}} Minuten keinen aktiven Checker, seit {{.Since}}.\n\nMonitore, die nur von dort geprüft werden, werden gerade nicht geprüft: Sie fallen weder aus noch alarmieren sie. Monitore mit weiteren Regionen werden nur nach diesen beurteilt, bis diese Region wieder meldet.\n\nStarte einen Checker der Region oder sieh dir seine Logs an:\n{{.Link}}",
|
||||
"email.region_down.subject": "Region {{.Region}} hat keinen aktiven Checker",
|
||||
"email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.",
|
||||
"email.resolved.subject": "[UP] {{.Monitor}}",
|
||||
"email.support_admin.body": "Hallo,\n\nein Support-Ticket wartet auf eine Antwort:\n\n{{.Subject}}\n\n{{.Link}}",
|
||||
@@ -1045,6 +1049,7 @@
|
||||
"monitors.db_tls_verify": "TLS mit geprüftem Zertifikat",
|
||||
"monitors.db_user": "Benutzer",
|
||||
"monitors.db_user_redis": "Benutzer (ACL, optional)",
|
||||
"monitors.dead_region": "Region {{.Region}} hat seit {{.Since}} keinen aktiven Checker.",
|
||||
"monitors.delete": "Monitor löschen",
|
||||
"monitors.delete_confirm": "Diesen Monitor samt Verlauf löschen?",
|
||||
"monitors.dns_expect": "Erwartete Antwort (optional)",
|
||||
@@ -1081,6 +1086,7 @@
|
||||
"monitors.minecraft_hint": "Ziel ist host:port (Java meist 25565, Bedrock 19132). Pingt den Server wie die Serverliste im Spiel.",
|
||||
"monitors.minecraft_java": "Java Edition",
|
||||
"monitors.new": "Neuer Monitor",
|
||||
"monitors.no_data_since": "keine Daten seit {{.Time}}",
|
||||
"monitors.no_match": "Kein Monitor gefunden.",
|
||||
"monitors.no_results": "Noch keine Ergebnisse.",
|
||||
"monitors.op_absent": "fehlt",
|
||||
@@ -1167,6 +1173,11 @@
|
||||
"monitors.type_steam": "Steam-Spieleserver",
|
||||
"monitors.type_tcp": "TCP-Port",
|
||||
"monitors.type_tls": "TLS-Zertifikat",
|
||||
"monitors.unchecked": "wird nicht geprüft",
|
||||
"monitors.unchecked_banner": {
|
||||
"one": "1 Monitor wird gerade nicht geprüft: Keine Region hat für ihn in letzter Zeit gemeldet. Er fällt weder aus noch alarmiert er, bis wieder ein Checker meldet.",
|
||||
"other": "{{.Count}} Monitore werden gerade nicht geprüft: Keine Region hat für sie in letzter Zeit gemeldet. Sie fallen weder aus noch alarmieren sie, bis wieder ein Checker meldet."
|
||||
},
|
||||
"monitors.ungrouped": "Ohne Gruppe",
|
||||
"monitors.uptime_chart": "Uptime pro Zeitraum",
|
||||
"monitors.verify_tls": "TLS-Zertifikat prüfen",
|
||||
@@ -1256,6 +1267,8 @@
|
||||
"pages.logo": "Logo-URL (https)",
|
||||
"pages.no_group": "Ohne Gruppe",
|
||||
"pages.open": "Öffnen",
|
||||
"pages.own_servers": "Die Statusseiten dieser Organisation liefern nur ihre eigenen Statusseiten-Server aus, nicht die der Plattform. Ruf sie über die Adresse deiner Server auf oder verbinde eine eigene Domain, die auf sie zeigt.",
|
||||
"pages.own_servers_short": "eigene Server",
|
||||
"pages.page_title": "Titel",
|
||||
"pages.published": "Veröffentlicht",
|
||||
"pages.section": "Abschnitt",
|
||||
|
||||
@@ -516,6 +516,10 @@
|
||||
"console.totp_missing_action": "Set up now",
|
||||
"email.opened.body": "{{.Monitor}} ({{.Target}}) is down in all of its regions since {{.Since}}.\n\nLast errors:\n{{.Cause}}\n\nYou receive this because a notification channel of your organization is set up for this address.",
|
||||
"email.opened.subject": "[DOWN] {{.Monitor}}",
|
||||
"email.region_back.body": "Region {{.Region}} has an active checker again; it had none since {{.Since}}. Overdue checks run right away.\n\n{{.Link}}",
|
||||
"email.region_back.subject": "Region {{.Region}} is checking again",
|
||||
"email.region_down.body": "Region {{.Region}} has had no active checker for {{.Minutes}} minutes, since {{.Since}}.\n\nMonitors checked only from there are not being checked right now: they neither go down nor alert. Monitors with other regions as well are judged by those alone until this one reports again.\n\nStart a checker of the region or look at its logs:\n{{.Link}}",
|
||||
"email.region_down.subject": "Region {{.Region}} has no active checker",
|
||||
"email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.",
|
||||
"email.resolved.subject": "[UP] {{.Monitor}}",
|
||||
"email.support_admin.body": "Hello,\n\na support ticket waits for an answer:\n\n{{.Subject}}\n\n{{.Link}}",
|
||||
@@ -1045,6 +1049,7 @@
|
||||
"monitors.db_tls_verify": "TLS with verified certificate",
|
||||
"monitors.db_user": "User",
|
||||
"monitors.db_user_redis": "User (ACL, optional)",
|
||||
"monitors.dead_region": "Region {{.Region}} has had no active checker since {{.Since}}.",
|
||||
"monitors.delete": "Delete monitor",
|
||||
"monitors.delete_confirm": "Delete this monitor and its history?",
|
||||
"monitors.dns_expect": "Expected answer (optional)",
|
||||
@@ -1081,6 +1086,7 @@
|
||||
"monitors.minecraft_hint": "Target is host:port (Java usually 25565, Bedrock 19132). Pings the server like the in-game server list.",
|
||||
"monitors.minecraft_java": "Java Edition",
|
||||
"monitors.new": "New monitor",
|
||||
"monitors.no_data_since": "no data since {{.Time}}",
|
||||
"monitors.no_match": "No monitor matches.",
|
||||
"monitors.no_results": "No results yet.",
|
||||
"monitors.op_absent": "is absent",
|
||||
@@ -1167,6 +1173,11 @@
|
||||
"monitors.type_steam": "Steam game server",
|
||||
"monitors.type_tcp": "TCP port",
|
||||
"monitors.type_tls": "TLS certificate",
|
||||
"monitors.unchecked": "not being checked",
|
||||
"monitors.unchecked_banner": {
|
||||
"one": "1 monitor is not being checked: no region has reported for it recently. It neither goes down nor alerts until a checker reports again.",
|
||||
"other": "{{.Count}} monitors are not being checked: no region has reported for them recently. They neither go down nor alert until a checker reports again."
|
||||
},
|
||||
"monitors.ungrouped": "Without group",
|
||||
"monitors.uptime_chart": "Uptime per period",
|
||||
"monitors.verify_tls": "Verify TLS certificate",
|
||||
@@ -1256,6 +1267,8 @@
|
||||
"pages.logo": "Logo URL (https)",
|
||||
"pages.no_group": "No group",
|
||||
"pages.open": "Open",
|
||||
"pages.own_servers": "Your organization's own status page servers serve its pages; the platform's do not. Open them at the address of your servers or connect a custom domain pointing at them.",
|
||||
"pages.own_servers_short": "own servers",
|
||||
"pages.page_title": "Title",
|
||||
"pages.published": "Published",
|
||||
"pages.section": "Section",
|
||||
|
||||
@@ -35,14 +35,24 @@ import (
|
||||
const (
|
||||
// freshFor is how long a snapshot is used without asking the API.
|
||||
freshFor = 30 * time.Second
|
||||
// staleNoticeAfter is when visitors are told the state may be outdated.
|
||||
staleNoticeAfter = 5 * time.Minute
|
||||
refreshInterval = 30 * time.Second
|
||||
// refreshInterval is how often pages visited within recentFor are
|
||||
// refreshed.
|
||||
refreshInterval = 30 * time.Second
|
||||
recentFor = 10 * time.Minute
|
||||
// syncInterval is how often every page the API lists is fetched, so
|
||||
// each one is cached before its first visit.
|
||||
syncInterval = 5 * time.Minute
|
||||
// staleNoticeAfter is when visitors are told the state may be outdated;
|
||||
// a page nobody visited is up to syncInterval old.
|
||||
staleNoticeAfter = 2 * syncInterval
|
||||
)
|
||||
|
||||
// Source fetches snapshots; *agentapi.Client implements it.
|
||||
type Source interface {
|
||||
Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error)
|
||||
// PageIfChanged answers agentapi.ErrNotModified when the page still
|
||||
// has checksum.
|
||||
PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error)
|
||||
Pages(ctx context.Context) ([]agentapi.PageRef, error)
|
||||
}
|
||||
|
||||
// Server renders pages for one status page agent.
|
||||
@@ -60,6 +70,8 @@ type Server struct {
|
||||
mu sync.Mutex
|
||||
cache map[string]entry
|
||||
refreshing map[string]bool
|
||||
// visited holds when each page was last visited.
|
||||
visited map[string]time.Time
|
||||
// background tracks refreshes started by visits.
|
||||
background sync.WaitGroup
|
||||
}
|
||||
@@ -71,6 +83,9 @@ type entry struct {
|
||||
Slug string `json:"slug,omitempty"`
|
||||
Snap agentapi.PageSnapshot `json:"snapshot"`
|
||||
Fetched time.Time `json:"fetched"`
|
||||
// Checksum is the snapshot's, sent so the API can answer that nothing
|
||||
// changed instead of sending it again.
|
||||
Checksum string `json:"checksum,omitempty"`
|
||||
}
|
||||
|
||||
// Options configure a Server.
|
||||
@@ -88,7 +103,7 @@ type Options struct {
|
||||
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{},
|
||||
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, visited: map[string]time.Time{},
|
||||
}
|
||||
for _, h := range o.Hosts {
|
||||
s.ownHosts[strings.ToLower(h)] = true
|
||||
@@ -308,6 +323,7 @@ func (s *Server) localizeRequest(c *gin.Context) {
|
||||
func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) {
|
||||
s.mu.Lock()
|
||||
e, cached := s.cache[key]
|
||||
s.visited[key] = s.now()
|
||||
s.mu.Unlock()
|
||||
if cached {
|
||||
if s.now().Sub(e.Fetched) >= freshFor {
|
||||
@@ -319,8 +335,20 @@ func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, boo
|
||||
}
|
||||
|
||||
func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) {
|
||||
snap, err := s.src.Page(ctx, host, slug)
|
||||
s.mu.Lock()
|
||||
old, known := s.cache[key]
|
||||
s.mu.Unlock()
|
||||
snap, err := s.src.PageIfChanged(ctx, host, slug, old.Checksum)
|
||||
switch {
|
||||
case errors.Is(err, agentapi.ErrNotModified) && known:
|
||||
// Unchanged: the copy is current as of now.
|
||||
old.Fetched = s.now()
|
||||
old.Snap.GeneratedAt = old.Fetched
|
||||
s.mu.Lock()
|
||||
s.cache[key] = old
|
||||
s.mu.Unlock()
|
||||
s.persist(old)
|
||||
return old, true
|
||||
case errors.Is(err, agentapi.ErrNotFound):
|
||||
s.forget(key)
|
||||
return entry{}, false
|
||||
@@ -331,7 +359,7 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
|
||||
s.mu.Unlock()
|
||||
return e, ok
|
||||
}
|
||||
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now()}
|
||||
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now(), Checksum: snap.Checksum()}
|
||||
s.mu.Lock()
|
||||
s.cache[key] = e
|
||||
s.mu.Unlock()
|
||||
@@ -361,25 +389,64 @@ func (s *Server) refresh(ctx context.Context, key, host, slug string) {
|
||||
// Wait returns once the background refreshes started by visits are done.
|
||||
func (s *Server) Wait() { s.background.Wait() }
|
||||
|
||||
// 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.
|
||||
// Run keeps pages fresh until ctx ends: every page the API lists every
|
||||
// syncInterval, so all are cached before their first visit and survive an
|
||||
// outage of the API, and recently visited ones every refreshInterval.
|
||||
func (s *Server) Run(ctx context.Context) {
|
||||
tick := time.NewTicker(refreshInterval)
|
||||
defer tick.Stop()
|
||||
refresh := time.NewTicker(refreshInterval)
|
||||
defer refresh.Stop()
|
||||
listAll := time.NewTicker(syncInterval)
|
||||
defer listAll.Stop()
|
||||
s.Sync(ctx)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
case <-listAll.C:
|
||||
s.Sync(ctx)
|
||||
case <-refresh.C:
|
||||
s.mu.Lock()
|
||||
entries := make([]entry, 0, len(s.cache))
|
||||
for _, e := range s.cache {
|
||||
entries = append(entries, e)
|
||||
var recent []entry
|
||||
for key, e := range s.cache {
|
||||
if s.now().Sub(s.visited[key]) < recentFor {
|
||||
recent = append(recent, e)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, e := range entries {
|
||||
for _, e := range recent {
|
||||
s.refresh(ctx, e.Key, e.Host, e.Slug)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sync fetches every page the API lists and every cached one, which drops
|
||||
// those the API no longer serves. While the API is unreachable the cache
|
||||
// stays as it is.
|
||||
func (s *Server) Sync(ctx context.Context) {
|
||||
ctx, cancel := context.WithTimeout(ctx, syncInterval)
|
||||
defer cancel()
|
||||
refs, err := s.src.Pages(ctx)
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "listing status pages failed", "error", err)
|
||||
return
|
||||
}
|
||||
todo := map[string]entry{}
|
||||
s.mu.Lock()
|
||||
for key, e := range s.cache {
|
||||
todo[key] = e
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, r := range refs {
|
||||
todo["slug:"+r.Slug] = entry{Key: "slug:" + r.Slug, Slug: r.Slug}
|
||||
if r.Host != "" {
|
||||
todo["host:"+r.Host] = entry{Key: "host:" + r.Host, Host: r.Host}
|
||||
}
|
||||
}
|
||||
for _, e := range todo {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
s.refresh(ctx, e.Key, e.Host, e.Slug)
|
||||
}
|
||||
}
|
||||
@@ -20,12 +20,27 @@ import (
|
||||
type fakeSource struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
err error
|
||||
delay time.Duration
|
||||
pages map[string]agentapi.PageSnapshot
|
||||
// unchanged counts the answers that the page had not changed.
|
||||
unchanged int
|
||||
err error
|
||||
delay time.Duration
|
||||
pages map[string]agentapi.PageSnapshot
|
||||
}
|
||||
|
||||
func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) {
|
||||
// PageIfChanged counts calls and answers like the API, sending pages
|
||||
// only when their checksum changed.
|
||||
func (f *fakeSource) PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error) {
|
||||
p, err := f.page(ctx, host, slug)
|
||||
if err == nil && checksum != "" && p.Checksum() == checksum {
|
||||
f.mu.Lock()
|
||||
f.unchanged++
|
||||
f.mu.Unlock()
|
||||
return agentapi.PageSnapshot{}, agentapi.ErrNotModified
|
||||
}
|
||||
return p, err
|
||||
}
|
||||
|
||||
func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) {
|
||||
f.mu.Lock()
|
||||
f.calls++
|
||||
err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false
|
||||
@@ -49,6 +64,21 @@ func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.Page
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Pages lists the fake's pages by their keys: "host|" or "|slug".
|
||||
func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
var out []agentapi.PageRef
|
||||
for k := range f.pages {
|
||||
host, slug, _ := strings.Cut(k, "|")
|
||||
out = append(out, agentapi.PageRef{Host: host, Slug: slug})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) set(fn func(*fakeSource)) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
@@ -464,3 +494,64 @@ func TestNestedGroupsAndComponentDetails(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSyncCachesPagesBeforeTheirFirstVisit(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, dir, &now)
|
||||
h.srv.Sync(context.Background())
|
||||
|
||||
// Nobody visited them, yet both survive an outage and a restart.
|
||||
now = now.Add(syncInterval)
|
||||
restarted := newHarness(t, &fakeSource{err: errors.New("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 of a synced page with the API down = %d, want it without stale notice", code)
|
||||
}
|
||||
if code, body := restarted.get("status.acme.test", "/"); code != 200 || !strings.Contains(body, "Acme on own domain") {
|
||||
t.Errorf("GET of a synced custom domain with the API down = %d", code)
|
||||
}
|
||||
restarted.srv.Sync(context.Background())
|
||||
if code, _ := restarted.get("status.example.test", "/acme"); code != 200 {
|
||||
t.Errorf("a failed sync dropped the cache: %d", code)
|
||||
}
|
||||
|
||||
// A page the API no longer lists is dropped by the next sync.
|
||||
src.set(func(f *fakeSource) { delete(f.pages, "|acme") })
|
||||
h.srv.Sync(context.Background())
|
||||
if code, _ := h.get("status.example.test", "/acme"); code != 404 {
|
||||
t.Errorf("GET after the page left the list = %d, want 404", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshSkipsUnchangedPages(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, dir, &now)
|
||||
h.srv.Sync(context.Background())
|
||||
now = now.Add(syncInterval)
|
||||
h.srv.Sync(context.Background())
|
||||
src.mu.Lock()
|
||||
unchanged := src.unchanged
|
||||
src.mu.Unlock()
|
||||
if unchanged != 2 {
|
||||
t.Errorf("unchanged answers on the second sync = %d, want 2", unchanged)
|
||||
}
|
||||
if _, body := h.get("status.example.test", "/acme"); !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
|
||||
t.Error("an unchanged page is not served as current")
|
||||
}
|
||||
|
||||
// A changed page is sent again, and the checksum survives a restart.
|
||||
src.set(func(f *fakeSource) {
|
||||
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Renamed", Status: agentapi.PageOperational}
|
||||
})
|
||||
restarted := newHarness(t, src, dir, &now)
|
||||
restarted.srv.Sync(context.Background())
|
||||
src.mu.Lock()
|
||||
unchanged = src.unchanged
|
||||
src.mu.Unlock()
|
||||
if _, body := restarted.get("status.example.test", "/acme"); !strings.Contains(body, "Renamed") || unchanged != 3 {
|
||||
t.Errorf("after a change: renamed %t, unchanged answers %d, want 3", strings.Contains(body, "Renamed"), unchanged)
|
||||
}
|
||||
}
|
||||
@@ -318,6 +318,92 @@ func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const orgOwnerEmails = `-- name: OrgOwnerEmails :many
|
||||
SELECT u.email FROM memberships m JOIN users u ON u.id = m.user_id
|
||||
WHERE m.org_id = $1 AND m.is_owner AND u.disabled_at IS NULL
|
||||
`
|
||||
|
||||
// System scope.
|
||||
func (q *Queries) OrgOwnerEmails(ctx context.Context, orgID uuid.UUID) ([]string, error) {
|
||||
rows, err := q.db.Query(ctx, orgOwnerEmails, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []string{}
|
||||
for rows.Next() {
|
||||
var email string
|
||||
if err := rows.Scan(&email); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, email)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const orgServesOwnPages = `-- name: OrgServesOwnPages :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM agents
|
||||
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
|
||||
)
|
||||
`
|
||||
|
||||
// An organization serves its status pages itself once one of its own
|
||||
// status page servers has connected.
|
||||
func (q *Queries) OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, orgServesOwnPages, orgID)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const regionsToWatch = `-- name: RegionsToWatch :many
|
||||
SELECT r.id, r.name, r.org_id, o.name AS org_name
|
||||
FROM regions r
|
||||
LEFT JOIN orgs o ON o.id = r.org_id
|
||||
WHERE EXISTS (SELECT 1 FROM agents a WHERE a.kind = 'checker' AND a.region_id = r.id)
|
||||
AND EXISTS (SELECT 1 FROM monitor_regions mr JOIN monitors m ON m.id = mr.monitor_id
|
||||
WHERE mr.region_id = r.id AND m.enabled)
|
||||
ORDER BY r.name
|
||||
`
|
||||
|
||||
type RegionsToWatchRow struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
OrgID *uuid.UUID
|
||||
OrgName *string
|
||||
}
|
||||
|
||||
// System scope: regions that have checkers and enabled monitors, so a
|
||||
// region without a live checker leaves monitors unchecked.
|
||||
func (q *Queries) RegionsToWatch(ctx context.Context) ([]RegionsToWatchRow, error) {
|
||||
rows, err := q.db.Query(ctx, regionsToWatch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []RegionsToWatchRow{}
|
||||
for rows.Next() {
|
||||
var i RegionsToWatchRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
&i.OrgID,
|
||||
&i.OrgName,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const setAgentAllowPrivate = `-- name: SetAgentAllowPrivate :execrows
|
||||
UPDATE agents SET allow_private = $1
|
||||
WHERE id = $2 AND kind = 'checker' AND org_id = $3
|
||||
|
||||
@@ -289,6 +289,11 @@ type Querier interface {
|
||||
OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error)
|
||||
OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error)
|
||||
OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgMembersExportRow, error)
|
||||
// System scope.
|
||||
OrgOwnerEmails(ctx context.Context, orgID uuid.UUID) ([]string, error)
|
||||
// An organization serves its status pages itself once one of its own
|
||||
// status page servers has connected.
|
||||
OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error)
|
||||
// Organizations user owns, with their member and owner counts.
|
||||
OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error)
|
||||
// The public updates of incidents shown on a status page, newest first.
|
||||
@@ -318,6 +323,9 @@ type Querier interface {
|
||||
RegionBuckets(ctx context.Context, arg RegionBucketsParams) ([]RegionBucketsRow, error)
|
||||
RegionBucketsDaily(ctx context.Context, arg RegionBucketsDailyParams) ([]RegionBucketsDailyRow, error)
|
||||
RegionBucketsHourly(ctx context.Context, arg RegionBucketsHourlyParams) ([]RegionBucketsHourlyRow, error)
|
||||
// System scope: regions that have checkers and enabled monitors, so a
|
||||
// region without a live checker leaves monitors unchecked.
|
||||
RegionsToWatch(ctx context.Context) ([]RegionsToWatchRow, error)
|
||||
RegroupMonitors(ctx context.Context, arg RegroupMonitorsParams) error
|
||||
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
|
||||
// Moves the subgroups of a group that is about to be deleted.
|
||||
@@ -334,6 +342,10 @@ type Querier interface {
|
||||
// page from a keyset cursor whose string key is monitor and region.
|
||||
ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error)
|
||||
ScrubAuditEmail(ctx context.Context, email string) error
|
||||
// System scope: the published pages a status page server serves, those
|
||||
// of agent_org for an organization's server; the platform's leave the
|
||||
// pages of organizations serving their own.
|
||||
ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]ServablePagesRow, error)
|
||||
SetAgentAllowPrivate(ctx context.Context, arg SetAgentAllowPrivateParams) (int64, error)
|
||||
SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error)
|
||||
SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabledCheckTypesParams) error
|
||||
|
||||
@@ -54,3 +54,27 @@ WHERE id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '30 s
|
||||
-- name: SetAgentAllowPrivate :execrows
|
||||
UPDATE agents SET allow_private = sqlc.arg(allow_private)
|
||||
WHERE id = sqlc.arg(id) AND kind = 'checker' AND org_id = sqlc.arg(org_id);
|
||||
|
||||
-- name: OrgServesOwnPages :one
|
||||
-- An organization serves its status pages itself once one of its own
|
||||
-- status page servers has connected.
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM agents
|
||||
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
|
||||
);
|
||||
|
||||
-- name: RegionsToWatch :many
|
||||
-- System scope: regions that have checkers and enabled monitors, so a
|
||||
-- region without a live checker leaves monitors unchecked.
|
||||
SELECT r.id, r.name, r.org_id, o.name AS org_name
|
||||
FROM regions r
|
||||
LEFT JOIN orgs o ON o.id = r.org_id
|
||||
WHERE EXISTS (SELECT 1 FROM agents a WHERE a.kind = 'checker' AND a.region_id = r.id)
|
||||
AND EXISTS (SELECT 1 FROM monitor_regions mr JOIN monitors m ON m.id = mr.monitor_id
|
||||
WHERE mr.region_id = r.id AND m.enabled)
|
||||
ORDER BY r.name;
|
||||
|
||||
-- name: OrgOwnerEmails :many
|
||||
-- System scope.
|
||||
SELECT u.email FROM memberships m JOIN users u ON u.id = m.user_id
|
||||
WHERE m.org_id = $1 AND m.is_owner AND u.disabled_at IS NULL;
|
||||
@@ -38,7 +38,8 @@ DELETE FROM status_pages WHERE id = $1;
|
||||
|
||||
-- name: StatusPageMonitors :many
|
||||
SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position,
|
||||
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id
|
||||
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id,
|
||||
m.type AS monitor_type, m.interval_seconds
|
||||
FROM status_page_monitors spm
|
||||
JOIN monitors m ON m.id = spm.monitor_id
|
||||
WHERE spm.page_id = $1
|
||||
@@ -93,3 +94,17 @@ WHERE published AND suspended_at IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM orgs o WHERE o.id = status_pages.org_id AND o.suspended_at IS NOT NULL)
|
||||
AND ((sqlc.narg(host)::citext IS NOT NULL AND custom_domain = sqlc.narg(host) AND domain_verified_at IS NOT NULL)
|
||||
OR (sqlc.narg(slug)::citext IS NOT NULL AND slug = sqlc.narg(slug)));
|
||||
|
||||
-- name: ServablePages :many
|
||||
-- System scope: the published pages a status page server serves, those
|
||||
-- of agent_org for an organization's server; the platform's leave the
|
||||
-- pages of organizations serving their own.
|
||||
SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host
|
||||
FROM status_pages p
|
||||
JOIN orgs o ON o.id = p.org_id
|
||||
WHERE p.published AND p.suspended_at IS NULL AND o.suspended_at IS NULL
|
||||
AND CASE WHEN sqlc.narg(agent_org)::uuid IS NULL
|
||||
THEN NOT EXISTS (SELECT 1 FROM agents a WHERE a.org_id = p.org_id AND a.kind = 'statuspage' AND a.last_seen_at IS NOT NULL)
|
||||
ELSE p.org_id = sqlc.narg(agent_org)::uuid
|
||||
END
|
||||
ORDER BY p.slug;
|
||||
@@ -352,6 +352,46 @@ func (q *Queries) ReparentStatusPageGroupMonitors(ctx context.Context, arg Repar
|
||||
return err
|
||||
}
|
||||
|
||||
const servablePages = `-- name: ServablePages :many
|
||||
SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host
|
||||
FROM status_pages p
|
||||
JOIN orgs o ON o.id = p.org_id
|
||||
WHERE p.published AND p.suspended_at IS NULL AND o.suspended_at IS NULL
|
||||
AND CASE WHEN $1::uuid IS NULL
|
||||
THEN NOT EXISTS (SELECT 1 FROM agents a WHERE a.org_id = p.org_id AND a.kind = 'statuspage' AND a.last_seen_at IS NOT NULL)
|
||||
ELSE p.org_id = $1::uuid
|
||||
END
|
||||
ORDER BY p.slug
|
||||
`
|
||||
|
||||
type ServablePagesRow struct {
|
||||
Slug string
|
||||
Host string
|
||||
}
|
||||
|
||||
// System scope: the published pages a status page server serves, those
|
||||
// of agent_org for an organization's server; the platform's leave the
|
||||
// pages of organizations serving their own.
|
||||
func (q *Queries) ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]ServablePagesRow, error) {
|
||||
rows, err := q.db.Query(ctx, servablePages, agentOrg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ServablePagesRow{}
|
||||
for rows.Next() {
|
||||
var i ServablePagesRow
|
||||
if err := rows.Scan(&i.Slug, &i.Host); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const setStatusPageDomain = `-- name: SetStatusPageDomain :one
|
||||
UPDATE status_pages SET
|
||||
custom_domain = $1,
|
||||
@@ -414,7 +454,8 @@ func (q *Queries) SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPa
|
||||
|
||||
const statusPageMonitors = `-- name: StatusPageMonitors :many
|
||||
SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position,
|
||||
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id
|
||||
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id,
|
||||
m.type AS monitor_type, m.interval_seconds
|
||||
FROM status_page_monitors spm
|
||||
JOIN monitors m ON m.id = spm.monitor_id
|
||||
WHERE spm.page_id = $1
|
||||
@@ -422,14 +463,16 @@ ORDER BY spm.position, m.name
|
||||
`
|
||||
|
||||
type StatusPageMonitorsRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Section string
|
||||
GroupID *uuid.UUID
|
||||
Label string
|
||||
Position int32
|
||||
MonitorName string
|
||||
Enabled bool
|
||||
MonitorGroupID *uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
Section string
|
||||
GroupID *uuid.UUID
|
||||
Label string
|
||||
Position int32
|
||||
MonitorName string
|
||||
Enabled bool
|
||||
MonitorGroupID *uuid.UUID
|
||||
MonitorType string
|
||||
IntervalSeconds int32
|
||||
}
|
||||
|
||||
func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error) {
|
||||
@@ -450,6 +493,8 @@ func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]S
|
||||
&i.MonitorName,
|
||||
&i.Enabled,
|
||||
&i.MonitorGroupID,
|
||||
&i.MonitorType,
|
||||
&i.IntervalSeconds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ type SignupConsent struct {
|
||||
templ consentLinks(docs []LegalLink) {
|
||||
for i, d := range docs {
|
||||
if i > 0 {
|
||||
{ i18n.T(ctx, "consent.and") }
|
||||
{ " " + i18n.T(ctx, "consent.and") }
|
||||
}
|
||||
<a href={ templ.SafeURL(d.Href) } target="_blank" rel="noopener" class="underline underline-offset-2">{ i18n.T(ctx, "consent.doc."+d.Kind) }</a>
|
||||
}
|
||||
|
||||
@@ -356,9 +356,9 @@ func consentLinks(docs []LegalLink) templ.Component {
|
||||
for i, d := range docs {
|
||||
if i > 0 {
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "consent.and"))
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(" " + i18n.T(ctx, "consent.and"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 81, Col: 31}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 81, Col: 37}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
|
||||
@@ -28,6 +28,9 @@ type MonitorRow struct {
|
||||
Latency string
|
||||
Uptime string
|
||||
Bars []Bar
|
||||
// Unchecked is set when no region has reported recently: nobody is
|
||||
// checking the monitor.
|
||||
Unchecked bool
|
||||
}
|
||||
|
||||
// GroupNode is a monitor group with its monitors and subgroups.
|
||||
@@ -64,6 +67,15 @@ type DashboardView struct {
|
||||
Counts map[Status]int
|
||||
Range string
|
||||
Ranges []RangeOption
|
||||
// Unchecked counts the monitors no region has reported for recently.
|
||||
Unchecked int
|
||||
// DeadRegions are regions of the monitors without a live checker.
|
||||
DeadRegions []DeadRegion
|
||||
}
|
||||
|
||||
// DeadRegion is a region without a live checker since Since.
|
||||
type DeadRegion struct {
|
||||
Name, Since string
|
||||
}
|
||||
|
||||
// RangeOption is an entry of the range switcher. Disabled ranges are not
|
||||
@@ -151,7 +163,7 @@ templ Dashboard(p Page, me Me, v DashboardView) {
|
||||
<h1 class="text-lg font-semibold">{ i18n.T(ctx, "console.monitors.title") }</h1>
|
||||
<div class="flex flex-wrap items-center gap-x-5 gap-y-3 font-mono text-xs text-muted">
|
||||
@rangeSwitch(v.Ranges)
|
||||
for _, s := range []Status{StatusUp, StatusDegraded, StatusDown, StatusMaintenance, StatusPaused} {
|
||||
for _, s := range []Status{StatusUp, StatusDegraded, StatusDown, StatusUnknown, StatusMaintenance, StatusPaused} {
|
||||
if v.Counts[s] > 0 {
|
||||
<span class="flex items-center gap-1.5">
|
||||
@statusDot(s)
|
||||
@@ -164,6 +176,16 @@ templ Dashboard(p Page, me Me, v DashboardView) {
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
if v.Unchecked > 0 || len(v.DeadRegions) > 0 {
|
||||
<div class="mb-6 border-l-2 border-unknown pl-3 text-sm" role="status">
|
||||
for _, r := range v.DeadRegions {
|
||||
<p>{ i18n.T(ctx, "monitors.dead_region", "Region", r.Name, "Since", r.Since) }</p>
|
||||
}
|
||||
if v.Unchecked > 0 {
|
||||
<p>{ i18n.T(ctx, "monitors.unchecked_banner", "Count", v.Unchecked) }</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
if !v.Empty {
|
||||
<form method="get" action="/" class="mb-4 flex max-w-md gap-2">
|
||||
if v.Range != "" {
|
||||
@@ -229,7 +251,11 @@ templ monitorList(ms []MonitorRow) {
|
||||
</span>
|
||||
</span>
|
||||
<span class="col-span-2 md:col-span-1">@bars(m.Bars, 18)</span>
|
||||
<span class="hidden text-right font-mono text-xs text-muted md:block">{ m.Latency }</span>
|
||||
if m.Unchecked {
|
||||
<span class="hidden text-right font-mono text-xs text-unknown md:block">{ i18n.T(ctx, "monitors.unchecked") }</span>
|
||||
} else {
|
||||
<span class="hidden text-right font-mono text-xs text-muted md:block">{ m.Latency }</span>
|
||||
}
|
||||
<span class="col-start-2 row-start-1 text-right font-mono text-sm md:col-auto md:row-auto">{ m.Uptime }</span>
|
||||
</a>
|
||||
</li>
|
||||
@@ -350,6 +376,9 @@ templ MonitorDetail(p Page, me Me, v MonitorDetailView) {
|
||||
<a href={ templ.SafeURL("/monitors/" + v.Row.ID + "/edit") } class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "sso.action.edit") }</a>
|
||||
}
|
||||
</div>
|
||||
if v.Row.Unchecked {
|
||||
<p class="mb-8 border-l-2 border-unknown pl-3 text-sm" role="status">{ i18n.T(ctx, "monitors.unchecked_banner", "Count", 1) }</p>
|
||||
}
|
||||
<section class="mb-10">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
|
||||
<h2 class="text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.history", "Range", v.Range) }</h2>
|
||||
|
||||
+2750
-2635
File diff suppressed because it is too large.
Load diff
@@ -44,6 +44,8 @@ templ StatusPagesPage(p Page, me Me, v PagesView) {
|
||||
}
|
||||
if pg.Suspended {
|
||||
<span class="ml-auto text-xs text-down">{ i18n.T(ctx, "pages.suspended") }</span>
|
||||
} else if pg.Published && pg.URL == "" {
|
||||
<span class="ml-auto text-xs text-muted">{ i18n.T(ctx, "pages.own_servers_short") }</span>
|
||||
} else if pg.Published {
|
||||
<a href={ templ.SafeURL(pg.URL) } class="ml-auto text-muted hover:text-ink" target="_blank" rel="noopener">{ i18n.T(ctx, "pages.open") } ↗</a>
|
||||
} else {
|
||||
@@ -89,6 +91,9 @@ type PageMonitorOption struct {
|
||||
|
||||
// PageEditor is the data of the status page editor.
|
||||
type PageEditor struct {
|
||||
// OwnServers is set when the organization's own status page servers
|
||||
// serve its pages instead of the platform's.
|
||||
OwnServers bool
|
||||
ID string
|
||||
Title string
|
||||
Slug string
|
||||
@@ -124,12 +129,15 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
|
||||
<div class="mb-8 flex flex-wrap items-baseline justify-between gap-4">
|
||||
<h1 class="text-lg font-semibold">{ e.Title }</h1>
|
||||
<span class="flex gap-5 text-sm">
|
||||
if e.Published {
|
||||
if e.Published && e.URL != "" {
|
||||
<a href={ templ.SafeURL(e.URL) } target="_blank" rel="noopener" class="text-muted hover:text-ink">{ i18n.T(ctx, "pages.open") } ↗</a>
|
||||
}
|
||||
<a href={ templ.SafeURL("/api/v1/org/statuspages/" + e.ID + "/export") } class="text-muted hover:text-ink">{ i18n.T(ctx, "pages.export") }</a>
|
||||
</span>
|
||||
</div>
|
||||
if e.OwnServers {
|
||||
<p class="mb-6 border-l-2 border-ink pl-3 text-sm">{ i18n.T(ctx, "pages.own_servers") }</p>
|
||||
}
|
||||
<div class="grid gap-12 md:grid-cols-2">
|
||||
<section>
|
||||
@sectionHeading("pages.settings")
|
||||
|
||||
+810
-766
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user