feat!: let checkers and status page servers reach data only through the api
Only cmd/api connects to Postgres and Redis. Agents authenticate with tokens created by 'api agent create' and use /agent/v1: checkers long poll for jobs, which doubles as heartbeat, and report results in batches. Organizations manage monitors through /api/v1/org/monitors. BREAKING CHANGE: cmd/checker and cmd/statuspage no longer read UPTIME_DATABASE_URL or UPTIME_REDIS_*; they need UPTIME_API_URL and UPTIME_AGENT_TOKEN. UPTIME_CHECKER_REGION is replaced by the region bound to the agent token. Closes #10 Closes #11 Closes #12 Closes #13 Closes #49 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
56862dce84
commit
d9891bb050
23 files changed
+1361
-45
No files matched your search
@@ -0,0 +1,129 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
const usage = `usage:
|
||||
api [serve]
|
||||
api migrate up|down|status
|
||||
api region add <key> [name]
|
||||
api agent create --kind checker|statuspage [--region <key>] --name <name>
|
||||
api agent list
|
||||
api agent revoke <id>`
|
||||
|
||||
// admin runs operator commands. They act across all organizations, hence the
|
||||
// system scope, and print to stdout for humans and scripts.
|
||||
func admin(ctx context.Context, cfg config.API, args []string) error {
|
||||
if err := cfg.Storage.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := platform.OpenPostgres(ctx, cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
db := tenant.New(pool)
|
||||
|
||||
switch {
|
||||
case len(args) >= 3 && args[0] == "region" && args[1] == "add":
|
||||
name := args[2]
|
||||
if len(args) > 3 {
|
||||
name = args[3]
|
||||
}
|
||||
return db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
r, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: args[2], Name: name})
|
||||
if err == nil {
|
||||
fmt.Printf("region %s (%s)\n", r.Key, r.Name)
|
||||
}
|
||||
return err
|
||||
})
|
||||
case len(args) >= 2 && args[0] == "agent" && args[1] == "create":
|
||||
return createAgent(ctx, db, args[2:])
|
||||
case len(args) == 2 && args[0] == "agent" && args[1] == "list":
|
||||
return db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
agents, err := q.ListAgents(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)
|
||||
_, _ = fmt.Fprintln(w, "ID\tKIND\tREGION\tNAME\tTOKEN\tLAST SEEN\tRELEASE")
|
||||
for _, a := range agents {
|
||||
seen := "never"
|
||||
if a.LastSeenAt != nil {
|
||||
seen = a.LastSeenAt.Format(time.DateTime)
|
||||
}
|
||||
_, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s…\t%s\t%s\n", a.ID, a.Kind, deref(a.Region), a.Name, a.Prefix, seen, deref(a.Release))
|
||||
}
|
||||
return w.Flush()
|
||||
})
|
||||
case len(args) == 3 && args[0] == "agent" && args[1] == "revoke":
|
||||
id, err := uuid.Parse(args[2])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
n, err := q.DeleteAgent(ctx, id)
|
||||
if err == nil && n == 0 {
|
||||
err = errors.New("agent not found")
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
return errors.New(usage)
|
||||
}
|
||||
|
||||
func createAgent(ctx context.Context, db *tenant.DB, args []string) error {
|
||||
fs := flag.NewFlagSet("agent create", flag.ContinueOnError)
|
||||
kind := fs.String("kind", "checker", "checker or statuspage")
|
||||
region := fs.String("region", "", "region key, required for checkers; created if missing")
|
||||
name := fs.String("name", "", "display name")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if *name == "" || (*kind == "checker") != (*region != "") {
|
||||
return errors.New(usage)
|
||||
}
|
||||
tok := api.AgentTokenPrefix + auth.RandomToken()
|
||||
params := store.CreateAgentParams{Kind: *kind, Name: *name, TokenHash: api.HashToken(tok), Prefix: tok[:len(api.AgentTokenPrefix)+6]}
|
||||
if *region != "" {
|
||||
params.Region = region
|
||||
}
|
||||
err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if *region != "" {
|
||||
if _, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: *region, Name: ""}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err := q.CreateAgent(ctx, params)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(tok)
|
||||
return nil
|
||||
}
|
||||
|
||||
func deref[T any](p *T) T {
|
||||
var zero T
|
||||
if p == nil {
|
||||
return zero
|
||||
}
|
||||
return *p
|
||||
}
|
||||
+12
-6
@@ -38,11 +38,16 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
ctx, stop := platform.SignalContext()
|
||||
defer stop()
|
||||
|
||||
if len(args) > 0 && args[0] == "migrate" {
|
||||
return migrate(ctx, log, cfg.DatabaseURL, args[1:])
|
||||
}
|
||||
if len(args) > 0 && args[0] != "serve" {
|
||||
return errors.New("usage: api [serve | migrate up|down|status]")
|
||||
if len(args) > 0 {
|
||||
switch args[0] {
|
||||
case "migrate":
|
||||
return migrate(ctx, log, cfg.DatabaseURL, args[1:])
|
||||
case "agent", "region":
|
||||
return admin(ctx, cfg, args)
|
||||
case "serve":
|
||||
default:
|
||||
return errors.New(usage)
|
||||
}
|
||||
}
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
@@ -52,7 +57,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
deps, err := platform.Connect(ctx, cfg.Common, log)
|
||||
deps, err := platform.Connect(ctx, cfg.Storage, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -68,6 +73,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
health.Register(r)
|
||||
r.StaticFS("/static", web.Static())
|
||||
srv.Mount(r)
|
||||
go srv.RunScheduler(ctx)
|
||||
|
||||
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
|
||||
}
|
||||
|
||||
+33
-7
@@ -1,11 +1,20 @@
|
||||
// Command checker executes uptime checks for one region and pulls data from
|
||||
// external sources. Any number of instances per region may run.
|
||||
// Command checker executes uptime checks for one region. It talks only to
|
||||
// the API, never to the database or Redis, so it can run anywhere the API is
|
||||
// reachable, including customer networks. Any number of instances may share
|
||||
// a region and token; each check goes to a randomly chosen live instance.
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/checker"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
)
|
||||
@@ -26,19 +35,36 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
return err
|
||||
}
|
||||
level.Set(cfg.LogLevel)
|
||||
if err := cfg.Common.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := platform.SignalContext()
|
||||
defer stop()
|
||||
|
||||
log = log.With("region", cfg.Region)
|
||||
deps, err := platform.Connect(ctx, cfg.Common, log)
|
||||
instance := uuid.New()
|
||||
client := agentapi.NewClient(cfg.APIURL, cfg.Token, instance, buildinfo.Version)
|
||||
hello, err := platform.Hello(ctx, client, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer deps.Close()
|
||||
if hello.Kind != "checker" {
|
||||
return fmt.Errorf("token belongs to a %s agent, not a checker", hello.Kind)
|
||||
}
|
||||
log = log.With("region", hello.Region, "agent", hello.Name, "instance", instance)
|
||||
log.Info("connected to api")
|
||||
|
||||
health := platform.NewHealth(deps.Probes())
|
||||
runner := checker.New(client, cfg.Concurrency, log)
|
||||
health := platform.NewHealth(map[string]platform.Probe{"api": runner.Healthy})
|
||||
r := platform.NewRouter(log)
|
||||
health.Register(r)
|
||||
|
||||
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.HealthListen, r), health, 0, cfg.ShutdownTimeout)
|
||||
serveErr := make(chan error, 1)
|
||||
go func() {
|
||||
serveErr <- platform.Serve(ctx, log, platform.NewHTTPServer(cfg.HealthListen, r), health, 0, cfg.ShutdownTimeout)
|
||||
}()
|
||||
runErr := runner.Run(ctx, cfg.ShutdownTimeout)
|
||||
if errors.Is(runErr, agentapi.ErrUnauthorized) {
|
||||
stop()
|
||||
}
|
||||
return errors.Join(runErr, <-serveErr)
|
||||
}
|
||||
+18
-4
@@ -1,12 +1,18 @@
|
||||
// Command statuspage serves public status pages, including on customer
|
||||
// domains.
|
||||
// domains. Like the checker it reads data only through the API.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
@@ -28,16 +34,24 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
return err
|
||||
}
|
||||
level.Set(cfg.LogLevel)
|
||||
if err := cfg.Common.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := platform.SignalContext()
|
||||
defer stop()
|
||||
|
||||
deps, err := platform.Connect(ctx, cfg.Common, log)
|
||||
client := agentapi.NewClient(cfg.APIURL, cfg.Token, uuid.New(), buildinfo.Version)
|
||||
hello, err := platform.Hello(ctx, client, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer deps.Close()
|
||||
if hello.Kind != "statuspage" {
|
||||
return fmt.Errorf("token belongs to a %s agent, not a status page server", hello.Kind)
|
||||
}
|
||||
|
||||
health := platform.NewHealth(deps.Probes())
|
||||
health := platform.NewHealth(map[string]platform.Probe{
|
||||
"api": func(ctx context.Context) error { _, err := client.Hello(ctx); return err },
|
||||
})
|
||||
r := platform.NewRouter(log)
|
||||
health.Register(r)
|
||||
r.StaticFS("/static", web.Static())
|
||||
|
||||
Reference in new issue
Block a user