diff --git a/README.md b/README.md index 70d0750..9a97b38 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,114 @@ -# RealConn +# realconn -Permite ver conexiones en tiempo real de Nginx y Apache \ No newline at end of file +Visualizador de conexiones en tiempo real. Tiene dos partes: + +1. **Servidor (Go)**: sigue el log de acceso de nginx o Apache, guarda las conexiones en RAM y las entrega por una API HTTP. +2. **Cliente (HTML5 + JS)**: muestra cada conexión como un misil que cae desde un mapa del mundo hacia un servidor rack detallado, con la IP debajo y, bajo ella, el navegador y el sistema operativo. Al impactar hay explosión de partículas en WebGL. + +## Compilar + +```sh +./build.sh # todos los destinos → ./dist +TARGETS="windows/amd64" ./build.sh # solo uno +go build -o realconn . # sistema actual +``` + +Destinos por defecto: linux (amd64/arm64/arm), windows (amd64/arm64), darwin (amd64/arm64) y freebsd/amd64. +El cliente va embebido en el binario, así que no hace falta copiar archivos. + +## Uso + +```sh +realconn -log /var/log/nginx/access.log -port 8080 +realconn.exe -log "C:\Apache24\logs\access.log" -port 8080 +``` + +Después abre `http://servidor:8080/`. + +| Parámetro | Por defecto | Descripción | +|----------------|-------------|-------------| +| `-log` | (obligatorio) | Ruta del log. Admite varias separadas por coma. | +| `-port` | `8080` | Puerto del servidor web integrado. | +| `-addr` | (todas) | Interfaz donde escuchar, por ejemplo `127.0.0.1`. | +| `-max-conns` | `50000` | Máximo de conexiones guardadas en RAM. Al llenarse se descartan las más antiguas. | +| `-max-mem` | `256` | Límite de memoria del proceso (MB). Si se supera, se descarta la mitad más antigua. | +| `-min-free` | `10` | % mínimo de RAM libre del host (Linux/Windows). Por debajo se descarta la mitad más antigua. | +| `-from-start` | `false` | Leer el log desde el principio en lugar de solo las líneas nuevas. | +| `-poll` | `250ms` | Frecuencia con que se revisa el archivo. | +| `-web` | (embebido) | Servir el cliente desde un directorio, útil para editar `web/index.html` sin recompilar. | +| `-no-web` | `false` | Servir solo la API. | +| `-client-ttl` | `30s` | Tiempo sin consultas tras el cual se olvida a un cliente y se deja de retener memoria por él. | +| `-max-clients` | `1000` | Máximo de clientes cuya posición se recuerda. Si se supera, se olvida al más inactivo. | +| `-cors` | `*` | Valor de `Access-Control-Allow-Origin`. | + +El lector usa sondeo, así que funciona igual en todos los sistemas. Detecta la rotación del log (logrotate) y el truncado. +Formato soportado: `combined` o `common`, el predeterminado de nginx y Apache. + +### Gestión de memoria y varios clientes + +Cada conexión leída recibe un número de secuencia (1, 2, 3…) y se guarda en un búfer circular de tamaño fijo (`-max-conns`). +Cada cliente consulta desde su propia posición (`since`), así que **varios navegadores ven todas las conexiones** sin quitárselas entre sí. + +La RAM se libera así: + +1. **Ya leídas por todos**: el servidor recuerda la posición de cada cliente activo y libera las conexiones que ya entregó a todos. +2. **Clientes inactivos**: un cliente que no consulta en `-client-ttl` se olvida, así que deja de retener memoria. +3. **Búfer lleno**: si nadie consulta o un cliente va muy atrasado, se sobrescriben las más antiguas. +4. **Vigilante de memoria**: cada segundo revisa la memoria del proceso (`-max-mem`) y la RAM libre del host (`-min-free`). Si alguna se agota, descarta la mitad más antigua y devuelve la memoria al sistema operativo. + +Cada cliente recibe en `dropped` cuántas conexiones se perdió por los casos 3 y 4. + +## API + +`GET /api/connections?client=&since=[&limit=N]` + +- `client`: identificador del cliente (máx. 64 caracteres). El cliente web genera uno aleatorio por pestaña. Sin `client`, la lectura es anónima: no se registra ni libera memoria. +- `since`: última secuencia recibida, que es el `next` de la respuesta anterior. Si se omite, se usa la posición que el servidor recuerda del cliente; un cliente nuevo empieza en vivo. `since=0` entrega todo lo que haya guardado. +- `limit`: máximo de conexiones por respuesta. El resto queda en `pending`. + +```json +{ + "connections": [ + {"ip":"203.0.113.7","time":"2026-11-02T10:00:01Z","method":"GET","path":"/","status":200,"bytes":512,"ua":"curl/8"} + ], + "count": 1, "next": 1842, "dropped": 0, "pending": 0, "reset": false, "server_time": "…" +} +``` + +`reset: true` indica que el `since` enviado era mayor que la última secuencia, por ejemplo porque el servidor se reinició. En ese caso el cursor se reajusta a `next`. + +`GET /api/stats`: estadísticas (conexiones guardadas, liberadas, descartadas y clientes activos). `GET /healthz`: devuelve `ok`. + +## Cliente + +El archivo es `web/index.html`. La URL de la API se define al inicio del script: + +```js +const CONFIG = { + API_URL: "api/connections", // <<< URL DE LA API + ... +``` + +También se puede indicar por parámetro en la URL, lo que es útil en un iframe: + +```html + +``` + +Parámetros: `api`, `interval` (ms), `labels=0` (ocultar IPs), `ua=0` (ocultar navegador/SO), `hud=0` (ocultar marcador), `map=`, `server=` y `demo=1` (datos simulados, sin API). + +Bajo cada IP se muestra el navegador y el sistema operativo, deducidos del campo `ua` (por ejemplo `Chrome 130 · Windows 10/11`, `Safari 18.1 · iOS 18.1`, `Googlebot · bot`, `curl 8 · script`). + +El servidor es un único equipo rack que reacciona a las conexiones: + +- **Bahías de discos**: cada impacto enciende el LED de actividad (verde) de la bahía bajo el punto de impacto. El LED de estado se pone ámbar con 4xx y rojo parpadeante con 5xx. +- **LEDs del panel**: PWR, NET (actividad de red), HDD (actividad de disco) y ERR (errores 5xx recientes). +- **Pantalla LCD**: conexiones por segundo, total recibidas y las últimas conexiones con IP, código y navegador/SO. +- **Ventiladores**: giran más rápido cuanto mayor es la carga. +- **Puertos de red**: LED de enlace y de actividad en cada puerto. + +Con `server=` se sustituye el dibujo por una imagen propia. + +Colores por código de estado: verde 2xx, azul 3xx, amarillo 4xx, rojo 5xx. +Las partículas se calculan en la GPU: la trayectoria se resuelve en el vertex shader. Si el navegador no tiene WebGL, hay una alternativa en canvas 2D. diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..df2a534 --- /dev/null +++ b/build.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env sh +# Compila realconn para varios sistemas operativos en ./dist +set -e +VERSION=${VERSION:-$(date +%Y.%m.%d)} +TARGETS=${TARGETS:-"linux/amd64 linux/arm64 linux/arm windows/amd64 windows/arm64 darwin/amd64 darwin/arm64 freebsd/amd64"} +mkdir -p dist +for t in $TARGETS; do + os=${t%/*}; arch=${t#*/} + out="dist/realconn-$os-$arch"; [ "$os" = windows ] && out="$out.exe" + echo "-> $out" + CGO_ENABLED=0 GOOS=$os GOARCH=$arch go build -trimpath -ldflags "-s -w -X main.version=$VERSION" -o "$out" . +done diff --git a/dist/realconn-darwin-amd64 b/dist/realconn-darwin-amd64 new file mode 100755 index 0000000..fb05282 Binary files /dev/null and b/dist/realconn-darwin-amd64 differ diff --git a/dist/realconn-darwin-arm64 b/dist/realconn-darwin-arm64 new file mode 100755 index 0000000..acb48d4 Binary files /dev/null and b/dist/realconn-darwin-arm64 differ diff --git a/dist/realconn-freebsd-amd64 b/dist/realconn-freebsd-amd64 new file mode 100755 index 0000000..d5c5bfd Binary files /dev/null and b/dist/realconn-freebsd-amd64 differ diff --git a/dist/realconn-linux-amd64 b/dist/realconn-linux-amd64 new file mode 100755 index 0000000..038e283 Binary files /dev/null and b/dist/realconn-linux-amd64 differ diff --git a/dist/realconn-linux-arm b/dist/realconn-linux-arm new file mode 100755 index 0000000..87ff027 Binary files /dev/null and b/dist/realconn-linux-arm differ diff --git a/dist/realconn-linux-arm64 b/dist/realconn-linux-arm64 new file mode 100755 index 0000000..5a7e947 Binary files /dev/null and b/dist/realconn-linux-arm64 differ diff --git a/dist/realconn-windows-amd64.exe b/dist/realconn-windows-amd64.exe new file mode 100755 index 0000000..150da77 Binary files /dev/null and b/dist/realconn-windows-amd64.exe differ diff --git a/dist/realconn-windows-arm64.exe b/dist/realconn-windows-arm64.exe new file mode 100755 index 0000000..6ac14f1 Binary files /dev/null and b/dist/realconn-windows-arm64.exe differ diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a8c5307 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module realconn + +go 1.21 diff --git a/main.go b/main.go new file mode 100644 index 0000000..fdaafba --- /dev/null +++ b/main.go @@ -0,0 +1,265 @@ +// 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) +} diff --git a/mem_linux.go b/mem_linux.go new file mode 100644 index 0000000..5de1c88 --- /dev/null +++ b/mem_linux.go @@ -0,0 +1,37 @@ +//go:build linux + +package main + +import ( + "bufio" + "os" + "strconv" + "strings" +) + +// hostMemory devuelve memoria disponible y total del host en bytes. +func hostMemory() (avail, total uint64, ok bool) { + f, err := os.Open("/proc/meminfo") + if err != nil { + return 0, 0, false + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + fields := strings.Fields(sc.Text()) + if len(fields) < 2 { + continue + } + v, err := strconv.ParseUint(fields[1], 10, 64) + if err != nil { + continue + } + switch fields[0] { + case "MemTotal:": + total = v * 1024 + case "MemAvailable:": + avail = v * 1024 + } + } + return avail, total, total > 0 && avail > 0 +} diff --git a/mem_other.go b/mem_other.go new file mode 100644 index 0000000..1ffd866 --- /dev/null +++ b/mem_other.go @@ -0,0 +1,7 @@ +//go:build !linux && !windows + +package main + +// En otros sistemas no se consulta la RAM del host; solo se aplican +// los límites -max-conns y -max-mem del propio proceso. +func hostMemory() (avail, total uint64, ok bool) { return 0, 0, false } diff --git a/mem_windows.go b/mem_windows.go new file mode 100644 index 0000000..3a54f8b --- /dev/null +++ b/mem_windows.go @@ -0,0 +1,33 @@ +//go:build windows + +package main + +import ( + "syscall" + "unsafe" +) + +type memoryStatusEx struct { + Length uint32 + MemoryLoad uint32 + TotalPhys uint64 + AvailPhys uint64 + TotalPageFile uint64 + AvailPageFile uint64 + TotalVirtual uint64 + AvailVirtual uint64 + AvailExtendedVirtual uint64 +} + +var procGlobalMemoryStatusEx = syscall.NewLazyDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx") + +// hostMemory devuelve memoria disponible y total del host en bytes. +func hostMemory() (avail, total uint64, ok bool) { + var m memoryStatusEx + m.Length = uint32(unsafe.Sizeof(m)) + r, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&m))) + if r == 0 { + return 0, 0, false + } + return m.AvailPhys, m.TotalPhys, m.TotalPhys > 0 +} diff --git a/parser.go b/parser.go new file mode 100644 index 0000000..8d6590f --- /dev/null +++ b/parser.go @@ -0,0 +1,55 @@ +package main + +import ( + "regexp" + "strconv" + "strings" + "time" +) + +// Formato "combined" / "common" compartido por nginx y Apache: +// 1.2.3.4 - user [10/Oct/2000:13:55:36 -0700] "GET /x HTTP/1.1" 200 2326 "ref" "ua" +var logRe = regexp.MustCompile( + `^(\S+) \S+ \S+ \[([^\]]+)\] "((?:[^"\\]|\\.)*)" (\d{3}) (\S+)(?: "((?:[^"\\]|\\.)*)" "((?:[^"\\]|\\.)*)")?`) + +const ( + maxPathLen = 256 + maxUALen = 200 +) + +func clip(s string, n int) string { + if len(s) > n { + s = s[:n] + } + // Clone para no retener la línea completa en memoria. + return strings.Clone(s) +} + +// ParseLine interpreta una línea de log. ok=false si no coincide con el formato. +func ParseLine(line string) (c Conn, ok bool) { + m := logRe.FindStringSubmatch(line) + if m == nil { + return c, false + } + c.IP = clip(m[1], 64) + if t, err := time.Parse("02/Jan/2006:15:04:05 -0700", m[2]); err == nil { + c.Time = t + } else { + c.Time = time.Now() + } + req := strings.SplitN(m[3], " ", 3) + if len(req) >= 2 { + c.Method = clip(req[0], 16) + c.Path = clip(req[1], maxPathLen) + } else { + c.Path = clip(m[3], maxPathLen) + } + c.Status, _ = strconv.Atoi(m[4]) + if m[5] != "-" { + c.Bytes, _ = strconv.ParseInt(m[5], 10, 64) + } + if len(m) > 7 && m[7] != "" && m[7] != "-" { + c.UA = clip(m[7], maxUALen) + } + return c, true +} diff --git a/store.go b/store.go new file mode 100644 index 0000000..35337e5 --- /dev/null +++ b/store.go @@ -0,0 +1,251 @@ +package main + +import ( + "sync" + "time" +) + +// Conn es una conexión detectada en el log. +type Conn struct { + IP string `json:"ip"` + Time time.Time `json:"time"` + Method string `json:"method,omitempty"` + Path string `json:"path,omitempty"` + Status int `json:"status"` + Bytes int64 `json:"bytes"` + UA string `json:"ua,omitempty"` +} + +type clientState struct { + cursor uint64 // última secuencia entregada + seen time.Time +} + +// Store es un búfer circular en RAM donde cada conexión tiene un número de +// secuencia creciente (1, 2, 3…). Cada cliente lee a partir de su propia +// posición, así que las lecturas no se roban datos entre sí. +// +// La memoria se libera de tres formas: +// - las conexiones que ya leyeron todos los clientes activos se eliminan; +// - si el búfer se llena, se sobrescriben las más antiguas; +// - el vigilante de memoria puede descartar las más antiguas (DropOldest). +type Store struct { + mu sync.Mutex + buf []Conn + head int // índice del elemento más antiguo + size int + + total uint64 // secuencia de la última conexión (= leídas desde el arranque) + droppedTotal uint64 // descartadas antes de que todos los clientes las leyeran + released uint64 // liberadas porque todos los clientes ya las leyeron + served uint64 // conexiones entregadas (sumando todos los clientes) + + clients map[string]*clientState + clientTTL time.Duration + maxClients int +} + +func NewStore(capacity int, clientTTL time.Duration, maxClients int) *Store { + if capacity < 1 { + capacity = 1 + } + if maxClients < 1 { + maxClients = 1 + } + return &Store{ + buf: make([]Conn, capacity), + clients: make(map[string]*clientState), + clientTTL: clientTTL, + maxClients: maxClients, + } +} + +// firstSeq devuelve la secuencia del elemento más antiguo (total+1 si está vacío). +func (s *Store) firstSeq() uint64 { return s.total - uint64(s.size) + 1 } + +func (s *Store) Add(c Conn) { + s.mu.Lock() + defer s.mu.Unlock() + n := len(s.buf) + if s.size == n { // lleno: se pierde el más antiguo + s.buf[s.head] = Conn{} + s.head = (s.head + 1) % n + s.size-- + s.droppedTotal++ + } + s.buf[(s.head+s.size)%n] = c + s.size++ + s.total++ +} + +// ReadResult es la respuesta de Read. +type ReadResult struct { + Conns []Conn + Next uint64 // cursor que el cliente debe enviar como since la próxima vez + Dropped uint64 // conexiones que este cliente se perdió por descarte + Pending uint64 // conexiones que siguen disponibles después de Next + Reset bool // el cursor del cliente no era válido (p. ej. el servidor se reinició) +} + +// Read entrega a un cliente las conexiones posteriores a su cursor. +// - since >= 0: posición indicada por el cliente. +// - since < 0: se usa la posición recordada del cliente; si es nuevo, +// empieza en vivo (solo recibirá conexiones nuevas). +// +// clientID vacío = lectura anónima: no se registra ni libera memoria. +func (s *Store) Read(clientID string, since int64, limit int) ReadResult { + s.mu.Lock() + defer s.mu.Unlock() + now := time.Now() + last := s.total + first := s.firstSeq() + + var res ReadResult + var cur uint64 + switch { + case since >= 0: + cur = uint64(since) + case clientID != "" && s.clients[clientID] != nil: + cur = s.clients[clientID].cursor + default: + cur = last // cliente nuevo: en vivo + } + if cur > last { + cur = last + res.Reset = true + } + if cur+1 < first { + res.Dropped = first - 1 - cur + cur = first - 1 + } + + k := last - cur + if limit > 0 && k > uint64(limit) { + k = uint64(limit) + } + res.Conns = make([]Conn, k) + n := len(s.buf) + start := s.head + int(cur+1-first) + for i := 0; i < int(k); i++ { + res.Conns[i] = s.buf[(start+i)%n] + } + res.Next = cur + k + res.Pending = last - res.Next + s.served += k + + if clientID != "" { + cs := s.clients[clientID] + if cs == nil { + if len(s.clients) >= s.maxClients { + s.evictOldestClientLocked() + } + cs = &clientState{} + s.clients[clientID] = cs + } + cs.cursor = res.Next + cs.seen = now + s.releaseLocked(now) + } + return res +} + +func (s *Store) evictOldestClientLocked() { + var oldID string + var oldT time.Time + for id, c := range s.clients { + if oldID == "" || c.seen.Before(oldT) { + oldID, oldT = id, c.seen + } + } + delete(s.clients, oldID) +} + +// releaseLocked olvida a los clientes inactivos y libera las conexiones que +// todos los clientes activos ya recibieron. +func (s *Store) releaseLocked(now time.Time) { + if len(s.clients) == 0 { + return + } + minCur := s.total + for id, c := range s.clients { + if now.Sub(c.seen) > s.clientTTL { + delete(s.clients, id) + continue + } + if c.cursor < minCur { + minCur = c.cursor + } + } + if len(s.clients) == 0 { + return // sin clientes: se conserva hasta que el búfer se llene + } + first := s.firstSeq() + if minCur < first { + return + } + k := int(minCur - first + 1) + if k > s.size { + k = s.size + } + n := len(s.buf) + for i := 0; i < k; i++ { + s.buf[(s.head+i)%n] = Conn{} + } + s.head = (s.head + k) % n + s.size -= k + s.released += uint64(k) +} + +// Maintain se llama periódicamente para expirar clientes y liberar memoria +// aunque nadie esté consultando. +func (s *Store) Maintain() { + s.mu.Lock() + defer s.mu.Unlock() + s.releaseLocked(time.Now()) +} + +// DropOldest descarta una fracción (0..1] de las conexiones guardadas. +func (s *Store) DropOldest(frac float64) int { + s.mu.Lock() + defer s.mu.Unlock() + k := int(float64(s.size) * frac) + if k < 1 && s.size > 0 { + k = 1 + } + n := len(s.buf) + for i := 0; i < k; i++ { + s.buf[(s.head+i)%n] = Conn{} + } + s.head = (s.head + k) % n + s.size -= k + s.droppedTotal += uint64(k) + return k +} + +type Stats struct { + Buffered int `json:"buffered"` + Capacity int `json:"capacity"` + FirstSeq uint64 `json:"first_seq"` + LastSeq uint64 `json:"last_seq"` + Total uint64 `json:"total"` + Served uint64 `json:"served"` + Released uint64 `json:"released"` + DroppedTotal uint64 `json:"dropped_total"` + Clients int `json:"clients"` +} + +func (s *Store) Stats() Stats { + s.mu.Lock() + defer s.mu.Unlock() + return Stats{ + Buffered: s.size, + Capacity: len(s.buf), + FirstSeq: s.firstSeq(), + LastSeq: s.total, + Total: s.total, + Served: s.served, + Released: s.released, + DroppedTotal: s.droppedTotal, + Clients: len(s.clients), + } +} diff --git a/store_test.go b/store_test.go new file mode 100644 index 0000000..b701617 --- /dev/null +++ b/store_test.go @@ -0,0 +1,142 @@ +package main + +import ( + "fmt" + "testing" + "time" +) + +func add(s *Store, n int, from int) { + for i := 0; i < n; i++ { + s.Add(Conn{IP: fmt.Sprintf("10.0.0.%d", from+i)}) + } +} + +func ips(cs []Conn) []string { + out := make([]string, len(cs)) + for i, c := range cs { + out[i] = c.IP + } + return out +} + +func TestClientsDoNotStealFromEachOther(t *testing.T) { + s := NewStore(100, time.Minute, 10) + // ambos se registran (empiezan en vivo) + if r := s.Read("a", -1, 0); len(r.Conns) != 0 || r.Next != 0 { + t.Fatalf("cliente nuevo debería empezar vacío: %+v", r) + } + s.Read("b", -1, 0) + add(s, 3, 1) + + ra := s.Read("a", -1, 0) + rb := s.Read("b", -1, 0) + if len(ra.Conns) != 3 || len(rb.Conns) != 3 { + t.Fatalf("ambos deben recibir 3: a=%v b=%v", ips(ra.Conns), ips(rb.Conns)) + } + if ra.Next != 3 || rb.Next != 3 { + t.Fatalf("next esperado 3: %d %d", ra.Next, rb.Next) + } + // ya los leyeron todos: se liberan + if st := s.Stats(); st.Buffered != 0 || st.Released != 3 { + t.Fatalf("deberían liberarse: %+v", st) + } +} + +func TestSlowClientPinsDataUntilRead(t *testing.T) { + s := NewStore(100, time.Minute, 10) + s.Read("fast", -1, 0) + s.Read("slow", -1, 0) + add(s, 5, 1) + s.Read("fast", -1, 0) + if st := s.Stats(); st.Buffered != 5 { + t.Fatalf("el lento aún no lee; deben quedar 5: %+v", st) + } + r := s.Read("slow", 2, 0) // cursor explícito + if got := ips(r.Conns); len(got) != 3 || got[0] != "10.0.0.3" { + t.Fatalf("desde since=2 esperaba 3..5, obtuve %v", got) + } + if st := s.Stats(); st.Buffered != 0 { + t.Fatalf("todo leído, debería liberarse: %+v", st) + } +} + +func TestOverflowReportsDropsPerClient(t *testing.T) { + s := NewStore(5, time.Minute, 10) + s.Read("a", -1, 0) + add(s, 12, 1) + r := s.Read("a", -1, 0) + if r.Dropped != 7 || len(r.Conns) != 5 || r.Conns[0].IP != "10.0.0.8" || r.Next != 12 { + t.Fatalf("overflow incorrecto: dropped=%d next=%d %v", r.Dropped, r.Next, ips(r.Conns)) + } +} + +func TestLimitAndPending(t *testing.T) { + s := NewStore(100, time.Minute, 10) + s.Read("a", -1, 0) + add(s, 10, 1) + r := s.Read("a", -1, 4) + if len(r.Conns) != 4 || r.Next != 4 || r.Pending != 6 { + t.Fatalf("limit: %+v", r) + } + if st := s.Stats(); st.Buffered != 6 { + t.Fatalf("solo deben liberarse las 4 leídas: %+v", st) + } +} + +func TestResetWhenCursorFromFuture(t *testing.T) { + s := NewStore(100, time.Minute, 10) + add(s, 3, 1) + r := s.Read("a", 999, 0) // p. ej. el servidor se reinició + if !r.Reset || r.Next != 3 || len(r.Conns) != 0 { + t.Fatalf("reset esperado: %+v", r) + } +} + +func TestInactiveClientExpires(t *testing.T) { + s := NewStore(100, 10*time.Millisecond, 10) + s.Read("gone", -1, 0) + s.Read("live", -1, 0) + add(s, 4, 1) + time.Sleep(20 * time.Millisecond) + s.Read("live", -1, 0) // "gone" expiró: ya no retiene memoria + if st := s.Stats(); st.Buffered != 0 || st.Clients != 1 { + t.Fatalf("el cliente inactivo debería expirar: %+v", st) + } +} + +func TestNoClientsKeepsData(t *testing.T) { + s := NewStore(100, time.Minute, 10) + add(s, 4, 1) + s.Read("", 0, 0) // lectura anónima: no libera + s.Maintain() + if st := s.Stats(); st.Buffered != 4 { + t.Fatalf("sin clientes registrados no debe liberar: %+v", st) + } + if r := s.Read("nuevo", 0, 0); len(r.Conns) != 4 { + t.Fatalf("since=0 debe entregar todo lo guardado: %v", ips(r.Conns)) + } +} + +func TestMaxClientsEvictsOldest(t *testing.T) { + s := NewStore(100, time.Minute, 2) + s.Read("a", -1, 0) + time.Sleep(time.Millisecond) + s.Read("b", -1, 0) + time.Sleep(time.Millisecond) + s.Read("c", -1, 0) + if st := s.Stats(); st.Clients != 2 { + t.Fatalf("máximo 2 clientes: %+v", st) + } +} + +func TestDropOldestThenRead(t *testing.T) { + s := NewStore(100, time.Minute, 10) + s.Read("a", -1, 0) + add(s, 10, 1) + s.DropOldest(0.5) + r := s.Read("a", -1, 0) + if r.Dropped != 5 || len(r.Conns) != 5 || r.Conns[0].IP != "10.0.0.6" { + t.Fatalf("drop: %+v %v", r.Dropped, ips(r.Conns)) + } +} diff --git a/tail.go b/tail.go new file mode 100644 index 0000000..1acf8b8 --- /dev/null +++ b/tail.go @@ -0,0 +1,142 @@ +package main + +import ( + "bufio" + "context" + "errors" + "io" + "log" + "os" + "time" +) + +const maxLineLen = 64 * 1024 + +// Tail sigue un archivo por sondeo (funciona igual en Windows, Linux y macOS). +// Detecta rotación (archivo reemplazado) y truncado, y llama a emit por línea. +func Tail(ctx context.Context, path string, fromStart bool, poll time.Duration, emit func(string)) { + first := true + for ctx.Err() == nil { + f, err := os.Open(path) + if err != nil { + if first { + log.Printf("[tail] no se puede abrir %s: %v (reintentando)", path, err) + } + first = false + if !sleepCtx(ctx, time.Second) { + return + } + continue + } + start := !first || fromStart + first = false + err = follow(ctx, f, path, start, poll, emit) + f.Close() + if err != nil && ctx.Err() == nil { + log.Printf("[tail] %s: %v; reabriendo", path, err) + } + } +} + +var errRotated = errors.New("archivo rotado") + +func follow(ctx context.Context, f *os.File, path string, fromStart bool, poll time.Duration, emit func(string)) error { + var offset int64 + if !fromStart { + off, err := f.Seek(0, io.SeekEnd) + if err != nil { + return err + } + offset = off + } + openedInfo, err := f.Stat() + if err != nil { + return err + } + log.Printf("[tail] siguiendo %s desde el byte %d", path, offset) + + r := bufio.NewReaderSize(f, maxLineLen) + var partial []byte + skipping := false + + readAvailable := func() error { + for { + chunk, err := r.ReadSlice('\n') + offset += int64(len(chunk)) + switch { + case err == nil: + if skipping { // final de una línea demasiado larga + skipping = false + partial = partial[:0] + continue + } + line := chunk + if len(partial) > 0 { + partial = append(partial, chunk...) + line = partial + } + emit(string(trimEOL(line))) + partial = partial[:0] + case errors.Is(err, bufio.ErrBufferFull): + skipping = true + partial = partial[:0] + case err == io.EOF: + if !skipping { + partial = append(partial, chunk...) + if len(partial) > maxLineLen { + skipping = true + partial = partial[:0] + } + } + return nil + default: + return err + } + } + } + + for { + if err := readAvailable(); err != nil { + return err + } + if !sleepCtx(ctx, poll) { + return nil + } + fi, err := os.Stat(path) + if err != nil { + continue // puede estar en plena rotación + } + if !os.SameFile(openedInfo, fi) { + _ = readAvailable() // lo que quede en el archivo viejo + return errRotated + } + if fi.Size() < offset { // truncado + log.Printf("[tail] %s truncado; leyendo desde el inicio", path) + if _, err := f.Seek(0, io.SeekStart); err != nil { + return err + } + offset = 0 + r.Reset(f) + partial = partial[:0] + skipping = false + } + } +} + +func trimEOL(b []byte) []byte { + for len(b) > 0 && (b[len(b)-1] == '\n' || b[len(b)-1] == '\r') { + b = b[:len(b)-1] + } + return b +} + +func sleepCtx(ctx context.Context, d time.Duration) bool { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return false + case <-t.C: + return true + } +} diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..e619bac --- /dev/null +++ b/web/index.html @@ -0,0 +1,1021 @@ + + + + + +realconn · conexiones en vivo + + + +
+ + + +
+ +
+
SCORE0
+
CICLO+0
+
EN VUELO0
+
IMPACTOS0
+
DESCARTADAS0
+
conectando…
+
+
+ 2xx + 3xx + 4xx + 5xx +
+ + + +