A Tianji-style Websites section: a small tracking script, a public collection endpoint, and a page per website with visitors, page views, visits, bounce rate, a chart and top lists for pages, referrers, browsers, systems, devices, countries, languages and events. No cookies and no stored IP address or user agent. SANDBAR_TRUST_PROXY makes the client address come from the proxy. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
151 lines
4.8 KiB
Go
151 lines
4.8 KiB
Go
// Command sandbar is a self-hosted notification, monitoring, on-call and incident tool.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"git.veillax.com/Veillax/reef/dotenv"
|
|
"git.veillax.com/Veillax/reef/secretbox"
|
|
"git.veillax.com/Veillax/reef/selfupdate"
|
|
"git.veillax.com/Veillax/sandbar/internal/sandbar"
|
|
)
|
|
|
|
var version = "dev"
|
|
|
|
func env(k, def string) string {
|
|
if v := os.Getenv(k); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
func main() {
|
|
envFile := "./.env"
|
|
for i, a := range os.Args {
|
|
if (a == "-env" || a == "--env") && i+1 < len(os.Args) {
|
|
envFile = os.Args[i+1]
|
|
}
|
|
}
|
|
if _, err := dotenv.Load(envFile); err != nil {
|
|
log.Fatalf("reading %s: %v", envFile, err)
|
|
}
|
|
|
|
listen := flag.String("listen", env("SANDBAR_LISTEN", ":8090"), "address for the web UI, API and topics")
|
|
data := flag.String("data", env("SANDBAR_DATA", "./sandbar-data"), "directory for the database")
|
|
url := flag.String("url", env("SANDBAR_URL", ""), "public URL (used for links in notifications)")
|
|
flag.String("env", ".env", "file to read secrets and settings from")
|
|
autoUpdate := flag.Bool("auto-update", os.Getenv("SANDBAR_AUTO_UPDATE") == "1", "check for new releases every few hours and update and restart by itself (Linux and macOS, including Docker)")
|
|
genkey := flag.Bool("genkey", false, "print a new random SANDBAR_MASTER_KEY and exit")
|
|
showVersion := flag.Bool("version", false, "print the version and exit")
|
|
flag.Parse()
|
|
|
|
if *showVersion {
|
|
fmt.Println("sandbar", version)
|
|
return
|
|
}
|
|
if *genkey {
|
|
fmt.Println(secretbox.GenerateKey())
|
|
return
|
|
}
|
|
|
|
// In a container, an update lives on the data volume and takes over from the image.
|
|
sandbar.UseNewerOverlay(*data, version, log.Printf)
|
|
|
|
key, err := masterKey(*data)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
box, err := secretbox.New(key)
|
|
if err != nil {
|
|
log.Fatalf("SANDBAR_MASTER_KEY: %v", err)
|
|
}
|
|
st, err := sandbar.OpenStore(*data, box)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer st.Close()
|
|
|
|
var hs *http.Server
|
|
atoi := func(k string) int { n, _ := strconv.Atoi(os.Getenv(k)); return n }
|
|
var srv *sandbar.Server
|
|
srv = sandbar.New(sandbar.Options{
|
|
DataDir: *data,
|
|
URL: strings.TrimRight(*url, "/"),
|
|
MetricsToken: os.Getenv("SANDBAR_METRICS_TOKEN"),
|
|
MessageDays: atoi("SANDBAR_MESSAGE_DAYS"),
|
|
CheckDays: atoi("SANDBAR_CHECK_DAYS"),
|
|
HitDays: atoi("SANDBAR_ANALYTICS_DAYS"),
|
|
TrustProxy: os.Getenv("SANDBAR_TRUST_PROXY") == "1",
|
|
Version: version,
|
|
AutoUpdate: *autoUpdate,
|
|
UpdateServer: os.Getenv("SANDBAR_UPDATE_SERVER"),
|
|
UpdateRepo: os.Getenv("SANDBAR_UPDATE_REPO"),
|
|
Restart: func(exe string) error {
|
|
// Let go of the port and the database, then become the new binary. If that fails, exit
|
|
// so the container or service manager starts it again, now from the new file.
|
|
hs.Close()
|
|
srv.Close()
|
|
st.Close()
|
|
err := selfupdate.Restart(exe)
|
|
log.Printf("could not restart into %s, exiting: %v", exe, err)
|
|
os.Exit(1)
|
|
return err
|
|
},
|
|
SMTP: sandbar.SMTPConfig{Host: os.Getenv("SANDBAR_SMTP_HOST"), Port: os.Getenv("SANDBAR_SMTP_PORT"),
|
|
User: os.Getenv("SANDBAR_SMTP_USER"), Password: os.Getenv("SANDBAR_SMTP_PASSWORD"), From: env("SANDBAR_SMTP_FROM", "sandbar@localhost")},
|
|
}, st)
|
|
srv.BootstrapAdmin(os.Getenv("SANDBAR_ADMIN_EMAIL"), os.Getenv("SANDBAR_ADMIN_PASSWORD"))
|
|
srv.Start()
|
|
if *autoUpdate {
|
|
go srv.RunAutoUpdate(context.Background())
|
|
}
|
|
|
|
hs = &http.Server{Addr: *listen, Handler: srv.Handler(), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 2 * time.Minute}
|
|
go func() {
|
|
log.Printf("sandbar %s listening on %s", version, *listen)
|
|
if err := hs.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatal(err)
|
|
}
|
|
}()
|
|
sig := make(chan os.Signal, 1)
|
|
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
|
|
<-sig
|
|
srv.Close() // ends open subscriptions so Shutdown doesn't wait on them
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
hs.Shutdown(ctx)
|
|
}
|
|
|
|
// masterKey returns SANDBAR_MASTER_KEY, or generates one into <data>/master.key so
|
|
// it works out of the box (move it into .env so a backup of the folder doesn't carry it).
|
|
func masterKey(dir string) (string, error) {
|
|
if k := strings.TrimSpace(os.Getenv("SANDBAR_MASTER_KEY")); k != "" {
|
|
return k, nil
|
|
}
|
|
p := filepath.Join(dir, "master.key")
|
|
if b, err := os.ReadFile(p); err == nil {
|
|
return strings.TrimSpace(string(b)), nil
|
|
}
|
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
return "", err
|
|
}
|
|
k := secretbox.GenerateKey()
|
|
if err := os.WriteFile(p, []byte(k+"\n"), 0o600); err != nil {
|
|
return "", err
|
|
}
|
|
log.Printf("generated %s; copy it into .env as SANDBAR_MASTER_KEY and delete the file. Back it up: without it, saved secrets can't be recovered", p)
|
|
return k, nil
|
|
}
|