Merge branch 'fix/traffic-hosts'
This commit is contained in:
commit
551b0ebc40
15 files changed
+329
-85
No files matched your search
@@ -82,3 +82,13 @@ func TestProbeSourceMissingIsWaiting(t *testing.T) {
|
||||
}
|
||||
_ = time.Now
|
||||
}
|
||||
|
||||
func TestSameHeadCopytruncate(t *testing.T) {
|
||||
old := store.Offset{Inode: 7, Offset: 900, FP: 111, FPLen: 64}
|
||||
if !sameHead(old, store.Offset{Inode: 7, Offset: 500, FP: 111, FPLen: 64}) {
|
||||
t.Fatal("same generation must be a duplicate")
|
||||
}
|
||||
if sameHead(old, store.Offset{Inode: 7, Offset: 500, FP: 222, FPLen: 64}) {
|
||||
t.Fatal("truncated and regrown file must not be a duplicate")
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -225,7 +225,7 @@ func (r *Runner) Feed(src string, text []byte, end store.Offset) bool {
|
||||
|
||||
func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
|
||||
name := runnerSource(src)
|
||||
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset {
|
||||
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset && sameHead(saved, end) {
|
||||
return false
|
||||
}
|
||||
if src == wire.SrcEgress {
|
||||
@@ -243,6 +243,19 @@ func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// sameHead reports whether two positions of one inode belong to the same file
|
||||
// generation. A copytruncate rotation (Traefik's log) keeps the inode and
|
||||
// restarts the offsets at 0: without comparing the head fingerprint every new
|
||||
// line below the old high-water mark would be taken for a duplicate and lost
|
||||
// until the file regrew past it. Fingerprints of different lengths cannot be
|
||||
// compared and count as the same file.
|
||||
func sameHead(a, b store.Offset) bool {
|
||||
if a.FPLen > 0 && a.FPLen == b.FPLen {
|
||||
return a.FP == b.FP
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ApplyBatch applies the lines of a batch under the commit mutex.
|
||||
func (r *Runner) ApplyBatch(lines []wire.Line) (accepted, dup int) {
|
||||
r.mu.Lock()
|
||||
|
||||
+17
-1
@@ -867,7 +867,7 @@ func (f *Filter) Match(r *Rec) bool {
|
||||
if r.T < f.From || (f.To != 0 && r.T > f.To) {
|
||||
return false
|
||||
}
|
||||
if f.Host != "" && r.Host != f.Host {
|
||||
if f.Host != "" && !hostMatch(f.Host, r.Host) {
|
||||
return false
|
||||
}
|
||||
if len(f.Cats) > 0 && !f.Cats[r.Cat] {
|
||||
@@ -1164,3 +1164,19 @@ func (l *Log) Counts(from, to int64) map[int64]int64 {
|
||||
|
||||
// StartCursor is a cursor that begins an ascending read at time t.
|
||||
func StartCursor(t int64) string { return encodeCursor(t, 0) }
|
||||
|
||||
// hostMatch reports whether host is the filter or one of its comma list.
|
||||
func hostMatch(filter, host string) bool {
|
||||
if filter == host {
|
||||
return true
|
||||
}
|
||||
if !strings.Contains(filter, ",") {
|
||||
return false
|
||||
}
|
||||
for _, n := range strings.Split(filter, ",") {
|
||||
if strings.TrimSpace(n) == host {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+18
-1
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -67,6 +68,22 @@ func NewHub(provider func() []Backend) *Hub {
|
||||
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
|
||||
@@ -74,7 +91,7 @@ func (h *Hub) backends(only string) []Backend {
|
||||
all := h.Provider()
|
||||
out := make([]Backend, 0, len(all))
|
||||
for _, b := range all {
|
||||
if only == "" || only == b.Name() {
|
||||
if only == "" || onlyHas(only, b.Name()) {
|
||||
out = append(out, b)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,17 +32,16 @@ func (s *Server) analytics(kind string) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
host := q.Get("host")
|
||||
if len(host) > 64 {
|
||||
if !hostListOK(host) {
|
||||
badRequest(w, "invalid host")
|
||||
return
|
||||
}
|
||||
if host == "all" {
|
||||
host = ""
|
||||
}
|
||||
if host != "" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
sel, ok := s.parseHosts(host)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
host = sel.csv(s.opt.Store.Name())
|
||||
dim := q.Get("dim")
|
||||
if kind == "concentration" {
|
||||
if dim == "" {
|
||||
|
||||
@@ -290,13 +290,10 @@ func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
hosts := s.incHosts()
|
||||
if q.Host != "" && q.Host != "all" {
|
||||
hosts = []string{q.Host}
|
||||
if s.incStore(q.Host) == nil {
|
||||
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
|
||||
return
|
||||
}
|
||||
hosts := s.incSelect(q.Host)
|
||||
if hosts == nil {
|
||||
writeJSON(w, 200, qPage{Items: []qSummary{}, Counts: map[string]int{}, Hosts: s.incHosts()})
|
||||
return
|
||||
}
|
||||
q.Host = ""
|
||||
if len(hosts) == 1 {
|
||||
@@ -480,10 +477,7 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="incidents.csv"`)
|
||||
cw := csv.NewWriter(w)
|
||||
cw.Write([]string{"id", "status", "severity", "host", "kind", "workload", "dst", "dport", "proto", "title", "first_seen", "last_seen", "count", "assignee", "tags", "verdict", "suppress", "created_at", "updated_at"})
|
||||
hosts := s.incHosts()
|
||||
if q.Host != "" && q.Host != "all" {
|
||||
hosts = []string{q.Host}
|
||||
}
|
||||
hosts := s.incSelect(q.Host)
|
||||
q.Host = ""
|
||||
var rows []qSummary
|
||||
for _, h := range hosts {
|
||||
@@ -504,3 +498,26 @@ func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
cw.Flush()
|
||||
}
|
||||
|
||||
// incSelect resolves the host filter of the ticket queries: "" or "all" is
|
||||
// every host with a store, otherwise the listed ones (comma list) that have
|
||||
// one. It returns nil when a selection names none.
|
||||
func (s *Server) incSelect(raw string) []string {
|
||||
if raw == "" || raw == "all" {
|
||||
return s.incHosts()
|
||||
}
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
for _, n := range strings.Split(raw, ",") {
|
||||
n = strings.TrimSpace(n)
|
||||
if n == "all" {
|
||||
return s.incHosts()
|
||||
}
|
||||
if n == "" || seen[n] || s.incStore(n) == nil {
|
||||
continue
|
||||
}
|
||||
seen[n] = true
|
||||
out = append(out, n)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -96,16 +96,12 @@ func figuresOf(t store.Totals, tr store.TrafficData) reportFigures {
|
||||
// trafficOf is what /api/v1/traffic answers for all domains, merged with the peers.
|
||||
func (s *Server) trafficOf(r *http.Request, rg store.Range, host string) store.TrafficData {
|
||||
var parts []store.TrafficData
|
||||
self := s.opt.Store.Name()
|
||||
if host == "all" || host == self {
|
||||
sel, _ := s.parseHosts(host)
|
||||
if sel.local {
|
||||
parts = append(parts, s.opt.Store.TrafficFor(rg, "all"))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, "all", only)...)
|
||||
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
|
||||
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, "all", sel.only())...)
|
||||
}
|
||||
return store.MergeTraffic(host, parts)
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ func (s *Server) geoAPI(w http.ResponseWriter, r *http.Request) {
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
if _, ok := s.parseHosts(host); !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// maxHostSel bounds how many names one host selection may carry.
|
||||
const maxHostSel = 16
|
||||
|
||||
// hostSel is a resolved host selection of a request: "all" (or empty), one
|
||||
// host, or a comma list such as host=oracle,hostinger.
|
||||
type hostSel struct {
|
||||
all bool // every host: no filtering
|
||||
local bool // this node is part of the selection
|
||||
peers []string // the other nodes of the selection (sorted), empty with all
|
||||
}
|
||||
|
||||
// csv is the canonical text of the selection ("" for all): the hub's own name
|
||||
// (when present) first, then the peers.
|
||||
func (h hostSel) csv(self string) string {
|
||||
if h.all {
|
||||
return ""
|
||||
}
|
||||
var n []string
|
||||
if h.local {
|
||||
n = append(n, self)
|
||||
}
|
||||
return strings.Join(append(n, h.peers...), ",")
|
||||
}
|
||||
|
||||
// only is the peers' list the fed.Hub understands ("" asks every node).
|
||||
func (h hostSel) only() string {
|
||||
if h.all {
|
||||
return ""
|
||||
}
|
||||
return strings.Join(h.peers, ",")
|
||||
}
|
||||
|
||||
// parseHosts resolves a host query value. ok is false for names this hub does
|
||||
// not serve, for a malformed or oversized list.
|
||||
func (s *Server) parseHosts(raw string) (hostSel, bool) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" || raw == "all" {
|
||||
return hostSel{all: true, local: true}, true
|
||||
}
|
||||
if len(raw) > 64*maxHostSel {
|
||||
return hostSel{}, false
|
||||
}
|
||||
self := s.opt.Store.Name()
|
||||
seen := map[string]bool{}
|
||||
var sel hostSel
|
||||
for _, n := range strings.Split(raw, ",") {
|
||||
n = strings.TrimSpace(n)
|
||||
switch {
|
||||
case n == "":
|
||||
continue
|
||||
case n == "all":
|
||||
return hostSel{all: true, local: true}, true
|
||||
case len(n) > 64 || len(seen) >= maxHostSel:
|
||||
return hostSel{}, false
|
||||
case seen[n]:
|
||||
continue
|
||||
}
|
||||
seen[n] = true
|
||||
if n == self {
|
||||
sel.local = true
|
||||
} else if s.opt.Hub != nil && s.opt.Hub.Has(n) {
|
||||
sel.peers = append(sel.peers, n)
|
||||
} else {
|
||||
return hostSel{}, false
|
||||
}
|
||||
}
|
||||
if len(seen) == 0 {
|
||||
return hostSel{all: true, local: true}, true
|
||||
}
|
||||
sort.Strings(sel.peers)
|
||||
// naming every node is the same as asking for all of them
|
||||
if sel.local {
|
||||
every := true
|
||||
if s.opt.Hub != nil {
|
||||
for _, p := range s.opt.Hub.PeerNames() {
|
||||
every = every && seen[p]
|
||||
}
|
||||
}
|
||||
if every {
|
||||
return hostSel{all: true, local: true}, true
|
||||
}
|
||||
}
|
||||
return sel, true
|
||||
}
|
||||
|
||||
// hostListOK bounds the text of a host list: names of 64 bytes at most, 16 at most.
|
||||
func hostListOK(raw string) bool {
|
||||
if len(raw) > 64*maxHostSel+maxHostSel {
|
||||
return false
|
||||
}
|
||||
for _, n := range strings.Split(raw, ",") {
|
||||
if len(strings.TrimSpace(n)) > 64 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
"time"
|
||||
)
|
||||
|
||||
// host= accepts "all", one name or a comma list, the same way on every endpoint.
|
||||
func TestHostSelectionList(t *testing.T) {
|
||||
mk := func(ip string) store.PeerExport {
|
||||
e := store.PeerExport{V: 1}
|
||||
e.Summary.IPs = []store.IPSummary{{IP: ip, Score: 10}}
|
||||
return e
|
||||
}
|
||||
hub := fed.NewHub(func() []fed.Backend {
|
||||
return []fed.Backend{fakeBackend{name: "p1", exp: mk("198.51.100.1")}, fakeBackend{name: "p2", exp: mk("198.51.100.2")}, fakeBackend{name: "p3", exp: mk("198.51.100.3")}}
|
||||
})
|
||||
st := store.New(store.Config{Name: "me", Version: "t"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "203.0.113.9", Cat: core.Scanner, Source: "traefik", Status: 404, Path: "/.env"})
|
||||
h := New(Options{Token: utok, Store: st, Hub: hub})
|
||||
total := func(host string) int {
|
||||
code, body := bearerGet(h, "/api/v1/ips?range=24h&min_score=0&host="+host)
|
||||
if code != 200 {
|
||||
t.Fatalf("host=%q: %d %s", host, code, body)
|
||||
}
|
||||
var o struct{ Total int }
|
||||
if err := json.Unmarshal([]byte(body), &o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return o.Total
|
||||
}
|
||||
for host, want := range map[string]int{"": 4, "all": 4, "p1": 1, "p1,p2": 2, "p1,p2,p3": 3, "me,p3": 2, "me": 1, "me,p1,p2,p3": 4, "p2,p2": 1, "p1,all": 4} {
|
||||
if got := total(host); got != want {
|
||||
t.Errorf("host=%q: %d IPs, want %d", host, got, want)
|
||||
}
|
||||
}
|
||||
for _, ep := range []string{"summary", "traffic", "integrity", "geo", "report"} {
|
||||
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,p2"); code != 200 {
|
||||
t.Errorf("%s host=p1,p2: %d", ep, code)
|
||||
}
|
||||
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,nope"); code != 404 {
|
||||
t.Errorf("%s host=p1,nope: %d", ep, code)
|
||||
}
|
||||
}
|
||||
for _, ep := range []string{"period", "metrics", "evolution", "egress"} {
|
||||
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=me,p1"); code != 200 {
|
||||
t.Errorf("%s host=me,p1: %d", ep, code)
|
||||
}
|
||||
if code, _ := bearerGet(h, "/api/v1/"+ep+"?host=p1,nope"); code != 404 {
|
||||
t.Errorf("%s host=p1,nope: %d", ep, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,13 +37,13 @@ func (s *Server) eventFilter(w http.ResponseWriter, r *http.Request, defaultSpan
|
||||
}
|
||||
eq.From, eq.To = rg.Bounds(s.opt.Now().Unix())
|
||||
eq.Host = q.Get("host")
|
||||
if eq.Host == "all" {
|
||||
eq.Host = ""
|
||||
}
|
||||
if len(eq.Host) > 64 {
|
||||
if !hostListOK(eq.Host) {
|
||||
badRequest(w, "invalid host")
|
||||
return eq, false
|
||||
}
|
||||
if sel, ok := s.parseHosts(eq.Host); ok { // "all" and a list naming every node become ""
|
||||
eq.Host = sel.csv(s.opt.Store.Name())
|
||||
}
|
||||
if ip := q.Get("ip"); ip != "" {
|
||||
_, err1 := netip.ParseAddr(ip)
|
||||
_, err2 := netip.ParsePrefix(ip)
|
||||
@@ -217,21 +217,19 @@ func (s *Server) sessionsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
}{list[from:to], gap, trunc, s.opt.Store.EventLog() != nil, pageTotal{metaOf(len(list), page, per), len(list)}})
|
||||
}
|
||||
|
||||
// studyHosts resolves the host selection of period and metrics: whether the
|
||||
// local study is wanted and which peers to ask. It answers 404 itself.
|
||||
// studyHosts resolves the host selection of period and metrics (one name, "all"
|
||||
// or a comma list): whether the local study is wanted and which peers to ask
|
||||
// (only: their names, comma separated). It answers 404 itself.
|
||||
func (s *Server) studyHosts(w http.ResponseWriter, host string) (local bool, peers bool, only string, ok bool) {
|
||||
self := s.opt.Store.Name()
|
||||
if host == "" || host == "all" {
|
||||
return true, s.opt.Hub != nil, "", true
|
||||
}
|
||||
if host == self {
|
||||
return true, false, "", true
|
||||
}
|
||||
if s.opt.Hub == nil || !s.opt.Hub.Has(host) {
|
||||
sel, ok := s.parseHosts(host)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return false, false, "", false
|
||||
}
|
||||
return false, true, host, true
|
||||
if sel.all {
|
||||
return true, s.opt.Hub != nil, "", true
|
||||
}
|
||||
return sel.local, len(sel.peers) > 0, sel.only(), true
|
||||
}
|
||||
|
||||
// userSlot admits one more user-side study (503 with Retry-After when four run).
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
|
||||
@@ -139,7 +140,7 @@ func (s *Server) primaryName() string { return s.opt.Store.Name() }
|
||||
|
||||
// enforceFor returns the engine of a host ("" or the primary: the primary's).
|
||||
func (s *Server) enforceFor(host string) *enforce.Engine {
|
||||
if host == "" || host == s.primaryName() || s.opt.Nodes == nil {
|
||||
if host == "" || strings.Contains(host, ",") || host == s.primaryName() || s.opt.Nodes == nil {
|
||||
return enforceEngine.Load()
|
||||
}
|
||||
return s.opt.Nodes.Enforce(host)
|
||||
|
||||
+13
-25
@@ -371,27 +371,23 @@ func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// parts returns the summaries to merge for a host selection.
|
||||
func (s *Server) parts(ctx context.Context, rg store.Range, host string) (parts []store.Summary, all []store.HostInfo) {
|
||||
self := s.opt.Store.Name()
|
||||
local := s.opt.Store.SummaryFor(rg)
|
||||
all = append(all, local.Hosts...)
|
||||
if s.opt.Hub != nil {
|
||||
all = append(all, s.opt.Hub.Hosts()...)
|
||||
}
|
||||
if host == "" || host == "all" || host == self {
|
||||
sel, _ := s.parseHosts(host)
|
||||
if sel.local {
|
||||
parts = append(parts, local)
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.SummariesFor(ctx, rg, only)...)
|
||||
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
|
||||
parts = append(parts, s.opt.Hub.SummariesFor(ctx, rg, sel.only())...)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Server) knownHost(w http.ResponseWriter, host string) bool {
|
||||
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
if _, ok := s.parseHosts(host); !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return false
|
||||
}
|
||||
@@ -437,16 +433,12 @@ func (s *Server) allIPs(ctx context.Context, rg store.Range, host string) []stor
|
||||
|
||||
func (s *Server) ipsOf(ctx context.Context, rg store.Range, host string, localOnly bool) []store.IPSummary {
|
||||
var lists [][]store.IPSummary
|
||||
self := s.opt.Store.Name()
|
||||
if host == "" || host == "all" || host == self {
|
||||
sel, _ := s.parseHosts(host)
|
||||
if sel.local {
|
||||
lists = append(lists, s.opt.Store.AllIPs(rg, false))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self && !localOnly {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
}
|
||||
for _, p := range s.opt.Hub.SummariesFor(ctx, rg, only) {
|
||||
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) && !localOnly {
|
||||
for _, p := range s.opt.Hub.SummariesFor(ctx, rg, sel.only()) {
|
||||
lists = append(lists, p.IPs)
|
||||
}
|
||||
}
|
||||
@@ -714,20 +706,16 @@ func (s *Server) traffic(w http.ResponseWriter, r *http.Request) {
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
self := s.opt.Store.Name()
|
||||
if !s.knownHost(w, host) {
|
||||
return
|
||||
}
|
||||
sel, _ := s.parseHosts(host)
|
||||
var parts []store.TrafficData
|
||||
if host == "all" || host == self {
|
||||
if sel.local {
|
||||
parts = append(parts, s.opt.Store.TrafficFor(rg, domain))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, domain, only)...)
|
||||
if s.opt.Hub != nil && (sel.all || len(sel.peers) > 0) {
|
||||
parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, domain, sel.only())...)
|
||||
}
|
||||
out := store.MergeTraffic(host, parts)
|
||||
out.Domain = domain
|
||||
|
||||
+39
-12
@@ -614,7 +614,7 @@
|
||||
var seen = {}, list = [];
|
||||
var rec = state.summary ? state.summary.recent || [] : [];
|
||||
state.live.concat(rec).forEach(function (e) {
|
||||
if (state.host !== 'all' && e.host !== state.host) return;
|
||||
if (!hostHas(state.host, e.host)) return;
|
||||
var key = e.t + '|' + e.ip + '|' + e.cat + '|' + (e.path || e.user || e.jail || '');
|
||||
if (seen[key]) return;
|
||||
seen[key] = 1;
|
||||
@@ -1021,7 +1021,7 @@
|
||||
// each probe enforces its own bans: the operator picks where to lift it (or every host)
|
||||
var hostSel = el('select', { id: 'unban-host' });
|
||||
var hostRow = el('div', { class: 'unban-host', hidden: true }, el('label', { for: 'unban-host' }, t('pr.unban.host')), hostSel);
|
||||
var wantHost = (opts && opts.host) || (state.host !== 'all' ? state.host : 'all');
|
||||
var wantHost = (opts && opts.host) || (hostList(state.host).length === 1 ? state.host : 'all');
|
||||
getSummary(ctx()).then(function (s) {
|
||||
var hs = (s.hosts || []).map(function (x) { return x.name; });
|
||||
if (hs.length < 2) return;
|
||||
@@ -1832,7 +1832,7 @@
|
||||
var p = [];
|
||||
if (sl.from !== null && sl.from !== undefined) p.push('from=' + encodeURIComponent(new Date(sl.from * 1000).toISOString()), 'to=' + encodeURIComponent(new Date(sl.to * 1000).toISOString()));
|
||||
else p.push('r=' + sl.range);
|
||||
if (sl.host && sl.host !== 'all') p.push('host=' + encodeURIComponent(sl.host));
|
||||
if (sl.host && sl.host !== 'all') p.push('host=' + encodeURIComponent(sl.host).replace(/%2C/gi, ','));
|
||||
return p;
|
||||
}
|
||||
function buildHash(id, segments, extra, sl) {
|
||||
@@ -1841,6 +1841,14 @@
|
||||
return '#/' + [id].concat((segments || []).map(encodeURIComponent)).join('/') + '?' + parts.join('&');
|
||||
}
|
||||
function hrefFor(id, segments, extra) { return buildHash(id, segments || [], extra || {}); }
|
||||
// host selection: 'all' or a comma list of probe names (host=oracle,hostinger in the URL and in the API)
|
||||
function hostList(v) {
|
||||
var seen = {}, out = [];
|
||||
String(v || '').split(',').forEach(function (n) { n = n.trim(); if (n && n !== 'all' && n.length <= 64 && !seen[n]) { seen[n] = 1; out.push(n); } });
|
||||
return out.slice(0, 16);
|
||||
}
|
||||
function hostJoin(list) { return list.length ? list.join(',') : 'all'; }
|
||||
function hostHas(v, name) { return v === 'all' || !v || hostList(v).indexOf(name) >= 0; }
|
||||
// read r/from/to/host from the URL; absent keys keep the current slice
|
||||
function readSlice(q) {
|
||||
var f = q.get('from'), to = q.get('to'), r = q.get('r') || q.get('range'), ok = false;
|
||||
@@ -1849,7 +1857,7 @@
|
||||
if (isFinite(a) && isFinite(b) && b > a && (b - a) / 1000 <= MAX_SPAN) { state.from = Math.floor(a / 1000); state.to = Math.floor(b / 1000); ok = true; }
|
||||
}
|
||||
if (!ok && r && PRESETS.indexOf(r) >= 0) { state.range = r; state.from = state.to = null; lsSet('urutau.range', r); }
|
||||
if (q.has('host')) { state.host = q.get('host') || 'all'; lsSet('urutau.host', state.host); }
|
||||
if (q.has('host')) { state.host = hostJoin(hostList(q.get('host'))); lsSet('urutau.host', state.host); }
|
||||
}
|
||||
// change the slice: the URL changes, the router does the rest
|
||||
function setShell(over) {
|
||||
@@ -2072,21 +2080,35 @@
|
||||
box.hidden = true;
|
||||
}
|
||||
function hostOpt(value, name, meta, tone) {
|
||||
var on = state.host === value;
|
||||
var sel = hostList(state.host), on = value === 'all' ? !sel.length : sel.indexOf(value) >= 0;
|
||||
var b = el('button', { type: 'button', class: 'fb-opt', 'data-host': value, 'aria-pressed': on ? 'true' : 'false' },
|
||||
h('span', 'fb-dot ' + tone), h('span', 'fb-opt-t', h('span', 'fb-opt-n', name), h('span', 'fb-opt-m', meta)), h('span', 'fb-tick', svgIcon(IC.check)));
|
||||
b.addEventListener('click', function () { closePop(hp, true); if (state.host !== value) setShell({ host: value }); });
|
||||
b.addEventListener('click', function () {
|
||||
// "all" clears the selection; any other row toggles that probe (several can be on); all of them, or none, is "all"
|
||||
var cur = hostList(state.host), next;
|
||||
if (value === 'all') next = [];
|
||||
else {
|
||||
var i = cur.indexOf(value);
|
||||
next = i >= 0 ? cur.filter(function (n) { return n !== value; }) : cur.concat([value]);
|
||||
var names = (state.hostList || []).map(function (x) { return x.name; });
|
||||
if (names.length && names.every(function (n) { return next.indexOf(n) >= 0; })) next = [];
|
||||
}
|
||||
var nv = hostJoin(next);
|
||||
if (value === 'all') closePop(hp, true);
|
||||
if (nv !== state.host) setShell({ host: nv });
|
||||
});
|
||||
return b;
|
||||
}
|
||||
function renderHostPicker() {
|
||||
if (!hp.btn) return;
|
||||
var hosts = state.hostList || [], on = hosts.filter(function (x) { return x.online; }).length;
|
||||
$('#host-picker').hidden = hosts.length < 2;
|
||||
var cur = hosts.filter(function (x) { return x.name === state.host; })[0];
|
||||
hp.label.textContent = state.host === 'all' ? t('host.all') : state.host;
|
||||
var tone = state.host === 'all' ? (on === hosts.length ? 'on' : on ? 'warn' : 'off') : (cur && cur.online ? 'on' : 'off');
|
||||
var sel = hostList(state.host), picked = hosts.filter(function (x) { return sel.indexOf(x.name) >= 0; });
|
||||
var pOn = picked.filter(function (x) { return x.online; }).length;
|
||||
hp.label.textContent = !sel.length ? t('host.all') : sel.join(', ');
|
||||
var tone = !sel.length ? (on === hosts.length ? 'on' : on ? 'warn' : 'off') : (pOn === picked.length && picked.length ? 'on' : pOn ? 'warn' : 'off');
|
||||
hp.dot.className = 'fb-dot ' + tone;
|
||||
hp.count.textContent = state.host === 'all' ? on + '/' + hosts.length : (cur && cur.online ? t('host.online') : t('host.offline'));
|
||||
hp.count.textContent = !sel.length ? on + '/' + hosts.length : (sel.length > 1 ? pOn + '/' + picked.length : (pOn ? t('host.online') : t('host.offline')));
|
||||
hp.count.className = 'fb-count ' + tone;
|
||||
hp.btn.setAttribute('aria-label', t('host.label') + ': ' + hp.label.textContent + ', ' + t('fb.host.status', { n: on, m: hosts.length }));
|
||||
var want = hosts.map(function (x) { return x.name + (x.online ? '1' : '0') + (x.version || ''); }).join('|') + '|' + state.host + '|' + lang;
|
||||
@@ -2126,7 +2148,7 @@
|
||||
var p = $('#slice-text');
|
||||
if (!p) return;
|
||||
clear(p);
|
||||
var parts = [state.host === 'all' ? t('slice.allHosts') : t('slice.host', { name: state.host })];
|
||||
var parts = [state.host === 'all' ? t('slice.allHosts') : t('slice.host', { name: hostList(state.host).join(', ') })];
|
||||
if (current && pages[current.id] && pages[current.id].domain) parts.push(state.domain === 'all' ? t('slice.allDomains') : t('slice.domain', { name: state.domain }));
|
||||
if (state.note) parts.push(state.note);
|
||||
var live = !isCustom();
|
||||
@@ -2306,7 +2328,12 @@
|
||||
function updateHostSelect(s) {
|
||||
var hosts = s.hosts || [];
|
||||
state.hostList = hosts;
|
||||
if (state.host !== 'all' && !hosts.some(function (x) { return x.name === state.host; })) { state.host = 'all'; lsSet('urutau.host', 'all'); }
|
||||
if (state.host !== 'all' && hosts.length) {
|
||||
var known = hostList(state.host).filter(function (n) { return hosts.some(function (x) { return x.name === n; }); });
|
||||
if (known.length === hosts.length) known = [];
|
||||
var kv = hostJoin(known);
|
||||
if (kv !== state.host) { state.host = kv; lsSet('urutau.host', kv); }
|
||||
}
|
||||
renderHostPicker();
|
||||
}
|
||||
function shellSummary() {
|
||||
|
||||
@@ -1317,7 +1317,7 @@
|
||||
this.listDirty = true;
|
||||
if (this.paused || this.hidden || this.offHosts[r.host] || (dev && this.offDev[dev])) return;
|
||||
var h = this.ctx && this.ctx.host;
|
||||
if (h && h !== 'all' && h !== r.host) return;
|
||||
if (h && h !== 'all' && (',' + h + ',').indexOf(',' + r.host + ',') < 0) return;
|
||||
this.map.spawn(e, { visit: true });
|
||||
};
|
||||
P.visitBatch = function (e) { if (isNum(e.n) && e.n > 0) this.vcount(Math.min(e.n, 1e6), isNum(e.t) ? e.t : Date.now() / 1000, '', ''); };
|
||||
@@ -1500,21 +1500,21 @@
|
||||
P.draw = function (r) {
|
||||
if (this.offCats[r.cat] || this.offHosts[r.host]) return;
|
||||
var h = this.ctx && this.ctx.host;
|
||||
if (h && h !== 'all' && h !== r.host) return;
|
||||
if (h && h !== 'all' && (',' + h + ',').indexOf(',' + r.host + ',') < 0) return;
|
||||
this.map.spawn(r.ev);
|
||||
};
|
||||
|
||||
P.visible = function (r) {
|
||||
if (this.offCats[r.cat] || this.offHosts[r.host]) return false;
|
||||
var h = this.ctx && this.ctx.host;
|
||||
return !h || h === 'all' || h === r.host;
|
||||
return !h || h === 'all' || (',' + h + ',').indexOf(',' + r.host + ',') >= 0;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ panels and metrics
|
||||
P.hostOk = function (h) {
|
||||
if (this.offHosts[h]) return false;
|
||||
var c = this.ctx && this.ctx.host;
|
||||
return !c || c === 'all' || c === h;
|
||||
return !c || c === 'all' || (',' + c + ',').indexOf(',' + h + ',') >= 0;
|
||||
};
|
||||
|
||||
// sums the minute buckets from..to (inclusive) over the visible hosts (or all of them)
|
||||
|
||||
Reference in new issue
Block a user