package hub import ( "fmt" "log/slog" "os" "path/filepath" "sort" "sync" "sync/atomic" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire" ) // Node is one probe's data seen from the ingest layer (implemented by the app). type Node interface { Name() string // Ready is false while the node still loads its snapshot. Ready() bool // Offsets are the hub-committed positions, keyed by wire source name. Offsets() map[string]wire.Pos // Apply commits a batch under the node's commit mutex. Apply(b wire.Batch) (accepted, dup int) // Hello tells the node what the probe announced (sources, location). Hello(h wire.Hello) // Queue is the command queue of the node. Queue() *CmdQueue // SetStatus hands over the last status the probe reported. SetStatus(st wire.Status, connected bool) // SetLocation changes the location events of this node point to. SetLocation(l *wire.Location) } // Factory builds the node of a probe. type Factory func(name string, primary bool, rec Probe) (Node, error) // Update is the body of PUT /api/v1/probes/{name}. type Update struct { Location *wire.Location `json:"location"` Egress Egress `json:"egress"` } // ProbeInfo is one row of GET /api/v1/probes. type ProbeInfo struct { Name string `json:"name"` Primary bool `json:"primary"` Registered bool `json:"registered"` Revoked bool `json:"revoked"` Created int64 `json:"created,omitempty"` Connected bool `json:"connected"` LastSeen int64 `json:"last_seen"` LastLine int64 `json:"last_line"` LagMS int64 `json:"lag_ms"` Version string `json:"version,omitempty"` Hostname string `json:"hostname,omitempty"` Dropped uint64 `json:"dropped"` Spool int64 `json:"spool"` SpoolFiles int `json:"spool_files"` CmdPending int `json:"cmd_pending"` CmdDropped uint64 `json:"cmd_dropped"` CmdErrors uint64 `json:"cmd_errors"` Uptime int64 `json:"uptime"` RSS uint64 `json:"rss"` Sources []wire.SourceStatus `json:"sources"` Location *wire.Location `json:"location,omitempty"` Egress Egress `json:"egress"` } type conn struct { mu sync.Mutex lastSeen int64 lastLine int64 lagMS int64 version string hostname string status wire.Status ack uint64 busy atomic.Bool } // Manager owns the registry and the nodes. type Manager struct { Dir string // data directory (primary node lives in its root) Primary string Version string Reg *Registry Make Factory Log *slog.Logger Now func() time.Time mu sync.Mutex nodes map[string]Node conns map[string]*conn infl atomic.Int32 } // NewManager opens probes.json in dir and returns a manager; call Load to // create the nodes. func NewManager(dir, primary, version string, mk Factory, log *slog.Logger) (*Manager, error) { reg, err := OpenRegistry(filepath.Join(dir, "probes.json")) if err != nil { return nil, err } if log == nil { log = slog.Default() } return &Manager{Dir: dir, Primary: primary, Version: version, Reg: reg, Make: mk, Log: log, Now: time.Now, nodes: map[string]Node{}, conns: map[string]*conn{}}, nil } // Load creates the primary node, one node per registered probe and one per // directory in probes/ (imported data), so every data set is served at once. func (m *Manager) Load() error { names := map[string]bool{m.Primary: true} for _, p := range m.Reg.List() { names[p.Name] = true } if ents, err := os.ReadDir(filepath.Join(m.Dir, "probes")); err == nil { for _, e := range ents { if e.IsDir() && wire.ValidName(e.Name()) { names[e.Name()] = true } } } list := make([]string, 0, len(names)) for n := range names { list = append(list, n) } sort.Strings(list) for _, n := range list { if _, err := m.Ensure(n); err != nil { return fmt.Errorf("node %s: %w", n, err) } } return nil } // Ensure returns the node of name, creating it on first use. func (m *Manager) Ensure(name string) (Node, error) { m.mu.Lock() defer m.mu.Unlock() if n, ok := m.nodes[name]; ok { return n, nil } if !wire.ValidName(name) { return nil, ErrName } rec, _ := m.Reg.Get(name) n, err := m.Make(name, name == m.Primary, rec) if err != nil { return nil, err } m.nodes[name] = n if m.conns[name] == nil { m.conns[name] = &conn{} } return n, nil } // Get returns an existing node. func (m *Manager) Get(name string) Node { m.mu.Lock() defer m.mu.Unlock() return m.nodes[name] } // Nodes lists the nodes sorted by name, the primary first. func (m *Manager) Nodes() []Node { m.mu.Lock() defer m.mu.Unlock() out := make([]Node, 0, len(m.nodes)) for _, n := range m.nodes { out = append(out, n) } sort.Slice(out, func(i, j int) bool { a, b := out[i].Name(), out[j].Name() if (a == m.Primary) != (b == m.Primary) { return a == m.Primary } return a < b }) return out } func (m *Manager) conn(name string) *conn { m.mu.Lock() defer m.mu.Unlock() c := m.conns[name] if c == nil { c = &conn{} m.conns[name] = c } return c } // Connected reports whether the probe pushed within OfflineSec. func (m *Manager) Connected(name string) bool { c := m.conn(name) c.mu.Lock() defer c.mu.Unlock() return c.lastSeen > 0 && m.Now().Unix()-c.lastSeen <= wire.OfflineSec } // Info describes one probe. func (m *Manager) Info(name string) (ProbeInfo, bool) { n := m.Get(name) rec, reg := m.Reg.Get(name) if n == nil && !reg { return ProbeInfo{}, false } c := m.conn(name) c.mu.Lock() st := c.status in := ProbeInfo{Name: name, Primary: name == m.Primary, Registered: reg, Revoked: rec.Revoked, Created: rec.Created, LastSeen: c.lastSeen, LastLine: c.lastLine, LagMS: c.lagMS, Version: c.version, Hostname: c.hostname, Dropped: st.Dropped, Spool: st.SpoolBytes, SpoolFiles: st.SpoolFiles, CmdErrors: st.CmdErrors, Uptime: st.UptimeSec, RSS: st.RSSBytes, Sources: append([]wire.SourceStatus{}, st.Sources...), Location: rec.Location, Egress: rec.Egress} c.mu.Unlock() in.Connected = m.Connected(name) if n != nil { if q := n.Queue(); q != nil { in.CmdPending, in.CmdDropped = q.Pending(0), q.Dropped() } } return in, true } // List describes every probe (registered ones and nodes without a record, such // as the primary or imported data). func (m *Manager) List() []ProbeInfo { names := map[string]bool{} for _, n := range m.Nodes() { names[n.Name()] = true } for _, p := range m.Reg.List() { names[p.Name] = true } var out []ProbeInfo for n := range names { if in, ok := m.Info(n); ok { out = append(out, in) } } sort.Slice(out, func(i, j int) bool { if out[i].Primary != out[j].Primary { return out[i].Primary } return out[i].Name < out[j].Name }) return out } // Create registers a probe, returning its token (shown once). func (m *Manager) Create(name string) (string, error) { tok, err := m.Reg.Create(name) if err != nil { return "", err } if _, err := m.Ensure(name); err != nil { return "", err } return tok, nil } // Revoke disables the token of a probe and drops its connection state; the // data stays. func (m *Manager) Revoke(name string) error { if err := m.Reg.Revoke(name); err != nil { return err } c := m.conn(name) c.mu.Lock() c.lastSeen = 0 c.mu.Unlock() return nil } // UpdateProbe stores the location and egress configuration and applies the location now. func (m *Manager) UpdateProbe(name string, u Update) error { if u.Location != nil { if l := u.Location; l.Lat < -90 || l.Lat > 90 || l.Lon < -180 || l.Lon > 180 || len(l.Label) > 80 { return fmt.Errorf("invalid location") } } if err := m.Reg.Update(name, u.Location, u.Egress); err != nil { return err } if n := m.Get(name); n != nil { n.SetLocation(u.Location) if r, ok := n.(interface{ ResetEgress(Egress) }); ok { r.ResetEgress(u.Egress) } } return nil } // Close flushes the command queues. func (m *Manager) Close() { for _, n := range m.Nodes() { if q := n.Queue(); q != nil { q.Close() } } }