Files
rollcall/cmd/rollcall/dhcpres_test.go
T
Ilker ManapandClaude Opus 5.5 dbb0d93dc7
CI / go (push) Successful in 41s
CI / agent (push) Successful in 2s
CI / site (push) Successful in 2s
Kea: reservations in memory when there is no hosts database
Found against Kea 3.0.5 in the lab: reservation-add answers "Host
database not available" on a server that keeps its configuration in a
file. Then reservations go into the running configuration
(operation-target memory) and config-write saves them; with a hosts
database nothing changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:13:05 +01:00

290 lines
10 KiB
Go

package main
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"testing"
)
func TestDesiredDHCPRes(t *testing.T) {
inv, _ := json.Marshal(obj{"network": []obj{{"name": "eth0", "mac": "52:54:00:00:00:01"}, {"name": "eth1", "mac": "52:54:00:00:00:02"}}})
mg := "10.214.0.50"
name := "fresh01"
m := &Machine{ID: "m-1", MACs: []string{"52:54:00:00:00:01", "52:54:00:00:00:02"}, MgmtIP: &mg, NodeName: &name, Inventory: inv}
subnets := []Subnet{{CIDR: "10.214.0.0/24", DHCPMode: "proxy"}, {CIDR: "10.215.0.0/24", DHCPMode: "proxy"}, {CIDR: "10.216.0.0/24"}, {CIDR: "fd00:214::/64", DHCPMode: "proxy"}}
ips := []IPAddr{
{IP: "10.214.0.50", MachineID: "m-1", Iface: "eth0"},
{IP: "10.215.0.50", MachineID: "m-1", Iface: "eth1"},
{IP: "10.216.0.50", MachineID: "m-1", Iface: "eth1"}, // served by Rollcall itself: no reservation
{IP: "fd00:214::50", MachineID: "m-1", Iface: "eth0"}, // DHCPv6 keys on DUIDs
{IP: "10.215.0.60", MachineID: "m-1", Iface: "bond0"}, // no single MAC
{IP: "10.214.0.70", MachineID: "", Kind: "reserved"}, // not a machine's
}
want, skipped := desiredDHCPRes(ips, subnets, map[string]*Machine{"m-1": m})
var got []string
for _, r := range want {
got = append(got, r.MAC+"="+r.IP+"/"+r.Hostname)
}
sort.Strings(got)
if strings.Join(got, " ") != "52:54:00:00:00:01=10.214.0.50/fresh01 52:54:00:00:00:02=10.215.0.50/fresh01" || len(skipped) != 1 {
t.Errorf("want %v skipped %v", got, skipped)
}
}
// fakeKea answers the control API like Kea 3.0's own socket (no "service")
// or a Control Agent (wants "service", answers with a list).
type fakeKea struct {
mu sync.Mutex
agent bool
noHooks bool
noHostDB bool // like Kea with a configuration file only: add/del need operation-target memory
hosts []obj
commands []string
written int
}
func (f *fakeKea) handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
if u, p, ok := r.BasicAuth(); !ok || u != "rollcall" || p != "pw" {
w.WriteHeader(401)
return
}
var req struct {
Command string `json:"command"`
Service []string `json:"service"`
Arguments json.RawMessage `json:"arguments"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
f.commands = append(f.commands, req.Command)
answer := func(o obj) {
if f.agent {
_ = json.NewEncoder(w).Encode([]obj{o})
return
}
_ = json.NewEncoder(w).Encode(o)
}
if f.agent && len(req.Service) == 0 {
answer(obj{"result": 1, "text": "service not specified"})
return
}
if !f.agent && len(req.Service) > 0 {
answer(obj{"result": 1, "text": "'service' parameter is not supported here"})
return
}
var args obj
_ = json.Unmarshal(req.Arguments, &args)
switch req.Command {
case "config-get":
answer(obj{"result": 0, "arguments": obj{"Dhcp4": obj{"subnet4": []obj{{"id": 7, "subnet": "10.214.0.0/24"}}}}})
case "reservation-get-all":
if f.noHooks {
answer(obj{"result": 2, "text": "'reservation-get-all' command not supported."})
return
}
answer(obj{"result": 0, "arguments": obj{"hosts": f.hosts}})
case "reservation-add", "reservation-del":
if f.noHostDB && args["operation-target"] != "memory" {
answer(obj{"result": 1, "text": "Host database not available, cannot add host."})
return
}
}
switch req.Command {
case "reservation-add":
res := args["reservation"].(map[string]any)
for _, h := range f.hosts {
if h["hw-address"] == res["hw-address"] || h["ip-address"] == res["ip-address"] {
answer(obj{"result": 1, "text": "Host already exists."})
return
}
}
f.hosts = append(f.hosts, res)
answer(obj{"result": 0, "text": "Host added."})
case "reservation-del":
for i, h := range f.hosts {
if h["hw-address"] == args["identifier"] {
f.hosts = append(f.hosts[:i], f.hosts[i+1:]...)
answer(obj{"result": 0, "text": "Host deleted."})
return
}
}
answer(obj{"result": 3, "text": "Host not deleted (not found)."})
case "config-write":
f.written++
answer(obj{"result": 0})
}
})
}
func keaFor(t *testing.T, f *fakeKea) (*keaProvider, func()) {
srv := httptest.NewServer(f.handler())
return &keaProvider{url: srv.URL, user: "rollcall", pass: "pw", hc: srv.Client(), persist: true}, srv.Close
}
func TestKeaReservations(t *testing.T) {
for _, agent := range []bool{false, true} {
f := &fakeKea{agent: agent, noHostDB: agent, hosts: []obj{
{"hw-address": "52:54:00:aa:aa:aa", "ip-address": "10.214.0.9", "hostname": "printer"}, // someone else's
{"hw-address": "52:54:00:00:00:09", "ip-address": "10.214.0.99", "user-context": obj{"rollcall": "m-old"}},
}}
k, done := keaFor(t, f)
a := &App{dhcpRes: k, dhcpResSt: &dhcpResState{}}
want := map[string]dhcpRes{}
for _, r := range []dhcpRes{
{MAC: "52:54:00:00:00:01", IP: "10.214.0.50", Hostname: "fresh01", Machine: "m-1", Subnet: "10.214.0.0/24"},
{MAC: "52:54:00:00:00:02", IP: "10.214.0.9", Machine: "m-2", Subnet: "10.214.0.0/24"}, // the printer's address
} {
want[r.key()] = r
}
rep := dhcpResReport{}
a.dhcpResWith(context.Background(), want, []string{"10.214.0.0/24"}, &rep)
if rep.Error != "" || strings.Join(rep.Put, ",") != "52:54:00:00:00:01 10.214.0.50" || len(rep.Conflicts) != 1 || strings.Join(rep.Deleted, ",") != "52:54:00:00:00:09 10.214.0.99" {
t.Errorf("agent=%v report %+v", agent, rep)
}
var added obj
for _, h := range f.hosts {
if h["hw-address"] == "52:54:00:00:00:01" {
added = h
}
}
wantWrites := 0 // a hosts database keeps reservations by itself
if f.noHostDB {
wantWrites = 1 // in memory: config-write saves them
}
if dig(added, "user-context", "rollcall") != "m-1" || added["hostname"] != "fresh01" || added["subnet-id"] != float64(7) || f.written != wantWrites {
t.Errorf("agent=%v added %v written %d", agent, added, f.written)
}
// a second pass changes nothing
rep = dhcpResReport{}
a.dhcpResWith(context.Background(), want, []string{"10.214.0.0/24"}, &rep)
if len(rep.Put)+len(rep.Deleted) != 0 || f.written != wantWrites {
t.Errorf("agent=%v second pass %+v", agent, rep)
}
done()
}
f := &fakeKea{noHooks: true}
k, done := keaFor(t, f)
defer done()
if _, _, err := k.Owned(context.Background(), []string{"10.214.0.0/24"}); err == nil || !strings.Contains(err.Error(), "host_cmds") {
t.Errorf("without host_cmds: %v", err)
}
if _, _, err := k.Owned(context.Background(), []string{"10.99.0.0/24"}); err == nil || !strings.Contains(err.Error(), "no subnet") {
t.Errorf("unknown subnet: %v", err)
}
}
// fakeUbus is rpcd's JSON-RPC with uci on "dhcp" and rc.
type fakeUbus struct {
mu sync.Mutex
sessions map[string]bool
sections map[string]map[string]any
n int
commits int
reloads int
logins int
}
func (f *fakeUbus) handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
b, _ := io.ReadAll(r.Body)
var req struct {
Params []json.RawMessage `json:"params"`
}
_ = json.Unmarshal(b, &req)
var sid, object, method string
var args map[string]any
_ = json.Unmarshal(req.Params[0], &sid)
_ = json.Unmarshal(req.Params[1], &object)
_ = json.Unmarshal(req.Params[2], &method)
_ = json.Unmarshal(req.Params[3], &args)
reply := func(v ...any) { _ = json.NewEncoder(w).Encode(obj{"jsonrpc": "2.0", "id": 1, "result": v}) }
if object == "session" && method == "login" {
if args["username"] != "rollcall" || args["password"] != "pw" {
reply(6)
return
}
f.logins++
s := "s" + strings.Repeat("x", f.logins)
f.sessions[s] = true
reply(0, obj{"ubus_rpc_session": s})
return
}
if !f.sessions[sid] {
_ = json.NewEncoder(w).Encode(obj{"jsonrpc": "2.0", "id": 1, "error": obj{"code": -32002, "message": "Access denied"}})
return
}
switch object + "." + method {
case "uci.get":
vals := obj{}
for k, v := range f.sections {
vals[k] = v
}
reply(0, obj{"values": vals})
case "uci.add":
f.n++
name := "cfg" + strings.Repeat("0", f.n)
sec := map[string]any{".type": "host"}
for k, v := range args["values"].(map[string]any) {
sec[k] = v
}
f.sections[name] = sec
reply(0, obj{"section": name})
case "uci.delete":
delete(f.sections, args["section"].(string))
reply(0)
case "uci.commit":
f.commits++
reply(0)
case "rc.init":
f.reloads++
reply(0)
default:
reply(3)
}
})
}
func TestOpenWrtReservations(t *testing.T) {
f := &fakeUbus{sessions: map[string]bool{}, sections: map[string]map[string]any{
"lan_printer": {".type": "host", "name": "printer", "mac": "52:54:00:aa:aa:aa", "ip": "10.214.0.9"},
"other_net": {".type": "host", "mac": []any{"52:54:00:bb:bb:bb"}, "ip": "192.168.9.9"},
}}
srv := httptest.NewServer(f.handler())
defer srv.Close()
o := &openwrtProvider{url: srv.URL + "/ubus", user: "rollcall", pass: "pw", hc: srv.Client()}
a := &App{dhcpRes: o, dhcpResSt: &dhcpResState{}}
want := map[string]dhcpRes{}
r := dhcpRes{MAC: "52:54:00:00:00:01", IP: "10.214.0.50", Hostname: "fresh01", Machine: "m-1", Subnet: "10.214.0.0/24"}
want[r.key()] = r
rep := dhcpResReport{}
a.dhcpResWith(context.Background(), want, []string{"10.214.0.0/24"}, &rep)
if rep.Error != "" || len(rep.Put) != 1 || f.commits != 1 || f.reloads != 1 {
t.Fatalf("report %+v commits %d reloads %d", rep, f.commits, f.reloads)
}
var mine map[string]any
for _, s := range f.sections {
if s["rollcall"] == "m-1" {
mine = s
}
}
if mine == nil || mine["ip"] != "10.214.0.50" || mine["name"] != "fresh01" {
t.Errorf("sections %v", f.sections)
}
// session expired: logs in again; the machine goes away: its section is deleted, the printer stays
f.sessions = map[string]bool{}
rep = dhcpResReport{}
a.dhcpResWith(context.Background(), map[string]dhcpRes{}, []string{"10.214.0.0/24"}, &rep)
if rep.Error != "" || len(rep.Deleted) != 1 || f.logins != 2 || f.sections["lan_printer"] == nil || f.sections["other_net"] == nil {
t.Errorf("report %+v logins %d sections %v", rep, f.logins, f.sections)
}
}