Files
rollcall/cmd/rollcall/dhcpres_kea.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

234 lines
6.7 KiB
Go

package main
// Kea: the control API (Kea 3.0's own HTTP control socket, or the Control
// Agent before it) with the host_cmds hook. Subnet ids come from
// config-get; reservations carry user-context {"rollcall": <machine>}.
// A server with a hosts database keeps them there; one without answers
// "Host database not available", and then they go into its running
// configuration (operation-target memory), which config-write saves.
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/netip"
"strings"
)
type keaProvider struct {
url, user, pass string
hc *http.Client
persist bool
service *bool // send "service": ["dhcp4"] (a Control Agent wants it; Kea 3.0's own socket refuses it)
memory bool // no hosts database: reservations go into the running configuration
}
func (k *keaProvider) Name() string { return "kea" }
type keaAnswer struct {
Result int `json:"result"`
Text string `json:"text"`
Arguments json.RawMessage `json:"arguments"`
}
// call sends one command; result 0 (success) and 3 (empty) are not errors.
func (k *keaProvider) call(ctx context.Context, command string, args any) (*keaAnswer, error) {
try := func(service bool) (*keaAnswer, error) {
body := map[string]any{"command": command}
if args != nil {
body["arguments"] = args
}
if service {
body["service"] = []string{"dhcp4"}
}
b, _ := json.Marshal(body)
req, err := http.NewRequestWithContext(ctx, "POST", k.url, bytes.NewReader(b))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if k.user != "" {
req.SetBasicAuth(k.user, k.pass)
}
resp, err := k.hc.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, _ := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if resp.StatusCode >= 300 {
return nil, fmt.Errorf("kea %s: %s %s", command, resp.Status, oneLine(string(data)))
}
var many []keaAnswer // the Control Agent answers with a list, one per service
if json.Unmarshal(data, &many) == nil && len(many) > 0 {
return &many[0], nil
}
var one keaAnswer
if err := json.Unmarshal(data, &one); err != nil {
return nil, fmt.Errorf("kea %s: %w", command, err)
}
return &one, nil
}
if k.service == nil { // learn once whether this endpoint wants "service"
ans, err := try(false)
if err == nil && !(ans.Result == 1 && strings.Contains(strings.ToLower(ans.Text), "service")) {
f := false
k.service = &f
return ans, nil
}
t := true
k.service = &t
}
return try(*k.service)
}
func (k *keaProvider) ok(ctx context.Context, command string, args any) (*keaAnswer, error) {
ans, err := k.call(ctx, command, args)
if err != nil {
return nil, err
}
switch ans.Result {
case 0, 3:
return ans, nil
case 2:
return nil, fmt.Errorf("kea does not know %s (the host_cmds hook is needed: open source since Kea 3.0)", command)
}
return nil, fmt.Errorf("kea %s: %s", command, ans.Text)
}
// subnetIDs maps CIDR -> Kea subnet id (also inside shared networks).
func (k *keaProvider) subnetIDs(ctx context.Context) (map[string]int, error) {
ans, err := k.ok(ctx, "config-get", nil)
if err != nil {
return nil, err
}
type sub struct {
ID int `json:"id"`
Subnet string `json:"subnet"`
}
var cfg struct {
Dhcp4 struct {
Subnet4 []sub `json:"subnet4"`
SharedNetworks []struct {
Subnet4 []sub `json:"subnet4"`
} `json:"shared-networks"`
} `json:"Dhcp4"`
}
if err := json.Unmarshal(ans.Arguments, &cfg); err != nil {
return nil, fmt.Errorf("kea config-get: %w", err)
}
out := map[string]int{}
add := func(s sub) {
if p, err := netip.ParsePrefix(s.Subnet); err == nil {
out[p.Masked().String()] = s.ID
}
}
for _, s := range cfg.Dhcp4.Subnet4 {
add(s)
}
for _, n := range cfg.Dhcp4.SharedNetworks {
for _, s := range n.Subnet4 {
add(s)
}
}
return out, nil
}
func (k *keaProvider) Owned(ctx context.Context, subnets []string) ([]dhcpRes, []dhcpRes, error) {
ids, err := k.subnetIDs(ctx)
if err != nil {
return nil, nil, err
}
var owned, foreign []dhcpRes
for _, cidr := range subnets {
id, ok := ids[cidr]
if !ok {
return nil, nil, fmt.Errorf("kea serves no subnet %s", cidr)
}
ans, err := k.ok(ctx, "reservation-get-all", map[string]any{"subnet-id": id})
if err != nil {
return nil, nil, err
}
var got struct {
Hosts []struct {
HWAddress string `json:"hw-address"`
IPAddress string `json:"ip-address"`
Hostname string `json:"hostname"`
UserContext map[string]any `json:"user-context"`
} `json:"hosts"`
}
_ = json.Unmarshal(ans.Arguments, &got)
for _, h := range got.Hosts {
r := dhcpRes{MAC: normMAC(h.HWAddress), IP: h.IPAddress, Hostname: h.Hostname, Subnet: cidr}
if m, ok := h.UserContext["rollcall"].(string); ok && m != "" {
r.Machine = m
owned = append(owned, r)
} else {
foreign = append(foreign, r)
}
}
}
return owned, foreign, nil
}
func (k *keaProvider) subnetID(ctx context.Context, cidr string) (int, error) {
ids, err := k.subnetIDs(ctx)
if err != nil {
return 0, err
}
id, ok := ids[cidr]
if !ok {
return 0, fmt.Errorf("kea serves no subnet %s", cidr)
}
return id, nil
}
func (k *keaProvider) Put(ctx context.Context, r dhcpRes) error {
id, err := k.subnetID(ctx, r.Subnet)
if err != nil {
return err
}
res := map[string]any{"subnet-id": id, "hw-address": r.MAC, "ip-address": r.IP, "user-context": map[string]any{"rollcall": r.Machine}}
if r.Hostname != "" {
res["hostname"] = r.Hostname
}
return k.change(ctx, "reservation-add", map[string]any{"reservation": res})
}
// change runs reservation-add/-del against the hosts database, or the
// configuration in memory when the server has no hosts database.
func (k *keaProvider) change(ctx context.Context, command string, args map[string]any) error {
if k.memory {
args["operation-target"] = "memory"
}
_, err := k.ok(ctx, command, args)
if err != nil && !k.memory && strings.Contains(err.Error(), "database not available") {
k.memory = true
args["operation-target"] = "memory"
_, err = k.ok(ctx, command, args)
}
return err
}
func (k *keaProvider) Delete(ctx context.Context, r dhcpRes) error {
id, err := k.subnetID(ctx, r.Subnet)
if err != nil {
return err
}
return k.change(ctx, "reservation-del", map[string]any{"subnet-id": id, "identifier-type": "hw-address", "identifier": r.MAC})
}
func (k *keaProvider) Done(ctx context.Context) error {
if !k.persist || !k.memory { // a hosts database keeps them by itself
return nil
}
if _, err := k.ok(ctx, "config-write", map[string]any{}); err != nil {
return errors.New("reservations are in effect but not saved: " + err.Error())
}
return nil
}