SPB Git

Repository Public

cluster_network.go 7.3 KB 222 lines go

1package api23import (4	"context"5	"encoding/json"6	"strconv"7	"strings"8	"time"910	"github.com/jackc/pgx/v5"1112	"clustr.spboucher.ai/mcc/internal/authz"13	"clustr.spboucher.ai/mcc/internal/protocol"14)1516// Labels of the connectivity probes an agent runs (metrics net.latency and17// net.loss; see protocol.Catalog).18const (19	clProbeGateway = "gateway"20	clProbeHub     = "hub"21	clVertexLAN    = "lan-gateway"22	clVertexHub    = "wg-hub"23	clMaxTopology  = 100024)2526type clNetNode struct {27	n      clNode28	inv    protocol.Inventory29	values map[string]any30	avail  map[string]string31}3233func (h *clusterHandlers) netNodes(ctx context.Context, now time.Time, cond string, args []any, tail string) ([]clNetNode, error) {34	rows, err := h.Pool.Query(ctx, `select `+clNodeCols+`, n.inventory, s.values, s.availability`+clNodeFrom+35		` where n.retired_at is null`+cond+tail, append(h.clFreshArgs(now), args...)...)36	if err != nil {37		return nil, err38	}39	return pgx.CollectRows(rows, func(r pgx.CollectableRow) (clNetNode, error) {40		var x clNetNode41		var inv, values, avail []byte42		var err error43		if x.n, err = clScanNode(r, &inv, &values, &avail); err != nil {44			return x, err45		}46		if len(inv) > 0 {47			_ = json.Unmarshal(inv, &x.inv)48		}49		x.values, x.avail = clValues(values), clStringMap(avail)50		return x, nil51	})52}5354// clProbe states one probe measurement of a node: its availability and, only55// while the node is fresh or stale, its value.56func clProbe(x *clNetNode, fresh Freshness, metric, label string) (Availability, *float32) {57	if x.n.ObservedAt == nil || fresh == FreshnessOffline {58		return AvailabilityOffline, nil59	}60	if v, ok := clNumber(x.values, clValueKey(metric, label)); ok {61		return clAvail(fresh), clF32(&v)62	}63	if a, ok := clDeclared(x.avail, metric, label); ok {64		return a, nil65	}66	return AvailabilityUnavailable, nil67}6869// GetNetworkTopology reports what the agents observed, nothing more: every70// node is a vertex; a node that has reported has a link to the LAN gateway,71// and a link to the WireGuard hub only when it has a WireGuard interface or72// probes the hub. Each link carries the measured latency and loss, or says73// why there is no measurement.74func (h *clusterHandlers) GetNetworkTopology(ctx context.Context, _ GetNetworkTopologyRequestObject) (GetNetworkTopologyResponseObject, error) {75	acc, err := h.clAccessFor(ctx)76	if err != nil {77		return nil, err78	}79	now := time.Now().UTC()80	nodes, err := h.netNodes(ctx, now, "", nil, ` order by lower(n.alias::text), n.id limit `+strconv.Itoa(clMaxTopology))81	if err != nil {82		return nil, err83	}84	out := NetworkTopology{GeneratedAt: now, Nodes: []TopologyNode{}, Links: []TopologyLink{}}85	filter := acc.scoped(authz.NodesRead)86	var lan, hub bool87	for i := range nodes {88		x := &nodes[i]89		if filter && !acc.can(authz.NodesRead, x.n.facets()...) {90			continue91		}92		fresh := h.clFresh(now, x.n.Seen)93		v := TopologyNode{Id: x.n.ID.String(), Kind: TopologyNodeKindNode, Label: x.n.Alias, NodeId: &x.n.ID, Freshness: &fresh}94		if acc.can(authz.NodesPrivateRead, x.n.facets()...) {95			v.Address = x.n.PrimaryIP96		}97		out.Nodes = append(out.Nodes, v)98		if x.n.ObservedAt == nil {99			continue // never reported: nothing was observed about its connectivity100		}101		var defaultIf, wgIf *string102		for j := range x.inv.Interfaces {103			itf := &x.inv.Interfaces[j]104			if itf.Default && defaultIf == nil {105				defaultIf = &itf.Name106			}107			if clInterfaceKind(*itf) == NetworkInterfaceKindWireguard && wgIf == nil {108				wgIf = &itf.Name109			}110		}111		link := func(kind TopologyLinkKind, target, label string, itf *string) TopologyLink {112			l := TopologyLink{Id: x.n.ID.String() + ":" + target, Source: x.n.ID.String(), Target: target, Kind: kind, Interface: itf,113				State: TopologyLinkStateUnknown, ObservedAt: x.n.ObservedAt, Freshness: fresh}114			l.LatencyAvailability, l.LatencyMs = clProbe(x, fresh, "net.latency", label)115			l.LossAvailability, l.LossPct = clProbe(x, fresh, "net.loss", label)116			switch {117			case l.LossPct != nil && *l.LossPct >= 100:118				l.State = TopologyLinkStateDown119			case l.LossPct != nil || l.LatencyMs != nil:120				l.State = TopologyLinkStateUp121			}122			return l123		}124		out.Links = append(out.Links, link(TopologyLinkKindLan, clVertexLAN, clProbeGateway, defaultIf))125		lan = true126		probesHub := false127		for _, m := range []string{"net.latency", "net.loss"} {128			k := clValueKey(m, clProbeHub)129			_, inValues := x.values[k]130			_, declared := x.avail[k]131			probesHub = probesHub || inValues || declared132		}133		if wgIf != nil || probesHub {134			out.Links = append(out.Links, link(TopologyLinkKindWireguard, clVertexHub, clProbeHub, wgIf))135			hub = true136		}137	}138	// Infrastructure vertices exist only as link targets; their addresses are not observed.139	if lan {140		out.Nodes = append(out.Nodes, TopologyNode{Id: clVertexLAN, Kind: TopologyNodeKindLanGateway, Label: "LAN gateway"})141	}142	if hub {143		out.Nodes = append(out.Nodes, TopologyNode{Id: clVertexHub, Kind: TopologyNodeKindWgHub, Label: "WireGuard hub"})144	}145	return GetNetworkTopology200JSONResponse{Body: out}, nil146}147148// ListNetworkInterfaces flattens the inventory interfaces of the nodes,149// ordered by node alias then by position in the node's inventory.150func (h *clusterHandlers) ListNetworkInterfaces(ctx context.Context, req ListNetworkInterfacesRequestObject) (ListNetworkInterfacesResponseObject, error) {151	p := req.Params152	limit, err := clLimit(p.Limit)153	if err != nil {154		return nil, err155	}156	acc, err := h.clAccessFor(ctx)157	if err != nil {158		return nil, err159	}160	cur, err := clDecodeCursor(p.Cursor, "interfaces", 3)161	if err != nil {162		return nil, err163	}164	now := time.Now().UTC()165	b := &clSQL{args: h.clFreshArgs(now)}166	b.and("jsonb_typeof(n.inventory->'interfaces') = 'array'")167	b.and("jsonb_array_length(n.inventory->'interfaces') > 0")168	if p.NodeId != nil {169		b.and("n.id = " + b.arg(*p.NodeId))170	}171	after := -1172	if cur != nil {173		id, err := clCursorUUID(cur[1])174		if err != nil {175			return nil, err176		}177		if after, err = strconv.Atoi(cur[2]); err != nil || after < 0 {178			return nil, errClCursor179		}180		b.and("(lower(n.alias::text), n.id) >= (" + b.arg(cur[0]) + "::text, " + b.arg(id) + ")")181	}182	// Every selected node has at least one interface, so limit+2 nodes always183	// hold more than a page, even when the first one is partly consumed.184	nodeLimit := limit + 2185	cond := ""186	if len(b.conds) > 0 {187		cond = " and " + strings.Join(b.conds, " and ")188	}189	nodes, err := h.netNodes(ctx, now, cond, b.args[3:], ` order by lower(n.alias::text), n.id limit `+strconv.Itoa(nodeLimit))190	if err != nil {191		return nil, err192	}193	out := NetworkInterfaceList{Items: make([]NetworkInterface, 0, limit)}194	filter := acc.scoped(authz.NodesRead)195	more := len(nodes) == nodeLimit196	var last *string197fill:198	for i := range nodes {199		x := &nodes[i]200		first := 0201		if cur != nil && x.n.ID.String() == cur[1] {202			first = after + 1203		}204		visible := !filter || acc.can(authz.NodesRead, x.n.facets()...)205		all := clInterfaces(&x.n, h.clFresh(now, x.n.Seen), x.inv.Interfaces, x.values, acc.can(authz.NodesPrivateRead, x.n.facets()...))206		for j := first; j < len(all); j++ {207			if len(out.Items) == limit {208				more = true209				break fill210			}211			if visible {212				out.Items = append(out.Items, all[j])213			}214			last = clEncodeCursor("interfaces", strings.ToLower(x.n.Alias), x.n.ID.String(), strconv.Itoa(j))215		}216	}217	if more && last != nil {218		out.NextCursor = last219	}220	return ListNetworkInterfaces200JSONResponse{Body: out}, nil221}222
Files main
Menu

Theme