feat(agent): publish signed abuse observation feed
parent
219bfd32a9
commit
5ad82fd3ff
@ -0,0 +1,155 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"git.luoli.live/root/virt/agent/auth"
|
||||
"git.luoli.live/root/virt/agent/hypervisor"
|
||||
"git.luoli.live/root/virt/agent/networkobserve"
|
||||
)
|
||||
|
||||
var networkObservationGenerationPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
|
||||
|
||||
// NetworkObservationReader is the bounded, read-only surface exposed by the
|
||||
// in-memory collector. It deliberately offers no firewall, lifecycle, billing,
|
||||
// or other mutation method.
|
||||
type NetworkObservationReader interface {
|
||||
Generation() string
|
||||
Capability() networkobserve.Capability
|
||||
Batch(after uint64, limit int) (networkobserve.Batch, error)
|
||||
}
|
||||
|
||||
// SetNetworkObserver installs the process-local collector before the Agent
|
||||
// begins admitting requests. Observation is optional and never gates ordinary
|
||||
// VM scheduling or mutation endpoints.
|
||||
func (s *Server) SetNetworkObserver(observer NetworkObservationReader) error {
|
||||
if observer == nil || !networkObservationGenerationPattern.MatchString(observer.Generation()) {
|
||||
return errors.New("valid network observation reader is required")
|
||||
}
|
||||
if err := observer.Capability().Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
s.networkObserverMu.Lock()
|
||||
defer s.networkObserverMu.Unlock()
|
||||
if s.networkObserver != nil {
|
||||
return errors.New("network observation reader is already configured")
|
||||
}
|
||||
s.networkObserver = observer
|
||||
return nil
|
||||
}
|
||||
|
||||
type capabilitiesResponse struct {
|
||||
hypervisor.Capabilities
|
||||
NetworkAbuseObservation *networkobserve.Capability `json:"network_abuse_observation,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) capabilitiesResponse(base hypervisor.Capabilities) capabilitiesResponse {
|
||||
result := capabilitiesResponse{Capabilities: base}
|
||||
s.networkObserverMu.RLock()
|
||||
observer := s.networkObserver
|
||||
s.networkObserverMu.RUnlock()
|
||||
if observer != nil {
|
||||
capability := observer.Capability()
|
||||
result.NetworkAbuseObservation = &capability
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Server) routeNetworkObservations(w http.ResponseWriter, r *http.Request, segments []string, actor auth.Actor) {
|
||||
if len(segments) != 2 {
|
||||
writePreDispatchError(w, http.StatusNotFound, "not_found", "endpoint not found")
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet {
|
||||
methodOrNotFound(w, r, true, http.MethodGet)
|
||||
return
|
||||
}
|
||||
if !requireSuperAdminObservation(w, actor) {
|
||||
return
|
||||
}
|
||||
query, err := parseNetworkObservationQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
writePreDispatchError(w, http.StatusUnprocessableEntity, "invalid_network_observation_query", err.Error())
|
||||
return
|
||||
}
|
||||
s.networkObserverMu.RLock()
|
||||
observer := s.networkObserver
|
||||
s.networkObserverMu.RUnlock()
|
||||
if observer == nil {
|
||||
writePreDispatchError(w, http.StatusServiceUnavailable, "network_observation_unavailable", "network observation is not configured")
|
||||
return
|
||||
}
|
||||
after := query.after
|
||||
if query.generation != "" && query.generation != observer.Generation() {
|
||||
// A process restart creates a new generation. Old cursors must never be
|
||||
// interpreted in the new ring; the panel re-establishes its baseline.
|
||||
after = 0
|
||||
}
|
||||
batch, err := observer.Batch(after, query.limit)
|
||||
if err != nil || batch.Validate() != nil {
|
||||
writePreDispatchError(w, http.StatusServiceUnavailable, "network_observation_unavailable", "network observations could not be read safely")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, batch)
|
||||
}
|
||||
|
||||
type networkObservationQuery struct {
|
||||
generation string
|
||||
after uint64
|
||||
limit int
|
||||
}
|
||||
|
||||
func parseNetworkObservationQuery(raw string) (networkObservationQuery, error) {
|
||||
values, err := url.ParseQuery(raw)
|
||||
if err != nil {
|
||||
return networkObservationQuery{}, errors.New("query string is invalid")
|
||||
}
|
||||
for key, entries := range values {
|
||||
if key != "generation" && key != "after_cursor" && key != "limit" {
|
||||
return networkObservationQuery{}, errors.New("query contains an unknown field")
|
||||
}
|
||||
if len(entries) != 1 {
|
||||
return networkObservationQuery{}, errors.New("query field must occur exactly once")
|
||||
}
|
||||
}
|
||||
result := networkObservationQuery{limit: networkobserve.MaxBatchWindows}
|
||||
if entries, exists := values["generation"]; exists {
|
||||
generation := entries[0]
|
||||
if !networkObservationGenerationPattern.MatchString(generation) {
|
||||
return networkObservationQuery{}, errors.New("generation is invalid")
|
||||
}
|
||||
result.generation = generation
|
||||
}
|
||||
if entries, exists := values["after_cursor"]; exists {
|
||||
rawAfter := entries[0]
|
||||
after, parseErr := strconv.ParseUint(rawAfter, 10, 64)
|
||||
if parseErr != nil {
|
||||
return networkObservationQuery{}, errors.New("after_cursor is invalid")
|
||||
}
|
||||
result.after = after
|
||||
}
|
||||
if result.after != 0 && result.generation == "" {
|
||||
return networkObservationQuery{}, errors.New("generation is required with after_cursor")
|
||||
}
|
||||
if entries, exists := values["limit"]; exists {
|
||||
rawLimit := entries[0]
|
||||
limit, parseErr := strconv.Atoi(rawLimit)
|
||||
if parseErr != nil || limit <= 0 || limit > networkobserve.MaxBatchWindows {
|
||||
return networkObservationQuery{}, errors.New("limit is invalid")
|
||||
}
|
||||
result.limit = limit
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func requireSuperAdminObservation(w http.ResponseWriter, actor auth.Actor) bool {
|
||||
if actor.UserID < 1 || !actor.IsSuperAdmin || !actor.CanManage {
|
||||
writePreDispatchError(w, http.StatusForbidden, "forbidden", "actor is not authorized to read host network observations")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -0,0 +1,187 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.luoli.live/root/virt/agent/auth"
|
||||
"git.luoli.live/root/virt/agent/hypervisor"
|
||||
"git.luoli.live/root/virt/agent/networkobserve"
|
||||
)
|
||||
|
||||
const testObservationGeneration = "0123456789abcdef0123456789abcdef"
|
||||
|
||||
type recordingNetworkObserver struct {
|
||||
mu sync.Mutex
|
||||
generation string
|
||||
capability networkobserve.Capability
|
||||
lastAfter uint64
|
||||
lastLimit int
|
||||
calls int
|
||||
}
|
||||
|
||||
func (observer *recordingNetworkObserver) Generation() string { return observer.generation }
|
||||
|
||||
func (observer *recordingNetworkObserver) Capability() networkobserve.Capability {
|
||||
return observer.capability
|
||||
}
|
||||
|
||||
func (observer *recordingNetworkObserver) Batch(after uint64, limit int) (networkobserve.Batch, error) {
|
||||
observer.mu.Lock()
|
||||
observer.lastAfter = after
|
||||
observer.lastLimit = limit
|
||||
observer.calls++
|
||||
observer.mu.Unlock()
|
||||
return networkobserve.Batch{
|
||||
ContractVersion: networkobserve.ContractVersion,
|
||||
CollectorGeneration: observer.generation,
|
||||
Capability: observer.capability,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func availableObservationCapability() networkobserve.Capability {
|
||||
return networkobserve.Capability{
|
||||
Name: networkobserve.CapabilityName, ContractVersion: networkobserve.ContractVersion,
|
||||
Available: true, NoPayload: true, IPv4: true, IPv6: true, Conntrack: true,
|
||||
PolicyDecisions: false, BucketSeconds: networkobserve.BucketSeconds,
|
||||
}
|
||||
}
|
||||
|
||||
func (*testHypervisor) Capabilities(context.Context) (hypervisor.Capabilities, error) {
|
||||
return hypervisor.Capabilities{Backend: "test"}, nil
|
||||
}
|
||||
|
||||
func TestNetworkObservationRouteRequiresExactSuperAdminActor(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
observer := &recordingNetworkObserver{
|
||||
generation: testObservationGeneration,
|
||||
capability: availableObservationCapability(),
|
||||
}
|
||||
if err := api.handler.SetNetworkObserver(observer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, actor := range []auth.Actor{
|
||||
{UserID: 1, CanManage: true},
|
||||
{UserID: 1, IsSuperAdmin: true},
|
||||
{UserID: 0, IsSuperAdmin: true, CanManage: true},
|
||||
} {
|
||||
response := api.request(t, http.MethodGet, "/v1/network-observations", nil, actor)
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("actor %#v status=%d body=%s", actor, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if observer.calls != 0 {
|
||||
t.Fatalf("unauthorized requests reached observer: %d", observer.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkObservationIsOptionalAndUnavailableWithoutCollector(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
actor := auth.Actor{UserID: 1, IsSuperAdmin: true, CanManage: true}
|
||||
response := api.request(t, http.MethodGet, "/v1/network-observations", nil, actor)
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("observation status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
capabilities := api.request(t, http.MethodGet, "/v1/capabilities", nil, auth.Actor{UserID: 1})
|
||||
if capabilities.Code != http.StatusOK {
|
||||
t.Fatalf("capability status=%d body=%s", capabilities.Code, capabilities.Body.String())
|
||||
}
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal(capabilities.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exists := payload["network_abuse_observation"]; exists {
|
||||
t.Fatalf("unconfigured optional capability leaked into response: %s", capabilities.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkObservationRouteResetsOnlyStaleGenerationCursor(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
observer := &recordingNetworkObserver{
|
||||
generation: testObservationGeneration,
|
||||
capability: availableObservationCapability(),
|
||||
}
|
||||
if err := api.handler.SetNetworkObserver(observer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actor := auth.Actor{UserID: 1, IsSuperAdmin: true, CanManage: true}
|
||||
|
||||
response := api.request(t, http.MethodGet,
|
||||
"/v1/network-observations?generation=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&after_cursor=77&limit=12",
|
||||
nil, actor)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("stale generation status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if observer.lastAfter != 0 || observer.lastLimit != 12 {
|
||||
t.Fatalf("stale generation request = after %d limit %d", observer.lastAfter, observer.lastLimit)
|
||||
}
|
||||
|
||||
response = api.request(t, http.MethodGet,
|
||||
"/v1/network-observations?generation="+testObservationGeneration+"&after_cursor=77&limit=4",
|
||||
nil, actor)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("current generation status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
if observer.lastAfter != 77 || observer.lastLimit != 4 {
|
||||
t.Fatalf("current generation request = after %d limit %d", observer.lastAfter, observer.lastLimit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkObservationQueryIsStrictAndBounded(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
observer := &recordingNetworkObserver{
|
||||
generation: testObservationGeneration,
|
||||
capability: availableObservationCapability(),
|
||||
}
|
||||
if err := api.handler.SetNetworkObserver(observer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actor := auth.Actor{UserID: 1, IsSuperAdmin: true, CanManage: true}
|
||||
for _, target := range []string{
|
||||
"/v1/network-observations?after_cursor=1",
|
||||
"/v1/network-observations?limit=0",
|
||||
"/v1/network-observations?limit=65",
|
||||
"/v1/network-observations?limit=1&limit=2",
|
||||
"/v1/network-observations?unknown=1",
|
||||
"/v1/network-observations?generation=ABCDEF",
|
||||
"/v1/network-observations?generation=",
|
||||
"/v1/network-observations?after_cursor=",
|
||||
"/v1/network-observations?limit=",
|
||||
} {
|
||||
response := api.request(t, http.MethodGet, target, nil, actor)
|
||||
if response.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("target %q status=%d body=%s", target, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if observer.calls != 0 {
|
||||
t.Fatalf("invalid requests reached observer: %d", observer.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapabilitiesAdvertiseOptionalObservationWithoutSchedulingGate(t *testing.T) {
|
||||
api := newTestAPI(t)
|
||||
observer := &recordingNetworkObserver{
|
||||
generation: testObservationGeneration,
|
||||
capability: availableObservationCapability(),
|
||||
}
|
||||
if err := api.handler.SetNetworkObserver(observer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response := api.request(t, http.MethodGet, "/v1/capabilities", nil, auth.Actor{UserID: 1})
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("capability status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
var payload struct {
|
||||
Backend string `json:"backend"`
|
||||
Observation networkobserve.Capability `json:"network_abuse_observation"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Backend != "test" || payload.Observation != observer.capability {
|
||||
t.Fatalf("capability response=%#v", payload)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,192 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"sync"
|
||||
|
||||
"git.luoli.live/root/virt/agent/hypervisor"
|
||||
"git.luoli.live/root/virt/agent/networkobserve"
|
||||
)
|
||||
|
||||
type networkObservationInventoryBackend interface {
|
||||
ListVMs(context.Context) ([]hypervisor.VMMetadata, error)
|
||||
GetMetrics(context.Context, string) (hypervisor.Metrics, error)
|
||||
}
|
||||
|
||||
// hypervisorNetworkObservationInventory builds attribution only from the one
|
||||
// canonical public-network identity frozen in managed libvirt metadata. VPC
|
||||
// addresses and interface discovery heuristics never enter this inventory.
|
||||
type hypervisorNetworkObservationInventory struct {
|
||||
backend networkObservationInventoryBackend
|
||||
}
|
||||
|
||||
func (inventory hypervisorNetworkObservationInventory) NetworkObservationInventory(ctx context.Context) ([]networkobserve.VMTarget, error) {
|
||||
if inventory.backend == nil {
|
||||
return nil, errors.New("network observation hypervisor is unavailable")
|
||||
}
|
||||
vms, err := inventory.backend.ListVMs(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list managed VMs for network observation: %w", err)
|
||||
}
|
||||
targets := make([]networkobserve.VMTarget, 0, len(vms))
|
||||
for _, vm := range vms {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
public, err := vm.PublicNetwork.Canonical()
|
||||
if err != nil {
|
||||
// An invalid frozen identity makes host-wide address attribution
|
||||
// ambiguous. Fail this observation cycle instead of guessing from a
|
||||
// bridge, MAC, domain name, or private/VPC address.
|
||||
return nil, fmt.Errorf("VM %s has invalid public network identity: %w", vm.UUID, err)
|
||||
}
|
||||
ipv4, err := publicAddress(public.IPv4.AddressCIDR, true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("VM %s IPv4 identity: %w", vm.UUID, err)
|
||||
}
|
||||
ipv6, err := publicAddress(public.IPv6.AddressCIDR, false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("VM %s IPv6 identity: %w", vm.UUID, err)
|
||||
}
|
||||
target := networkobserve.VMTarget{UUID: vm.UUID, IPv4: ipv4, IPv6: ipv6}
|
||||
metrics, metricsErr := inventory.backend.GetMetrics(ctx, vm.UUID)
|
||||
if metricsErr == nil && metrics.UUID == vm.UUID {
|
||||
target.Interface = interfaceCounters(metrics)
|
||||
}
|
||||
// A stopped domain or one transiently unavailable metrics call does not
|
||||
// remove its exact public address from attribution. Nil counters make the
|
||||
// window explicitly incomplete while the other VMs remain observable.
|
||||
targets = append(targets, target)
|
||||
}
|
||||
return targets, nil
|
||||
}
|
||||
|
||||
func publicAddress(cidr string, ipv4 bool) (netip.Addr, error) {
|
||||
prefix, err := netip.ParsePrefix(cidr)
|
||||
if err != nil || prefix.Addr().Is4() != ipv4 || prefix.Addr().Is4In6() {
|
||||
return netip.Addr{}, errors.New("address is not a canonical public prefix")
|
||||
}
|
||||
return prefix.Addr(), nil
|
||||
}
|
||||
|
||||
func interfaceCounters(metrics hypervisor.Metrics) networkobserve.InterfaceCounters {
|
||||
rxBytes, txBytes := metrics.RXBytes, metrics.TXBytes
|
||||
return networkobserve.InterfaceCounters{
|
||||
RXBytes: &rxBytes, TXBytes: &txBytes,
|
||||
RXPackets: cloneUint64(metrics.RXPackets), TXPackets: cloneUint64(metrics.TXPackets),
|
||||
RXErrors: cloneUint64(metrics.RXErrors), TXErrors: cloneUint64(metrics.TXErrors),
|
||||
RXDrops: cloneUint64(metrics.RXDrops), TXDrops: cloneUint64(metrics.TXDrops),
|
||||
}
|
||||
}
|
||||
|
||||
func cloneUint64(value *uint64) *uint64 {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
copy := *value
|
||||
return ©
|
||||
}
|
||||
|
||||
type unavailableConntrackSource struct{ err error }
|
||||
|
||||
func (source unavailableConntrackSource) Probe(context.Context) (networkobserve.ProbeEvidence, error) {
|
||||
return networkobserve.ProbeEvidence{}, source.err
|
||||
}
|
||||
|
||||
func (source unavailableConntrackSource) Snapshot(context.Context) (networkobserve.KernelSnapshot, error) {
|
||||
return networkobserve.KernelSnapshot{}, source.err
|
||||
}
|
||||
|
||||
func (unavailableConntrackSource) Close() error { return nil }
|
||||
|
||||
type networkObservationRuntime struct {
|
||||
collector *networkobserve.Collector
|
||||
|
||||
mu sync.Mutex
|
||||
cancel context.CancelFunc
|
||||
done chan error
|
||||
started bool
|
||||
}
|
||||
|
||||
func newNetworkObservationRuntime(hv networkObservationInventoryBackend) (*networkObservationRuntime, error) {
|
||||
generation, err := networkobserve.NewGeneration()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create network observation generation: %w", err)
|
||||
}
|
||||
source, err := networkobserve.OpenNetlinkSource()
|
||||
if err != nil {
|
||||
return newNetworkObservationRuntimeWithSource(hv, unavailableConntrackSource{err: err}, generation)
|
||||
}
|
||||
return newNetworkObservationRuntimeWithSource(hv, source, generation)
|
||||
}
|
||||
|
||||
func newNetworkObservationRuntimeWithSource(hv networkObservationInventoryBackend, source networkobserve.ConntrackSource,
|
||||
generation string) (*networkObservationRuntime, error) {
|
||||
if source == nil {
|
||||
return nil, errors.New("network observation source is required")
|
||||
}
|
||||
collector, err := networkobserve.NewCollector(
|
||||
hypervisorNetworkObservationInventory{backend: hv}, source, generation,
|
||||
networkobserve.DefaultCollectorConfig(),
|
||||
)
|
||||
if err != nil {
|
||||
_ = source.Close()
|
||||
return nil, fmt.Errorf("initialize network observation collector: %w", err)
|
||||
}
|
||||
return &networkObservationRuntime{collector: collector}, nil
|
||||
}
|
||||
|
||||
func (runtime *networkObservationRuntime) Start(parent context.Context) error {
|
||||
if runtime == nil || runtime.collector == nil {
|
||||
return errors.New("network observation runtime is unavailable")
|
||||
}
|
||||
runtime.mu.Lock()
|
||||
defer runtime.mu.Unlock()
|
||||
if runtime.started {
|
||||
return errors.New("network observation runtime is already started")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
runtime.cancel = cancel
|
||||
runtime.done = make(chan error, 1)
|
||||
runtime.started = true
|
||||
go func() {
|
||||
runtime.done <- runtime.collector.Run(ctx)
|
||||
close(runtime.done)
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (runtime *networkObservationRuntime) Shutdown(ctx context.Context) error {
|
||||
if runtime == nil || runtime.collector == nil {
|
||||
return nil
|
||||
}
|
||||
runtime.mu.Lock()
|
||||
started, cancel, done := runtime.started, runtime.cancel, runtime.done
|
||||
runtime.mu.Unlock()
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
closeResult := make(chan error, 1)
|
||||
go func() { closeResult <- runtime.collector.Close() }()
|
||||
var closeErr error
|
||||
select {
|
||||
case closeErr = <-closeResult:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
if !started {
|
||||
return closeErr
|
||||
}
|
||||
select {
|
||||
case runErr := <-done:
|
||||
if runErr != nil && !errors.Is(runErr, context.Canceled) {
|
||||
return errors.Join(closeErr, runErr)
|
||||
}
|
||||
return closeErr
|
||||
case <-ctx.Done():
|
||||
return errors.Join(closeErr, ctx.Err())
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,132 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.luoli.live/root/virt/agent/hypervisor"
|
||||
"git.luoli.live/root/virt/agent/networkobserve"
|
||||
"git.luoli.live/root/virt/agent/publicnetwork"
|
||||
)
|
||||
|
||||
const observationTestGeneration = "0123456789abcdef0123456789abcdef"
|
||||
|
||||
type observationInventoryBackend struct {
|
||||
vms []hypervisor.VMMetadata
|
||||
metrics map[string]hypervisor.Metrics
|
||||
metricErrs map[string]error
|
||||
}
|
||||
|
||||
func (backend observationInventoryBackend) ListVMs(context.Context) ([]hypervisor.VMMetadata, error) {
|
||||
return append([]hypervisor.VMMetadata(nil), backend.vms...), nil
|
||||
}
|
||||
|
||||
func (backend observationInventoryBackend) GetMetrics(_ context.Context, uuid string) (hypervisor.Metrics, error) {
|
||||
if err := backend.metricErrs[uuid]; err != nil {
|
||||
return hypervisor.Metrics{}, err
|
||||
}
|
||||
return backend.metrics[uuid], nil
|
||||
}
|
||||
|
||||
type observationSource struct{ closed atomic.Int32 }
|
||||
|
||||
func (*observationSource) Probe(context.Context) (networkobserve.ProbeEvidence, error) {
|
||||
return networkobserve.ProbeEvidence{Conntrack: true, IPv4: true, IPv6: true}, nil
|
||||
}
|
||||
|
||||
func (*observationSource) Snapshot(context.Context) (networkobserve.KernelSnapshot, error) {
|
||||
return networkobserve.KernelSnapshot{}, nil
|
||||
}
|
||||
|
||||
func (source *observationSource) Close() error {
|
||||
source.closed.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func observationPublicNetwork(ipv4, ipv6 string) publicnetwork.Intent {
|
||||
return publicnetwork.Intent{
|
||||
Contract: publicnetwork.ContractVersion, NetworkSelector: "bridge:br0",
|
||||
IPv4: publicnetwork.AddressIntent{
|
||||
PoolKey: "11111111111111111111111111111111", PoolCIDR: "8.8.8.0/24",
|
||||
AddressCIDR: ipv4 + "/24", Gateway: "8.8.8.1",
|
||||
},
|
||||
IPv6: publicnetwork.AddressIntent{
|
||||
PoolKey: "22222222222222222222222222222222", PoolCIDR: "2606:4700:4700::/64",
|
||||
AddressCIDR: ipv6 + "/64", Gateway: "2606:4700:4700::1",
|
||||
},
|
||||
DNSServers: []string{"1.1.1.1", "2606:4700:4700::1111"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestHypervisorObservationInventoryKeepsExactIdentityWhenMetricsUnavailable(t *testing.T) {
|
||||
const first = "123e4567-e89b-42d3-a456-426614174000"
|
||||
const second = "223e4567-e89b-42d3-a456-426614174000"
|
||||
rxPackets := uint64(12)
|
||||
backend := observationInventoryBackend{
|
||||
vms: []hypervisor.VMMetadata{
|
||||
{UUID: first, PublicNetwork: observationPublicNetwork("8.8.8.10", "2606:4700:4700::10")},
|
||||
{UUID: second, PublicNetwork: observationPublicNetwork("8.8.8.11", "2606:4700:4700::11")},
|
||||
},
|
||||
metrics: map[string]hypervisor.Metrics{
|
||||
first: {UUID: first, RXBytes: 100, TXBytes: 200, RXPackets: &rxPackets},
|
||||
},
|
||||
metricErrs: map[string]error{second: errors.New("domain is stopped")},
|
||||
}
|
||||
inventory := hypervisorNetworkObservationInventory{backend: backend}
|
||||
targets, err := inventory.NetworkObservationInventory(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(targets) != 2 || targets[0].IPv4.String() != "8.8.8.10" ||
|
||||
targets[1].IPv6.String() != "2606:4700:4700::11" {
|
||||
t.Fatalf("targets=%#v", targets)
|
||||
}
|
||||
if targets[0].Interface.RXBytes == nil || *targets[0].Interface.RXBytes != 100 ||
|
||||
targets[0].Interface.RXPackets == nil || *targets[0].Interface.RXPackets != 12 {
|
||||
t.Fatalf("first counters=%#v", targets[0].Interface)
|
||||
}
|
||||
if targets[1].Interface.RXBytes != nil || targets[1].Interface.TXBytes != nil {
|
||||
t.Fatalf("failed metrics must remain explicit nil counters: %#v", targets[1].Interface)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHypervisorObservationInventoryNeverGuessesInvalidPublicIdentity(t *testing.T) {
|
||||
backend := observationInventoryBackend{
|
||||
vms: []hypervisor.VMMetadata{{
|
||||
UUID: "123e4567-e89b-42d3-a456-426614174000",
|
||||
PublicNetwork: observationPublicNetwork("10.0.0.10", "2606:4700:4700::10"),
|
||||
}},
|
||||
metrics: map[string]hypervisor.Metrics{}, metricErrs: map[string]error{},
|
||||
}
|
||||
_, err := (hypervisorNetworkObservationInventory{backend: backend}).NetworkObservationInventory(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("invalid public identity was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkObservationRuntimeStopsBeforeHypervisorClosure(t *testing.T) {
|
||||
source := &observationSource{}
|
||||
runtime, err := newNetworkObservationRuntimeWithSource(
|
||||
observationInventoryBackend{metrics: map[string]hypervisor.Metrics{}, metricErrs: map[string]error{}},
|
||||
source, observationTestGeneration,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parent, cancelParent := context.WithCancel(context.Background())
|
||||
if err := runtime.Start(parent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancelParent()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := runtime.Shutdown(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if source.closed.Load() != 1 {
|
||||
t.Fatalf("source close count=%d", source.closed.Load())
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue