Files
urutau/internal/fed/fed.go
T

284 lines
7.3 KiB
Go

// Package fed aggregates the nodes of the hub: one node per probe, each with
// its own store, served in process through the Backend interface.
package fed
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// Backend is one probe node seen from the aggregation layer.
type Backend interface {
Name() string
Export(rg store.Range) store.PeerExport
Study(q store.PeriodQuery) store.PeerStudy
Egress(from, to int64) json.RawMessage
Subscribe() (<-chan store.LiveEvent, func())
SubscribeVisits() (<-chan store.VisitMsg, func())
// Online reports whether the probe is connected. The data of an offline
// node is still served (it lives in the hub).
Online() bool
Location() *store.Location
}
// HostStatus is implemented by backends that know more than Online (version,
// last contact, lag); Hosts uses it when present.
type HostStatus interface {
HostInfo() store.HostInfo
}
const (
exportTTL = 5 * time.Second
studyTTL = 30 * time.Second
cacheMax = 24
liveBuf = 500
)
type cached[T any] struct {
at time.Time
v T
}
// Hub merges the backends supplied by Provider.
type Hub struct {
Provider func() []Backend
mu sync.Mutex
exports map[string]cached[store.PeerExport]
studies map[string]cached[store.PeerStudy]
lmu sync.Mutex
recent []store.LiveEvent
head int
subs map[chan store.LiveEvent]struct{}
vsubs map[chan store.VisitMsg]struct{}
attach map[string]func() // backend name -> stop
}
// NewHub creates a hub over the backends returned by provider (called on every use).
func NewHub(provider func() []Backend) *Hub {
return &Hub{Provider: provider, exports: map[string]cached[store.PeerExport]{}, studies: map[string]cached[store.PeerStudy]{},
subs: map[chan store.LiveEvent]struct{}{}, vsubs: map[chan store.VisitMsg]struct{}{}, attach: map[string]func(){}}
}
// onlyHas reports whether name is in only: one node name or a comma list.
func onlyHas(only, name string) bool {
if only == name {
return true
}
if !strings.Contains(only, ",") {
return false
}
for _, n := range strings.Split(only, ",") {
if strings.TrimSpace(n) == name {
return true
}
}
return false
}
func (h *Hub) backends(only string) []Backend {
if h == nil || h.Provider == nil {
return nil
}
all := h.Provider()
out := make([]Backend, 0, len(all))
for _, b := range all {
if only == "" || onlyHas(only, b.Name()) {
out = append(out, b)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name() < out[j].Name() })
return out
}
// PeerNames lists the names of the nodes (nil-safe).
func (h *Hub) PeerNames() []string {
var out []string
for _, b := range h.backends("") {
out = append(out, b.Name())
}
return out
}
// Has reports whether name is a node served by this hub.
func (h *Hub) Has(name string) bool { return len(h.backends(name)) > 0 }
func (h *Hub) export(b Backend, rg store.Range) (store.PeerExport, bool) {
key := b.Name() + "|" + rg.Key()
h.mu.Lock()
if c, ok := h.exports[key]; ok && time.Since(c.at) < exportTTL {
h.mu.Unlock()
return c.v, true
}
h.mu.Unlock()
e := b.Export(rg)
if err := e.SanitizeRange(rg); err != nil {
return e, false
}
e.Summary = rename(e.Summary, b.Name())
h.mu.Lock()
if len(h.exports) >= cacheMax {
h.exports = map[string]cached[store.PeerExport]{}
}
h.exports[key] = cached[store.PeerExport]{time.Now(), e}
h.mu.Unlock()
return e, true
}
// SummariesFor returns the summaries of the nodes (or one) for any window.
func (h *Hub) SummariesFor(ctx context.Context, rg store.Range, only string) []store.Summary {
var out []store.Summary
for _, b := range h.backends(only) {
if e, ok := h.export(b, rg); ok {
out = append(out, e.Summary)
}
}
return out
}
// TrafficFor returns the analytics of the nodes (or one) for a window and domain.
func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only string) []store.TrafficData {
var out []store.TrafficData
for _, b := range h.backends(only) {
if e, ok := h.export(b, rg); ok {
if t, ok := e.Traffic[domain]; ok {
t.Host = b.Name()
out = append(out, t)
}
}
}
return out
}
// Summaries is SummariesFor for a named range.
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
return h.SummariesFor(context.Background(), store.ParseRange(rangeName), only)
}
// Traffic is TrafficFor for a named range.
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
return h.TrafficFor(context.Background(), store.ParseRange(rangeName), domain, only)
}
// rename forces the node name on every row of a summary.
func rename(s store.Summary, name string) store.Summary {
s.Host = name
for i := range s.Hosts {
s.Hosts[i].Name, s.Hosts[i].Self = name, false
}
for i := range s.IPs {
s.IPs[i].Hosts = []string{name}
}
for i := range s.Recent {
s.Recent[i].Host = name
}
for i := range s.Sources {
s.Sources[i].Host = name
}
return s
}
// IPDetail looks an address up in the 30-day export of every node.
func (h *Hub) IPDetail(ip string) []store.IPSummary {
var out []store.IPSummary
rg := store.ParseRange("30d")
for _, b := range h.backends("") {
e, ok := h.export(b, rg)
if !ok {
continue
}
for _, x := range e.Summary.IPs {
if x.IP == ip {
out = append(out, x)
break
}
}
}
return out
}
// Hosts lists the status of every node (online or not).
func (h *Hub) Hosts() []store.HostInfo {
rg := store.ParseRange("24h")
var out []store.HostInfo
for _, b := range h.backends("") {
hi := store.HostInfo{Name: b.Name(), Online: b.Online(), Live: b.Online(), Location: b.Location()}
if hs, ok := b.(HostStatus); ok {
hi = hs.HostInfo()
hi.Name = b.Name()
}
if e, ok := h.export(b, rg); ok {
s := e.Summary
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
if hi.Location == nil && len(s.Hosts) > 0 {
hi.Location = s.Hosts[0].Location
}
}
out = append(out, hi)
}
return out
}
func studyKey(q store.PeriodQuery) string {
return fmt.Sprintf("%d-%d|%s|%s|%s|%d", q.From, q.To, q.IP, q.Cat, q.Fam, q.Gap)
}
// StudiesFor returns the period and metrics study of every node (or one).
func (h *Hub) StudiesFor(ctx context.Context, q store.PeriodQuery, only string) map[string]store.PeerStudy {
out := map[string]store.PeerStudy{}
var mu sync.Mutex
var wg sync.WaitGroup
for _, b := range h.backends(only) {
key := b.Name() + "|" + studyKey(q)
h.mu.Lock()
c, hit := h.studies[key]
h.mu.Unlock()
if hit && time.Since(c.at) < studyTTL {
out[b.Name()] = c.v
continue
}
wg.Add(1)
go func(b Backend) {
defer wg.Done()
pq := q
pq.Host = b.Name()
s := b.Study(pq)
if !s.Sanitize(b.Name()) {
return
}
h.mu.Lock()
if len(h.studies) >= cacheMax {
h.studies = map[string]cached[store.PeerStudy]{}
}
h.studies[key] = cached[store.PeerStudy]{time.Now(), s}
h.mu.Unlock()
mu.Lock()
out[b.Name()] = s
mu.Unlock()
}(b)
}
wg.Wait()
return out
}
// EgressFor returns the egress report of every node (or one) for [from, to];
// nodes without egress analysis are left out.
func (h *Hub) EgressFor(ctx context.Context, from, to int64, only string) map[string]json.RawMessage {
out := map[string]json.RawMessage{}
for _, b := range h.backends(only) {
if raw := b.Egress(from, to); len(raw) > 0 {
out[b.Name()] = raw
}
}
return out
}