feat(api): configurable retention, housekeeping and storage overview
UPTIME_RETENTION_RAW, _HOURLY and _DAILY set TimescaleDB's retention policies, applied by "api migrate up" with owner rights and on start; periods too short for the charts are rejected. An hourly job deletes delivered notifications, stale invitations and expired API tokens after UPTIME_RETENTION_HOUSEKEEPING and resolved incidents together with the daily aggregate. The admin panel shows size, compression, retention and background job status of each storage level. Closes #63 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
057e41d5b6
commit
538e9358c3
17 files changed
+1342
-7
No files matched your search
@@ -0,0 +1,123 @@
|
||||
// Package datapolicy keeps TimescaleDB's retention policies in line with
|
||||
// the configuration and reports storage use.
|
||||
//
|
||||
// Raw results are compressed after a week and dropped after Raw; the hourly
|
||||
// and daily aggregates outlive them so long charts keep working. All
|
||||
// policies run as TimescaleDB background jobs; this package only sets them.
|
||||
package datapolicy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Retention sets how long each level of check results is kept. Zero keeps
|
||||
// a level forever.
|
||||
type Retention struct {
|
||||
Raw time.Duration
|
||||
Hourly time.Duration
|
||||
Daily time.Duration
|
||||
}
|
||||
|
||||
// Relations in the order data flows through them.
|
||||
var relations = []string{"check_results", "check_results_1h", "check_results_1d"}
|
||||
|
||||
func (r Retention) of(rel string) time.Duration {
|
||||
switch rel {
|
||||
case "check_results":
|
||||
return r.Raw
|
||||
case "check_results_1h":
|
||||
return r.Hourly
|
||||
}
|
||||
return r.Daily
|
||||
}
|
||||
|
||||
// Validate rejects periods that would break features: charts read the
|
||||
// hourly aggregate for up to 30 days and the daily one for up to a year,
|
||||
// and the hourly aggregate is refreshed from the last three days of raw
|
||||
// data.
|
||||
func (r Retention) Validate() error {
|
||||
day := 24 * time.Hour
|
||||
switch {
|
||||
case r.Raw != 0 && r.Raw < 7*day:
|
||||
return fmt.Errorf("datapolicy: raw results must be kept at least 7 days")
|
||||
case r.Hourly != 0 && r.Hourly < 35*day:
|
||||
return fmt.Errorf("datapolicy: the hourly aggregate must be kept at least 35 days")
|
||||
case r.Daily != 0 && r.Daily < 365*day:
|
||||
return fmt.Errorf("datapolicy: the daily aggregate must be kept at least 365 days")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// lockID serializes Apply across API replicas starting at the same time.
|
||||
const lockID = 0x75707470
|
||||
|
||||
// Apply replaces retention policies whose period differs from want. It is
|
||||
// idempotent and safe to call from several replicas.
|
||||
func Apply(ctx context.Context, pool *pgxpool.Pool, want Retention, log *slog.Logger) error {
|
||||
if err := want.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockID); err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := retentionPolicies(ctx, tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, rel := range relations {
|
||||
have, ok := current[rel]
|
||||
target := want.of(rel)
|
||||
if (ok && have == target) || (!ok && target == 0) {
|
||||
continue
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `SELECT remove_retention_policy($1::regclass, if_exists => true)`, rel); err != nil {
|
||||
return fmt.Errorf("datapolicy: removing retention of %s: %w", rel, err)
|
||||
}
|
||||
if target > 0 {
|
||||
if _, err := tx.Exec(ctx, `SELECT add_retention_policy($1::regclass, drop_after => $2::interval)`, rel, interval(target)); err != nil {
|
||||
return fmt.Errorf("datapolicy: setting retention of %s: %w", rel, err)
|
||||
}
|
||||
}
|
||||
log.InfoContext(ctx, "retention policy updated", "relation", rel, "from", have.String(), "to", target.String())
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func retentionPolicies(ctx context.Context, q interface {
|
||||
Query(context.Context, string, ...any) (pgx.Rows, error)
|
||||
}) (map[string]time.Duration, error) {
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT hypertable_name, (config->>'drop_after')::interval
|
||||
FROM timescaledb_information.jobs
|
||||
WHERE proc_name = 'policy_retention'`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]time.Duration{}
|
||||
for rows.Next() {
|
||||
var name string
|
||||
var d time.Duration
|
||||
if err := rows.Scan(&name, &d); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[name] = d
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// interval formats d for Postgres, in days where possible so policies read
|
||||
// as configured.
|
||||
func interval(d time.Duration) string {
|
||||
if d%(24*time.Hour) == 0 {
|
||||
return fmt.Sprintf("%d days", d/(24*time.Hour))
|
||||
}
|
||||
return fmt.Sprintf("%d seconds", int64(d.Seconds()))
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package datapolicy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
)
|
||||
|
||||
const day = 24 * time.Hour
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
r Retention
|
||||
ok bool
|
||||
}{
|
||||
{Retention{}, true},
|
||||
{Retention{Raw: 90 * day, Hourly: 400 * day, Daily: 365 * day}, true},
|
||||
{Retention{Raw: 6 * day}, false},
|
||||
{Retention{Hourly: 30 * day}, false},
|
||||
{Retention{Daily: 364 * day}, false},
|
||||
} {
|
||||
if err := tc.r.Validate(); (err == nil) != tc.ok {
|
||||
t.Errorf("%+v.Validate() = %v, want ok=%t", tc.r, err, tc.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testPool(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("UPTIME_TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("UPTIME_TEST_DATABASE_URL must be set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
if _, err := migrations.Up(ctx, dsn); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
func TestApply(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
ctx := context.Background()
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
defaults := Retention{Raw: 90 * day, Hourly: 400 * day, Daily: 1095 * day}
|
||||
t.Cleanup(func() { _ = Apply(ctx, pool, defaults, log) })
|
||||
|
||||
want := Retention{Raw: 30 * day, Hourly: 0, Daily: 730 * day}
|
||||
for range 2 {
|
||||
if err := Apply(ctx, pool, want, log); err != nil {
|
||||
t.Fatalf("Apply() = %v", err)
|
||||
}
|
||||
}
|
||||
got, err := retentionPolicies(ctx, pool)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got["check_results"] != want.Raw || got["check_results_1d"] != want.Daily {
|
||||
t.Errorf("policies = %v, want raw %v and daily %v", got, want.Raw, want.Daily)
|
||||
}
|
||||
if _, ok := got["check_results_1h"]; ok {
|
||||
t.Error("hourly aggregate still has a retention policy after setting it to forever")
|
||||
}
|
||||
if err := Apply(ctx, pool, Retention{Raw: day}, log); err == nil {
|
||||
t.Error("Apply() accepted one day of raw results")
|
||||
}
|
||||
|
||||
st, err := Collect(ctx, pool)
|
||||
if err != nil {
|
||||
t.Fatalf("Collect() = %v", err)
|
||||
}
|
||||
if len(st.Relations) != 3 || st.Relations[0].Name != "check_results" || st.Relations[0].Retention != want.Raw {
|
||||
t.Errorf("Collect().Relations = %+v", st.Relations)
|
||||
}
|
||||
if len(st.Jobs) == 0 {
|
||||
t.Error("Collect() found no background jobs")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package datapolicy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// RelationStats describes one level of check result storage.
|
||||
type RelationStats struct {
|
||||
Name string
|
||||
// TotalBytes includes indexes and compressed data.
|
||||
TotalBytes int64
|
||||
// BeforeBytes and AfterBytes cover compressed chunks only.
|
||||
BeforeBytes int64
|
||||
AfterBytes int64
|
||||
Chunks int64
|
||||
CompressedChunks int64
|
||||
Retention time.Duration
|
||||
CompressAfter time.Duration
|
||||
}
|
||||
|
||||
// JobStats is the last run of a TimescaleDB background job.
|
||||
type JobStats struct {
|
||||
ID int64
|
||||
Proc string
|
||||
Relation string
|
||||
LastStatus string
|
||||
LastRun *time.Time
|
||||
NextRun *time.Time
|
||||
Failures int64
|
||||
}
|
||||
|
||||
// Stats is a storage overview for the admin panel.
|
||||
type Stats struct {
|
||||
Relations []RelationStats
|
||||
Jobs []JobStats
|
||||
// TableBytes lists the largest regular tables.
|
||||
TableBytes map[string]int64
|
||||
}
|
||||
|
||||
// Collect gathers storage statistics. Aggregates are measured through their
|
||||
// materialization hypertables.
|
||||
func Collect(ctx context.Context, pool *pgxpool.Pool) (Stats, error) {
|
||||
var s Stats
|
||||
rows, err := pool.Query(ctx, `
|
||||
WITH rel AS (
|
||||
SELECT 'check_results'::text AS name, 'public'::text AS schema, 'check_results'::text AS ht
|
||||
UNION ALL
|
||||
SELECT view_name::text, materialization_hypertable_schema::text, materialization_hypertable_name::text
|
||||
FROM timescaledb_information.continuous_aggregates
|
||||
WHERE view_name IN ('check_results_1h', 'check_results_1d')
|
||||
)
|
||||
SELECT rel.name,
|
||||
hypertable_size(format('%I.%I', rel.schema, rel.ht)::regclass),
|
||||
coalesce(cs.before_compression_total_bytes, 0),
|
||||
coalesce(cs.after_compression_total_bytes, 0),
|
||||
coalesce(cs.total_chunks, 0),
|
||||
coalesce(cs.number_compressed_chunks, 0),
|
||||
(SELECT (config->>'drop_after')::interval FROM timescaledb_information.jobs
|
||||
WHERE proc_name = 'policy_retention' AND hypertable_name = rel.name),
|
||||
(SELECT (config->>'compress_after')::interval FROM timescaledb_information.jobs
|
||||
WHERE proc_name = 'policy_compression' AND hypertable_name = rel.name)
|
||||
FROM rel
|
||||
LEFT JOIN LATERAL hypertable_compression_stats(format('%I.%I', rel.schema, rel.ht)::regclass) cs ON true
|
||||
ORDER BY array_position(ARRAY['check_results', 'check_results_1h', 'check_results_1d'], rel.name)`)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var r RelationStats
|
||||
var retention, compress *time.Duration
|
||||
if err := rows.Scan(&r.Name, &r.TotalBytes, &r.BeforeBytes, &r.AfterBytes, &r.Chunks, &r.CompressedChunks, &retention, &compress); err != nil {
|
||||
return s, err
|
||||
}
|
||||
if retention != nil {
|
||||
r.Retention = *retention
|
||||
}
|
||||
if compress != nil {
|
||||
r.CompressAfter = *compress
|
||||
}
|
||||
s.Relations = append(s.Relations, r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return s, err
|
||||
}
|
||||
|
||||
rows, err = pool.Query(ctx, `
|
||||
SELECT j.job_id, j.proc_name, coalesce(j.hypertable_name, ''), coalesce(st.last_run_status, ''),
|
||||
st.last_run_started_at, st.next_start, coalesce(st.total_failures, 0)
|
||||
FROM timescaledb_information.jobs j
|
||||
LEFT JOIN timescaledb_information.job_stats st USING (job_id)
|
||||
WHERE j.proc_name LIKE 'policy_%' AND j.proc_name <> 'policy_telemetry'
|
||||
ORDER BY j.hypertable_name NULLS FIRST, j.proc_name`)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var j JobStats
|
||||
if err := rows.Scan(&j.ID, &j.Proc, &j.Relation, &j.LastStatus, &j.LastRun, &j.NextRun, &j.Failures); err != nil {
|
||||
return s, err
|
||||
}
|
||||
s.Jobs = append(s.Jobs, j)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return s, err
|
||||
}
|
||||
|
||||
s.TableBytes = map[string]int64{}
|
||||
rows, err = pool.Query(ctx, `
|
||||
SELECT relname::text, pg_total_relation_size(c.oid)
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = 'public' AND c.relkind = 'r'
|
||||
AND relname IN ('incidents', 'notifications', 'monitors', 'agent_storage', 'invitations', 'api_tokens')`)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var name string
|
||||
var size int64
|
||||
if err := rows.Scan(&name, &size); err != nil {
|
||||
return s, err
|
||||
}
|
||||
s.TableBytes[name] = size
|
||||
}
|
||||
return s, rows.Err()
|
||||
}
|
||||
Reference in new issue
Block a user