round3-hub: backup, metrics auth, device ls, gc --keep-days, access log
Some checks are pending
CI / vet-build-test (push) Waiting to run
Some checks are pending
CI / vet-build-test (push) Waiting to run
This commit is contained in:
parent
8f78f65d57
commit
dd27af3cc2
7 changed files with 441 additions and 20 deletions
|
|
@ -78,7 +78,7 @@ func TestGCKeepsChunksSharedAcrossShares(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// GC keeping only each share's head.
|
// GC keeping only each share's head.
|
||||||
if _, _, err := runGC(db, store, 1, false); err != nil {
|
if _, _, err := runGC(db, store, 1, 0, false); err != nil {
|
||||||
t.Fatalf("gc: %v", err)
|
t.Fatalf("gc: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -98,7 +98,7 @@ func TestGCDropsOldUniqueChunks(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// gc keeping only the newest snapshot (v2 == head): v1 is pruned.
|
// gc keeping only the newest snapshot (v2 == head): v1 is pruned.
|
||||||
snaps, chunks, err := runGC(db, store, 1, false)
|
snaps, chunks, err := runGC(db, store, 1, 0, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("gc: %v", err)
|
t.Fatalf("gc: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -193,7 +193,7 @@ func TestGCDryRun(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dry-run reports what would go, deletes nothing.
|
// Dry-run reports what would go, deletes nothing.
|
||||||
dSnaps, dChunks, err := runGC(db, store, 1, true)
|
dSnaps, dChunks, err := runGC(db, store, 1, 0, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("dry-run gc: %v", err)
|
t.Fatalf("dry-run gc: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -210,7 +210,7 @@ func TestGCDryRun(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Real run matches the dry-run prediction.
|
// Real run matches the dry-run prediction.
|
||||||
rSnaps, rChunks, err := runGC(db, store, 1, false)
|
rSnaps, rChunks, err := runGC(db, store, 1, 0, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("gc: %v", err)
|
t.Fatalf("gc: %v", err)
|
||||||
}
|
}
|
||||||
|
|
@ -257,3 +257,69 @@ func intersect(a, b []string) []string {
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestGCKeepDays proves that --keep-days keeps a snapshot still within the
|
||||||
|
// time window even when it's outside the --keep newest-N window, and prunes it
|
||||||
|
// once it's beyond both.
|
||||||
|
func TestGCKeepDays(t *testing.T) {
|
||||||
|
twoDaysAgo := time.Now().Add(-48 * time.Hour).Unix()
|
||||||
|
now := time.Now().Unix()
|
||||||
|
|
||||||
|
setup := func(t *testing.T) (*meta.DB, blobstore.Store) {
|
||||||
|
t.Helper()
|
||||||
|
db, err := meta.Open(":memory:")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { db.Close() })
|
||||||
|
store, err := blobstore.NewDisk(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.AddDevice("d1", "dev", []byte("pub"), now); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.CreateShare("proj", "d1", now); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// v1: 2 days old — beyond the keep=1 window but within 3 days.
|
||||||
|
if err := db.AddSnapshot(meta.Snapshot{
|
||||||
|
ID: "v1snap", Share: "proj", DeviceID: "d1",
|
||||||
|
ManifestHash: "v1snap", CreatedAt: twoDaysAgo,
|
||||||
|
}, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// v2: now — this becomes the head.
|
||||||
|
if err := db.AddSnapshot(meta.Snapshot{
|
||||||
|
ID: "v2snap", Share: "proj", DeviceID: "d1",
|
||||||
|
ManifestHash: "v2snap", CreatedAt: now,
|
||||||
|
}, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return db, store
|
||||||
|
}
|
||||||
|
|
||||||
|
// keepDays=3: v1 is 2 days old → within window → kept despite being beyond keep=1.
|
||||||
|
t.Run("within-keepDays", func(t *testing.T) {
|
||||||
|
db, store := setup(t)
|
||||||
|
snaps, _, err := runGC(db, store, 1, 3, false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if snaps != 0 {
|
||||||
|
t.Fatalf("keepDays=3: pruned %d snapshots, want 0 (v1 within 3-day window)", snaps)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// keepDays=1: v1 is 2 days old → beyond 1-day window → pruned.
|
||||||
|
t.Run("beyond-keepDays", func(t *testing.T) {
|
||||||
|
db, store := setup(t)
|
||||||
|
snaps, _, err := runGC(db, store, 1, 1, false)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if snaps != 1 {
|
||||||
|
t.Fatalf("keepDays=1: pruned %d snapshots, want 1 (v1 beyond 1-day window)", snaps)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,11 @@ import (
|
||||||
"cmp"
|
"cmp"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
|
@ -56,6 +60,8 @@ func main() {
|
||||||
memberCmd(),
|
memberCmd(),
|
||||||
principalCmd(),
|
principalCmd(),
|
||||||
gcCmd(),
|
gcCmd(),
|
||||||
|
backupCmd(),
|
||||||
|
deviceCmd(),
|
||||||
)
|
)
|
||||||
if err := root.Execute(); err != nil {
|
if err := root.Execute(); err != nil {
|
||||||
fmt.Fprintln(os.Stderr, "error:", err)
|
fmt.Fprintln(os.Stderr, "error:", err)
|
||||||
|
|
@ -72,8 +78,8 @@ func openDB(data string) (*meta.DB, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func serveCmd() *cobra.Command {
|
func serveCmd() *cobra.Command {
|
||||||
var data, listen, dashAddr, dashToken string
|
var data, listen, dashAddr, dashToken, metricsToken string
|
||||||
var dash bool
|
var dash, accessLog bool
|
||||||
var gcEvery time.Duration
|
var gcEvery time.Duration
|
||||||
var gcKeep int
|
var gcKeep int
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
|
|
@ -88,7 +94,7 @@ func serveCmd() *cobra.Command {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
srv := hub.NewServer(db, store).SetVersion(version)
|
srv := hub.NewServer(db, store).SetVersion(version).SetMetricsToken(metricsToken)
|
||||||
out := cmd.OutOrStdout()
|
out := cmd.OutOrStdout()
|
||||||
|
|
||||||
// Optional live dashboard on its own address (localhost by default so it
|
// Optional live dashboard on its own address (localhost by default so it
|
||||||
|
|
@ -123,7 +129,7 @@ func serveCmd() *cobra.Command {
|
||||||
t := time.NewTicker(gcEvery)
|
t := time.NewTicker(gcEvery)
|
||||||
defer t.Stop()
|
defer t.Stop()
|
||||||
for range t.C {
|
for range t.C {
|
||||||
snaps, chunks, err := runGC(db, store, gcKeep, false)
|
snaps, chunks, err := runGC(db, store, gcKeep, 0, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(out, "gc sweep error: %v\n", err)
|
fmt.Fprintf(out, "gc sweep error: %v\n", err)
|
||||||
continue
|
continue
|
||||||
|
|
@ -140,9 +146,13 @@ func serveCmd() *cobra.Command {
|
||||||
// Explicit timeouts bound the slowloris surface (bare ListenAndServe
|
// Explicit timeouts bound the slowloris surface (bare ListenAndServe
|
||||||
// has none). No WriteTimeout on purpose: the /v1/events SSE stream is
|
// has none). No WriteTimeout on purpose: the /v1/events SSE stream is
|
||||||
// long-lived and a WriteTimeout would kill it mid-flight.
|
// long-lived and a WriteTimeout would kill it mid-flight.
|
||||||
|
handler := srv.Handler()
|
||||||
|
if accessLog {
|
||||||
|
handler = hub.AccessLogMiddleware(handler)
|
||||||
|
}
|
||||||
httpSrv := &http.Server{
|
httpSrv := &http.Server{
|
||||||
Addr: listen,
|
Addr: listen,
|
||||||
Handler: srv.Handler(),
|
Handler: handler,
|
||||||
ReadHeaderTimeout: 10 * time.Second,
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
ReadTimeout: 30 * time.Second,
|
ReadTimeout: 30 * time.Second,
|
||||||
IdleTimeout: 120 * time.Second,
|
IdleTimeout: 120 * time.Second,
|
||||||
|
|
@ -158,6 +168,8 @@ func serveCmd() *cobra.Command {
|
||||||
cmd.Flags().StringVar(&dashToken, "dashboard-token", "", "require this token to view the dashboard (recommended for non-loopback binds)")
|
cmd.Flags().StringVar(&dashToken, "dashboard-token", "", "require this token to view the dashboard (recommended for non-loopback binds)")
|
||||||
cmd.Flags().DurationVar(&gcEvery, "gc-every", 0, "run in-process GC on this interval (0 = off; e.g. 24h) — animates on the dashboard")
|
cmd.Flags().DurationVar(&gcEvery, "gc-every", 0, "run in-process GC on this interval (0 = off; e.g. 24h) — animates on the dashboard")
|
||||||
cmd.Flags().IntVar(&gcKeep, "gc-keep", 10, "snapshots to keep per share when --gc-every sweeps")
|
cmd.Flags().IntVar(&gcKeep, "gc-keep", 10, "snapshots to keep per share when --gc-every sweeps")
|
||||||
|
cmd.Flags().StringVar(&metricsToken, "metrics-token", "", "require this token to access /metrics (empty = open)")
|
||||||
|
cmd.Flags().BoolVar(&accessLog, "access-log", false, "log one line per request to stderr (method, path, status, bytes, addr, duration)")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -359,7 +371,7 @@ func principalCmd() *cobra.Command {
|
||||||
|
|
||||||
func gcCmd() *cobra.Command {
|
func gcCmd() *cobra.Command {
|
||||||
var data string
|
var data string
|
||||||
var keep int
|
var keep, keepDays int
|
||||||
var dryRun bool
|
var dryRun bool
|
||||||
cmd := &cobra.Command{
|
cmd := &cobra.Command{
|
||||||
Use: "gc",
|
Use: "gc",
|
||||||
|
|
@ -374,7 +386,7 @@ func gcCmd() *cobra.Command {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
snaps, chunks, err := runGC(db, store, keep, dryRun)
|
snaps, chunks, err := runGC(db, store, keep, keepDays, dryRun)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -388,17 +400,17 @@ func gcCmd() *cobra.Command {
|
||||||
}
|
}
|
||||||
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
||||||
cmd.Flags().IntVar(&keep, "keep", 10, "snapshots to keep per share (newest)")
|
cmd.Flags().IntVar(&keep, "keep", 10, "snapshots to keep per share (newest)")
|
||||||
|
cmd.Flags().IntVar(&keepDays, "keep-days", 0, "also keep snapshots newer than N days regardless of --keep (0 = disabled)")
|
||||||
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "show what would be pruned without deleting anything")
|
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "show what would be pruned without deleting anything")
|
||||||
return cmd
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
// runGC prunes deletable snapshots (keeping the head + `keep` newest per share)
|
// runGC prunes deletable snapshots (keeping the head + `keep` newest per share,
|
||||||
// and sweeps unreachable chunks. It is mark-and-sweep from every share's live
|
// and optionally any snapshot created within the last keepDays days) and sweeps
|
||||||
// snapshots as roots: nothing reachable from a kept snapshot is ever deleted,
|
// unreachable chunks. keepDays=0 preserves the existing behaviour exactly.
|
||||||
// regardless of refcounts. That makes GC safe even when refcounts are off — e.g.
|
// It is mark-and-sweep from every share's live snapshots as roots: nothing
|
||||||
// content-addressed snapshot ids are shared across shares, so a naive per-share
|
// reachable from a kept snapshot is ever deleted, regardless of refcounts.
|
||||||
// refcount can undercount a chunk that two share heads both need.
|
func runGC(db *meta.DB, store blobstore.Store, keep, keepDays int, dryRun bool) (snaps, chunks int, err error) {
|
||||||
func runGC(db *meta.DB, store blobstore.Store, keep int, dryRun bool) (snaps, chunks int, err error) {
|
|
||||||
shares, err := db.ShareNames()
|
shares, err := db.ShareNames()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, err
|
||||||
|
|
@ -412,6 +424,13 @@ func runGC(db *meta.DB, store blobstore.Store, keep int, dryRun bool) (snaps, ch
|
||||||
headSet[h] = true
|
headSet[h] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cutoff for --keep-days: snapshots created after this unix timestamp are kept
|
||||||
|
// even when outside the --keep newest-N window. Zero means "disabled".
|
||||||
|
var keepDaysCutoff int64
|
||||||
|
if keepDays > 0 {
|
||||||
|
keepDaysCutoff = time.Now().Add(-time.Duration(keepDays) * 24 * time.Hour).Unix()
|
||||||
|
}
|
||||||
|
|
||||||
// Partition snapshots into kept vs prunable. Snapshots are now per-(share, id),
|
// Partition snapshots into kept vs prunable. Snapshots are now per-(share, id),
|
||||||
// so a prunable entry is a (share, id) pair: it's deletable for its share AND
|
// so a prunable entry is a (share, id) pair: it's deletable for its share AND
|
||||||
// not the head of ANY share (a shared content id may be one share's stale
|
// not the head of ANY share (a shared content id may be one share's stale
|
||||||
|
|
@ -429,13 +448,26 @@ func runGC(db *meta.DB, store blobstore.Store, keep int, dryRun bool) (snaps, ch
|
||||||
for _, id := range del {
|
for _, id := range del {
|
||||||
delSet[id] = true
|
delSet[id] = true
|
||||||
}
|
}
|
||||||
|
// Fetch timestamps once per share when --keep-days is active.
|
||||||
|
var timestamps map[string]int64
|
||||||
|
if keepDaysCutoff != 0 {
|
||||||
|
timestamps, err = db.SnapshotTimestamps(share)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
ids, err := db.SnapshotIDs(share)
|
ids, err := db.SnapshotIDs(share)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, 0, err
|
return 0, 0, err
|
||||||
}
|
}
|
||||||
for _, id := range ids {
|
for _, id := range ids {
|
||||||
if delSet[id] && !headSet[id] {
|
if delSet[id] && !headSet[id] {
|
||||||
prunable = append(prunable, snapRef{share, id})
|
// Keep if within the --keep-days window (timestamp >= cutoff).
|
||||||
|
if keepDaysCutoff != 0 && timestamps[id] >= keepDaysCutoff {
|
||||||
|
keptSnaps[id] = true
|
||||||
|
} else {
|
||||||
|
prunable = append(prunable, snapRef{share, id})
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
keptSnaps[id] = true
|
keptSnaps[id] = true
|
||||||
}
|
}
|
||||||
|
|
@ -573,3 +605,122 @@ func randHex(n int) (string, error) {
|
||||||
}
|
}
|
||||||
return hex.EncodeToString(b), nil
|
return hex.EncodeToString(b), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func backupCmd() *cobra.Command {
|
||||||
|
var data string
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "backup <dir>",
|
||||||
|
Short: "💾 snapshot the DB + blobs to a directory",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
destDir := args[0]
|
||||||
|
if err := os.MkdirAll(destDir, 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
db, err := openDB(data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err := db.BackupTo(filepath.Join(destDir, "devbox-hub.db")); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// ponytail: blobs are a plain recursive copy; rsync/incremental is the upgrade path
|
||||||
|
srcBlobs := filepath.Join(data, "blobs")
|
||||||
|
dstBlobs := filepath.Join(destDir, "blobs")
|
||||||
|
var filesCopied, bytesCopied int64
|
||||||
|
walkErr := filepath.WalkDir(srcBlobs, func(path string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rel, _ := filepath.Rel(srcBlobs, path)
|
||||||
|
dst := filepath.Join(dstBlobs, rel)
|
||||||
|
if d.IsDir() {
|
||||||
|
return os.MkdirAll(dst, 0o700)
|
||||||
|
}
|
||||||
|
in, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer in.Close()
|
||||||
|
out, err := os.Create(dst)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer out.Close()
|
||||||
|
n, err := io.Copy(out, in)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
filesCopied++
|
||||||
|
bytesCopied += n
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if walkErr != nil && !errors.Is(walkErr, os.ErrNotExist) {
|
||||||
|
return walkErr
|
||||||
|
}
|
||||||
|
fmt.Fprintf(cmd.OutOrStdout(), "✅ backup: db + %d blobs (%d bytes) → %s\n", filesCopied, bytesCopied, destDir)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func deviceCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{Use: "device", Short: "🖥️ manage devices"}
|
||||||
|
var data string
|
||||||
|
var asJSON bool
|
||||||
|
ls := &cobra.Command{
|
||||||
|
Use: "ls",
|
||||||
|
Short: "list enrolled devices",
|
||||||
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||||
|
db, err := openDB(data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
devices, err := db.Devices()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if asJSON {
|
||||||
|
type deviceView struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Principal string `json:"principal"`
|
||||||
|
LastSeen int64 `json:"last_seen"`
|
||||||
|
Revoked bool `json:"revoked"`
|
||||||
|
}
|
||||||
|
out := make([]deviceView, len(devices))
|
||||||
|
for i, d := range devices {
|
||||||
|
out[i] = deviceView{d.ID, d.Name, d.Principal, d.LastSeen, d.Revoked}
|
||||||
|
}
|
||||||
|
enc := json.NewEncoder(cmd.OutOrStdout())
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
return enc.Encode(out)
|
||||||
|
}
|
||||||
|
w := cmd.OutOrStdout()
|
||||||
|
for _, d := range devices {
|
||||||
|
id := d.ID
|
||||||
|
if len(id) > 12 {
|
||||||
|
id = id[:12]
|
||||||
|
}
|
||||||
|
rev := ""
|
||||||
|
if d.Revoked {
|
||||||
|
rev = " [revoked]"
|
||||||
|
}
|
||||||
|
lastSeen := "never"
|
||||||
|
if d.LastSeen > 0 {
|
||||||
|
lastSeen = time.Unix(d.LastSeen, 0).UTC().Format(time.RFC3339)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "%-12s %-20s %-20s %s%s\n", id, d.Name, d.Principal, lastSeen, rev)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
ls.Flags().StringVar(&data, "data", "./devbox-hub-data", "hub data directory")
|
||||||
|
ls.Flags().BoolVar(&asJSON, "json", false, "output as JSON")
|
||||||
|
cmd.AddCommand(ls)
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -255,6 +255,14 @@ func migrate(db *sql.DB, path string, preexisting bool) error {
|
||||||
// Close closes the database.
|
// Close closes the database.
|
||||||
func (d *DB) Close() error { return d.sql.Close() }
|
func (d *DB) Close() error { return d.sql.Close() }
|
||||||
|
|
||||||
|
// BackupTo writes a consistent snapshot of the live database to dest using
|
||||||
|
// VACUUM INTO (SQLite online backup: runs outside a transaction, WAL included).
|
||||||
|
// Same quoting pattern as the pre-migration backup in migrate().
|
||||||
|
func (d *DB) BackupTo(dest string) error {
|
||||||
|
_, err := d.sql.Exec(`VACUUM INTO '` + strings.ReplaceAll(dest, "'", "''") + `'`)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// --- devices -------------------------------------------------------------
|
// --- devices -------------------------------------------------------------
|
||||||
|
|
||||||
// AddDevice registers (or updates) a device by id.
|
// AddDevice registers (or updates) a device by id.
|
||||||
|
|
@ -855,6 +863,27 @@ func (d *DB) SnapshotIDs(share string) ([]string, error) {
|
||||||
return d.queryStrings(`SELECT id FROM snapshots WHERE share=?`, share)
|
return d.queryStrings(`SELECT id FROM snapshots WHERE share=?`, share)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SnapshotTimestamps returns id→created_at for all snapshots of a share.
|
||||||
|
// Used by GC's --keep-days: snapshots within the window are kept even when
|
||||||
|
// outside the --keep newest-N window.
|
||||||
|
func (d *DB) SnapshotTimestamps(share string) (map[string]int64, error) {
|
||||||
|
rows, err := d.sql.Query(`SELECT id, created_at FROM snapshots WHERE share=?`, share)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := make(map[string]int64)
|
||||||
|
for rows.Next() {
|
||||||
|
var id string
|
||||||
|
var ts int64
|
||||||
|
if err := rows.Scan(&id, &ts); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out[id] = ts
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
// --- dashboard reads ------------------------------------------------------
|
// --- dashboard reads ------------------------------------------------------
|
||||||
|
|
||||||
// DeviceRow is a device's detail for the dashboard.
|
// DeviceRow is a device's detail for the dashboard.
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func open(t *testing.T) *DB {
|
func open(t *testing.T) *DB {
|
||||||
|
|
@ -585,3 +586,61 @@ func TestMigrationFromV1WithData(t *testing.T) {
|
||||||
t.Fatalf("share t ids after new push = %v, want 2", ids)
|
t.Fatalf("share t ids after new push = %v, want 2", ids)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestBackupTo verifies that BackupTo produces a readable copy of the database
|
||||||
|
// that contains the same rows as the live DB.
|
||||||
|
func TestBackupTo(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
// Use a file-backed DB — VACUUM INTO doesn't work on :memory:.
|
||||||
|
db, err := Open(filepath.Join(dir, "live.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err := db.AddDevice("d1", "laptop", []byte("pub"), time.Now().Unix()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dest := filepath.Join(dir, "backup.db")
|
||||||
|
if err := db.BackupTo(dest); err != nil {
|
||||||
|
t.Fatalf("BackupTo: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(dest); err != nil {
|
||||||
|
t.Fatalf("backup file missing: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bak, err := Open(dest)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open backup: %v", err)
|
||||||
|
}
|
||||||
|
defer bak.Close()
|
||||||
|
n, err := bak.Count("devices")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("backup Count: %v", err)
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
t.Fatalf("backup has %d devices, want 1", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDeviceLsShowsDevice verifies that Devices() surfaces a joined device.
|
||||||
|
func TestDeviceLsShowsDevice(t *testing.T) {
|
||||||
|
db := open(t)
|
||||||
|
now := time.Now().Unix()
|
||||||
|
if err := db.AddDevice("d1", "laptop", []byte("pub"), now); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rows, err := db.Devices()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Devices: %v", err)
|
||||||
|
}
|
||||||
|
if len(rows) != 1 {
|
||||||
|
t.Fatalf("Devices returned %d rows, want 1", len(rows))
|
||||||
|
}
|
||||||
|
if rows[0].Name != "laptop" || rows[0].ID != "d1" {
|
||||||
|
t.Fatalf("unexpected row: %+v", rows[0])
|
||||||
|
}
|
||||||
|
if rows[0].Revoked {
|
||||||
|
t.Fatal("fresh device should not be revoked")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,11 +7,13 @@ import (
|
||||||
"crypto/ed25519"
|
"crypto/ed25519"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
@ -44,6 +46,8 @@ type Server struct {
|
||||||
publishMu sync.Mutex // serializes publish so the case-clash check + create is atomic
|
publishMu sync.Mutex // serializes publish so the case-clash check + create is atomic
|
||||||
version string // build version, surfaced at /healthz (set via SetVersion)
|
version string // build version, surfaced at /healthz (set via SetVersion)
|
||||||
|
|
||||||
|
metricsToken string // optional; "" = open (default, matches existing behaviour)
|
||||||
|
|
||||||
// Prometheus counters (monotonic). bytesIn/Out are the WAN signal now the hub
|
// Prometheus counters (monotonic). bytesIn/Out are the WAN signal now the hub
|
||||||
// is internet-reachable; pushes/conflicts show sync churn. Exposed at /metrics.
|
// is internet-reachable; pushes/conflicts show sync churn. Exposed at /metrics.
|
||||||
bytesIn atomic.Int64
|
bytesIn atomic.Int64
|
||||||
|
|
@ -60,6 +64,10 @@ func NewServer(db *meta.DB, store blobstore.Store) *Server {
|
||||||
// SetVersion records the build version for the /healthz response.
|
// SetVersion records the build version for the /healthz response.
|
||||||
func (s *Server) SetVersion(v string) *Server { s.version = v; return s }
|
func (s *Server) SetVersion(v string) *Server { s.version = v; return s }
|
||||||
|
|
||||||
|
// SetMetricsToken requires the given token to access /metrics. Empty = open (default).
|
||||||
|
// Mirror of the dashboard token pattern: accepts Authorization: Bearer or ?token=.
|
||||||
|
func (s *Server) SetMetricsToken(tok string) *Server { s.metricsToken = tok; return s }
|
||||||
|
|
||||||
// WithDashboard attaches a live dashboard so the hub emits flow events to it.
|
// WithDashboard attaches a live dashboard so the hub emits flow events to it.
|
||||||
func (s *Server) WithDashboard(d *dashboard.Dashboard) *Server { s.dash = d; return s }
|
func (s *Server) WithDashboard(d *dashboard.Dashboard) *Server { s.dash = d; return s }
|
||||||
|
|
||||||
|
|
@ -609,7 +617,20 @@ func (s *Server) handleMembers(w http.ResponseWriter, r *http.Request, _ string)
|
||||||
writeJSON(w, http.StatusOK, proto.MembersResponse{Legacy: mode != "explicit", Members: out})
|
writeJSON(w, http.StatusOK, proto.MembersResponse{Legacy: mode != "explicit", Members: out})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) handleMetrics(w http.ResponseWriter, _ *http.Request) {
|
func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if s.metricsToken != "" {
|
||||||
|
tok := r.URL.Query().Get("token")
|
||||||
|
if tok == "" {
|
||||||
|
const bp = "Bearer "
|
||||||
|
if h := r.Header.Get("Authorization"); strings.HasPrefix(h, bp) {
|
||||||
|
tok = h[len(bp):]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if subtle.ConstantTimeCompare([]byte(tok), []byte(s.metricsToken)) != 1 {
|
||||||
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
gauges := []struct {
|
gauges := []struct {
|
||||||
name, table, help string
|
name, table, help string
|
||||||
}{
|
}{
|
||||||
|
|
@ -682,3 +703,36 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||||
func writeErr(w http.ResponseWriter, status int, msg string) {
|
func writeErr(w http.ResponseWriter, status int, msg string) {
|
||||||
writeJSON(w, status, proto.Error{Error: msg})
|
writeJSON(w, status, proto.Error{Error: msg})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// loggingResponseWriter captures the status code and response bytes for the
|
||||||
|
// access log. Defaults to 200 so a handler that never calls WriteHeader is
|
||||||
|
// counted correctly.
|
||||||
|
type loggingResponseWriter struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
bytes int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lw *loggingResponseWriter) WriteHeader(status int) {
|
||||||
|
lw.status = status
|
||||||
|
lw.ResponseWriter.WriteHeader(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lw *loggingResponseWriter) Write(b []byte) (int, error) {
|
||||||
|
n, err := lw.ResponseWriter.Write(b)
|
||||||
|
lw.bytes += n
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccessLogMiddleware wraps h and logs one line per request via stdlib log:
|
||||||
|
// method, path, status, bytes, remote addr, duration. Default off; enabled by
|
||||||
|
// the --access-log serve flag.
|
||||||
|
func AccessLogMiddleware(h http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
start := time.Now()
|
||||||
|
lw := &loggingResponseWriter{ResponseWriter: w, status: http.StatusOK}
|
||||||
|
h.ServeHTTP(lw, r)
|
||||||
|
log.Printf("%s %s %d %d %s %s",
|
||||||
|
r.Method, r.URL.Path, lw.status, lw.bytes, r.RemoteAddr, time.Since(start))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -527,3 +527,65 @@ func TestHubAuthAndHashErrors(t *testing.T) {
|
||||||
t.Fatalf("mismatched blob status = %d, want 400", status)
|
t.Fatalf("mismatched blob status = %d, want 400", status)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestMetricsAuth verifies that /metrics returns 401 when a token is set and
|
||||||
|
// the request carries no token, and 200 on correct Authorization: Bearer or
|
||||||
|
// ?token= presentation.
|
||||||
|
func TestMetricsAuth(t *testing.T) {
|
||||||
|
db, err := meta.Open(":memory:")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("meta.Open: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { db.Close() })
|
||||||
|
store, err := blobstore.NewDisk(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewDisk: %v", err)
|
||||||
|
}
|
||||||
|
const tok = "secret-metrics-token"
|
||||||
|
srv := httptest.NewServer(NewServer(db, store).SetMetricsToken(tok).Handler())
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
|
||||||
|
// No token → 401.
|
||||||
|
if status, _ := do(t, "GET", srv.URL+proto.PathMetrics, "", nil); status != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("no token: status = %d, want 401", status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrong token via Bearer → 401.
|
||||||
|
if status, _ := do(t, "GET", srv.URL+proto.PathMetrics, "wrong-token", nil); status != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("wrong bearer: status = %d, want 401", status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct token via Authorization: Bearer → 200.
|
||||||
|
if status, _ := do(t, "GET", srv.URL+proto.PathMetrics, tok, nil); status != http.StatusOK {
|
||||||
|
t.Fatalf("correct bearer: status = %d, want 200", status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct token via ?token= query param → 200.
|
||||||
|
if status, _ := do(t, "GET", srv.URL+proto.PathMetrics+"?token="+tok, "", nil); status != http.StatusOK {
|
||||||
|
t.Fatalf("?token: status = %d, want 200", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMetricsOpenWhenNoToken verifies /metrics remains open when no token is configured.
|
||||||
|
func TestMetricsOpenWhenNoToken(t *testing.T) {
|
||||||
|
base, _ := testHub(t)
|
||||||
|
if status, _ := do(t, "GET", base+proto.PathMetrics, "", nil); status != http.StatusOK {
|
||||||
|
t.Fatalf("open metrics: status = %d, want 200", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAccessLogMiddleware verifies that the wrapper passes status and body through unchanged.
|
||||||
|
func TestAccessLogMiddleware(t *testing.T) {
|
||||||
|
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
w.Write([]byte("hello"))
|
||||||
|
})
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
AccessLogMiddleware(inner).ServeHTTP(rec, httptest.NewRequest("GET", "/test", nil))
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("code = %d, want 201", rec.Code)
|
||||||
|
}
|
||||||
|
if got := rec.Body.String(); got != "hello" {
|
||||||
|
t.Fatalf("body = %q, want 'hello'", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue