266 lines
7.5 KiB
Go
266 lines
7.5 KiB
Go
// realconn: lee logs de nginx/Apache, guarda las conexiones en RAM y las
|
|
// entrega por una API HTTP a un cliente web que las visualiza.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"embed"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"io/fs"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"runtime"
|
|
"runtime/debug"
|
|
"strconv"
|
|
"strings"
|
|
"sync/atomic"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
//go:embed web
|
|
var webFS embed.FS
|
|
|
|
var version = "dev"
|
|
|
|
type config struct {
|
|
logs []string
|
|
addr string
|
|
port int
|
|
maxConns int
|
|
maxMemMB int
|
|
minFree float64
|
|
fromStart bool
|
|
poll time.Duration
|
|
webDir string
|
|
noWeb bool
|
|
cors string
|
|
clientTTL time.Duration
|
|
maxClient int
|
|
}
|
|
|
|
func parseFlags() config {
|
|
var c config
|
|
var logs string
|
|
flag.StringVar(&logs, "log", "", "ruta del log de acceso nginx/Apache (varias separadas por coma) [obligatorio]")
|
|
flag.IntVar(&c.port, "port", 8080, "puerto del servidor web integrado")
|
|
flag.StringVar(&c.addr, "addr", "", "interfaz donde escuchar (vacío = todas)")
|
|
flag.IntVar(&c.maxConns, "max-conns", 50000, "máximo de conexiones guardadas en RAM; al llenarse se descartan las más antiguas")
|
|
flag.IntVar(&c.maxMemMB, "max-mem", 256, "límite de memoria del proceso en MB; al superarlo se descartan conexiones")
|
|
flag.Float64Var(&c.minFree, "min-free", 10, "%% mínimo de RAM libre del host; por debajo se descartan conexiones (Linux/Windows)")
|
|
flag.BoolVar(&c.fromStart, "from-start", false, "leer el log desde el inicio en vez de solo las líneas nuevas")
|
|
flag.DurationVar(&c.poll, "poll", 250*time.Millisecond, "intervalo de sondeo del archivo de log")
|
|
flag.StringVar(&c.webDir, "web", "", "servir el cliente desde este directorio en vez del embebido")
|
|
flag.BoolVar(&c.noWeb, "no-web", false, "no servir el cliente; solo la API")
|
|
flag.DurationVar(&c.clientTTL, "client-ttl", 30*time.Second, "tiempo sin consultas tras el cual se olvida a un cliente")
|
|
flag.IntVar(&c.maxClient, "max-clients", 1000, "máximo de clientes cuya posición se recuerda")
|
|
flag.StringVar(&c.cors, "cors", "*", "valor de Access-Control-Allow-Origin (vacío para desactivar)")
|
|
showVersion := flag.Bool("version", false, "mostrar versión y salir")
|
|
flag.Usage = func() {
|
|
fmt.Fprintf(flag.CommandLine.Output(), "realconn %s\n\nUso: realconn -log /var/log/nginx/access.log -port 8080 [opciones]\n\n", version)
|
|
flag.PrintDefaults()
|
|
}
|
|
flag.Parse()
|
|
if *showVersion {
|
|
fmt.Println("realconn", version)
|
|
os.Exit(0)
|
|
}
|
|
for _, p := range strings.Split(logs, ",") {
|
|
if p = strings.TrimSpace(p); p != "" {
|
|
c.logs = append(c.logs, p)
|
|
}
|
|
}
|
|
if len(c.logs) == 0 {
|
|
flag.Usage()
|
|
fmt.Fprintln(os.Stderr, "\nerror: falta -log")
|
|
os.Exit(2)
|
|
}
|
|
if c.port < 1 || c.port > 65535 {
|
|
fmt.Fprintln(os.Stderr, "error: -port inválido")
|
|
os.Exit(2)
|
|
}
|
|
return c
|
|
}
|
|
|
|
func main() {
|
|
cfg := parseFlags()
|
|
store := NewStore(cfg.maxConns, cfg.clientTTL, cfg.maxClient)
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
if cfg.maxMemMB > 0 {
|
|
// Límite blando para el GC; el guardián de memoria descarta datos si aun así se supera.
|
|
debug.SetMemoryLimit(int64(cfg.maxMemMB) << 20)
|
|
}
|
|
|
|
var bad atomic.Uint64
|
|
for _, p := range cfg.logs {
|
|
go Tail(ctx, p, cfg.fromStart, cfg.poll, func(line string) {
|
|
if line == "" {
|
|
return
|
|
}
|
|
if c, ok := ParseLine(line); ok {
|
|
store.Add(c)
|
|
} else {
|
|
if n := bad.Add(1); n <= 5 || n%1000 == 0 {
|
|
log.Printf("[parse] línea no reconocida (%d en total): %.120q", n, line)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
go memoryGuard(ctx, store, cfg)
|
|
|
|
srv := &http.Server{
|
|
Addr: fmt.Sprintf("%s:%d", cfg.addr, cfg.port),
|
|
Handler: routes(store, cfg),
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
}
|
|
go func() {
|
|
<-ctx.Done()
|
|
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
_ = srv.Shutdown(sctx)
|
|
}()
|
|
|
|
log.Printf("realconn %s escuchando en http://%s logs=%v max-conns=%d max-mem=%dMB min-free=%.0f%%",
|
|
version, displayAddr(cfg), cfg.logs, cfg.maxConns, cfg.maxMemMB, cfg.minFree)
|
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatal(err)
|
|
}
|
|
log.Println("detenido")
|
|
}
|
|
|
|
func displayAddr(c config) string {
|
|
h := c.addr
|
|
if h == "" {
|
|
h = "localhost"
|
|
}
|
|
return fmt.Sprintf("%s:%d", h, c.port)
|
|
}
|
|
|
|
// memoryGuard vigila la memoria del proceso y del host; si se agota,
|
|
// descarta la mitad de las conexiones pendientes más antiguas.
|
|
func memoryGuard(ctx context.Context, s *Store, cfg config) {
|
|
limit := uint64(cfg.maxMemMB) << 20
|
|
t := time.NewTicker(time.Second)
|
|
defer t.Stop()
|
|
var ms runtime.MemStats
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
}
|
|
s.Maintain() // expira clientes inactivos y libera lo ya leído por todos
|
|
reason := ""
|
|
if limit > 0 {
|
|
runtime.ReadMemStats(&ms)
|
|
if ms.HeapAlloc > limit {
|
|
reason = fmt.Sprintf("heap %dMB > %dMB", ms.HeapAlloc>>20, cfg.maxMemMB)
|
|
}
|
|
}
|
|
if reason == "" && cfg.minFree > 0 {
|
|
if avail, total, ok := hostMemory(); ok {
|
|
if pct := float64(avail) * 100 / float64(total); pct < cfg.minFree {
|
|
reason = fmt.Sprintf("RAM libre del host %.1f%% < %.0f%%", pct, cfg.minFree)
|
|
}
|
|
}
|
|
}
|
|
if reason != "" && s.Stats().Buffered > 0 {
|
|
n := s.DropOldest(0.5)
|
|
runtime.GC()
|
|
debug.FreeOSMemory()
|
|
log.Printf("[mem] %s: descartadas %d conexiones antiguas", reason, n)
|
|
}
|
|
}
|
|
}
|
|
|
|
func routes(s *Store, cfg config) http.Handler {
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/api/connections", func(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
limit, _ := strconv.Atoi(q.Get("limit"))
|
|
since := int64(-1)
|
|
if v := q.Get("since"); v != "" {
|
|
n, err := strconv.ParseInt(v, 10, 64)
|
|
if err != nil || n < 0 {
|
|
http.Error(w, "since inválido", http.StatusBadRequest)
|
|
return
|
|
}
|
|
since = n
|
|
}
|
|
client := q.Get("client")
|
|
if len(client) > 64 {
|
|
http.Error(w, "client demasiado largo (máx. 64)", http.StatusBadRequest)
|
|
return
|
|
}
|
|
res := s.Read(client, since, limit)
|
|
writeJSON(w, map[string]any{
|
|
"connections": res.Conns,
|
|
"count": len(res.Conns),
|
|
"next": res.Next,
|
|
"dropped": res.Dropped,
|
|
"pending": res.Pending,
|
|
"reset": res.Reset,
|
|
"server_time": time.Now(),
|
|
})
|
|
})
|
|
mux.HandleFunc("/api/stats", func(w http.ResponseWriter, r *http.Request) {
|
|
var ms runtime.MemStats
|
|
runtime.ReadMemStats(&ms)
|
|
writeJSON(w, map[string]any{
|
|
"store": s.Stats(),
|
|
"heap_mb": float64(ms.HeapAlloc) / (1 << 20),
|
|
"version": version,
|
|
"logs": cfg.logs,
|
|
})
|
|
})
|
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Write([]byte("ok"))
|
|
})
|
|
|
|
if !cfg.noWeb {
|
|
var static http.FileSystem
|
|
if cfg.webDir != "" {
|
|
static = http.Dir(cfg.webDir)
|
|
} else {
|
|
sub, _ := fs.Sub(webFS, "web")
|
|
static = http.FS(sub)
|
|
}
|
|
mux.Handle("/", http.FileServer(static))
|
|
}
|
|
|
|
return withHeaders(mux, cfg.cors)
|
|
}
|
|
|
|
func withHeaders(h http.Handler, cors string) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if cors != "" {
|
|
w.Header().Set("Access-Control-Allow-Origin", cors)
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
}
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
http.Error(w, "método no permitido", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
h.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|