Files
rollcall/cmd/rollcall/infoblox.go
T
Ilker ManapandClaude Opus 5.5 008fa3f66f
CI / agent (push) Successful in 3s
CI / site (push) Successful in 2s
CI / go (push) Successful in 41s
Infoblox WAPI driver for the IPAM authority
ipam.provider infoblox: one record:host per address, named by its DNS
name and configured for DNS in dns_view ("-" = IPAM only); ownership is
the rollcall_machine extensible attribute, changed with extattrs+ so a
host's other attributes stay. Anything else on the address (a host, a
lease, a fixed address, a DHCP or reserved range, network/broadcast) makes
it taken. Delegated networks carry the rollcall attribute. WAPI paging.

The reconcile no longer compares fields an authority does not keep
(Infoblox has no prefix length or status on a host). Built from the WAPI
reference and tested against a fake WAPI; no real grid yet.

Closes #11

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 23:22:17 +01:00

335 lines
9.9 KiB
Go

package main
// Infoblox WAPI driver for the IPAM authority. Each Rollcall address is one
// record:host holding that address, named by its DNS name (rollcall-<address>
// without one) and configured for DNS when it has a name and dns_view is not
// "-" (Infoblox then publishes the A/AAAA record itself). Ownership is the extensible
// attribute machine_field (default rollcall_machine), which must be defined
// in the grid (String). Delegated networks carry the extensible attribute
// named by tag (default rollcall). An address is taken when anything that is
// not Rollcall's host uses it: a lease, a fixed address, a DHCP or reserved
// range, another host, the network or broadcast address.
//
// Documentation: Infoblox WAPI reference (v2.12): record:host, ipv4address,
// ipv6address, network, ipv6network; extensible attribute search (*EA~=),
// "extattrs+" to change attributes without dropping others, paging
// (_paging, _return_as_object, _page_id).
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
"time"
)
type infoblox struct {
base string // https://gm.example.com/wapi/v2.12
user, pass string
field, tag string
networkView string
dnsView string // "" = no DNS (IPAM-only hosts)
client *http.Client
}
func newInfoblox(c IPAMConfig) (*infoblox, error) {
if c.URL == "" || c.User == "" || c.PasswordFile == "" {
return nil, fmt.Errorf("infoblox: url, user and password_file are required")
}
pw, err := os.ReadFile(c.PasswordFile)
if err != nil {
return nil, fmt.Errorf("infoblox password: %w", err)
}
hc, err := httpClientCA(c.CAFile, 30*time.Second)
if err != nil {
return nil, fmt.Errorf("infoblox ca_file: %w", err)
}
base := strings.TrimRight(c.URL, "/")
if !strings.Contains(base, "/wapi/") {
base += "/wapi/v2.12"
}
dv := orDefault(c.DNSView, "default")
if dv == "-" {
dv = ""
}
return &infoblox{base: base, user: c.User, pass: strings.TrimSpace(string(pw)), field: c.field(), tag: c.tag(),
networkView: orDefault(c.NetworkView, "default"), dnsView: dv, client: hc}, nil
}
func (ib *infoblox) Name() string { return "infoblox" }
type ibError struct {
Code int
Body string
}
func (e *ibError) Error() string {
var x struct{ Text, Code string }
if json.Unmarshal([]byte(e.Body), &x) == nil && x.Text != "" {
return fmt.Sprintf("HTTP %d: %s", e.Code, trunc(x.Text, 300))
}
return fmt.Sprintf("HTTP %d: %s", e.Code, trunc(e.Body, 300))
}
// do calls WAPI; path is an object type or reference with its query.
func (ib *infoblox) do(ctx context.Context, method, path string, q url.Values, body, out any) error {
var rd io.Reader
if body != nil {
b, _ := json.Marshal(body)
rd = bytes.NewReader(b)
}
u := ib.base + "/" + strings.TrimPrefix(path, "/")
if len(q) > 0 {
u += "?" + q.Encode()
}
req, err := http.NewRequestWithContext(ctx, method, u, rd)
if err != nil {
return err
}
req.SetBasicAuth(ib.user, ib.pass)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
resp, err := ib.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
b, _ := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if resp.StatusCode >= 300 {
return &ibError{resp.StatusCode, string(b)}
}
if out != nil && len(b) > 0 {
return json.Unmarshal(b, out)
}
return nil
}
// all reads every object of a search through WAPI paging.
func (ib *infoblox) all(ctx context.Context, objType string, q url.Values) ([]obj, error) {
q.Set("_paging", "1")
q.Set("_return_as_object", "1")
q.Set("_max_results", "1000")
var out []obj
for {
var p struct {
Result []obj `json:"result"`
NextPageID string `json:"next_page_id"`
}
if err := ib.do(ctx, "GET", objType, q, nil, &p); err != nil {
return nil, err
}
out = append(out, p.Result...)
if p.NextPageID == "" {
return out, nil
}
q = url.Values{"_page_id": {p.NextPageID}}
}
}
const ibHostFields = "name,comment,extattrs,configure_for_dns,ipv4addrs,ipv6addrs,view"
func ibIs6(ip string) bool {
a, ok := parseAddr(ip)
return ok && a.Is6()
}
// owner is the machine of a host record, "" when it is not Rollcall's.
func (ib *infoblox) owner(h obj) string {
return str(asObj(asObj(h["extattrs"])[ib.field])["value"])
}
func (ib *infoblox) hostIP(h obj) string {
for _, k := range []string{"ipv4addrs", "ipv6addrs"} {
for _, a := range toList(h[k]) {
for _, f := range []string{"ipv4addr", "ipv6addr"} {
if s := str(asObj(a)[f]); s != "" {
if p, ok := parseAddr(s); ok {
return p.String()
}
}
}
}
}
return ""
}
func (ib *infoblox) toExt(h obj) extAddr {
e := extAddr{ID: str(h["_ref"]), IP: ib.hostIP(h), Machine: ib.owner(h), Desc: str(h["comment"])}
if n := strings.ToLower(str(h["name"])); n != ibHostName(e) {
e.DNSName = n
}
return e // Bits and Status are not kept by Infoblox (0 and "": not compared)
}
func ibHostName(a extAddr) string {
return "rollcall-" + strings.NewReplacer(".", "-", ":", "-").Replace(a.IP)
}
func (ib *infoblox) hostBody(a extAddr, create bool) obj {
dns := a.DNSName != "" && ib.dnsView != ""
// the name is the DNS name even when Infoblox does not publish it (IPAM only)
b := obj{"name": orDefault(a.DNSName, ibHostName(a)), "comment": trunc(a.Desc, 256), "configure_for_dns": dns}
if create {
addr := "ipv4addr"
if ibIs6(a.IP) {
addr = "ipv6addr"
}
b[addr+"s"] = []obj{{addr: a.IP, "configure_for_dhcp": false}}
b["extattrs"] = obj{ib.field: obj{"value": a.Machine}}
b["network_view"] = ib.networkView
if dns {
b["view"] = ib.dnsView
}
} else {
b["extattrs+"] = obj{ib.field: obj{"value": a.Machine}} // other attributes stay
}
return b
}
func (ib *infoblox) hostsAt(ctx context.Context, ip string) ([]obj, error) {
k := "ipv4addr"
if ibIs6(ip) {
k = "ipv6addr"
}
return ib.all(ctx, "record:host", url.Values{k: {ip}, "network_view": {ib.networkView}, "_return_fields": {ibHostFields}})
}
// used: references of whatever uses ip (empty when Infoblox has no network for it).
func (ib *infoblox) used(ctx context.Context, ip string) (status string, refs []string, types []string, err error) {
t := "ipv4address"
if ibIs6(ip) {
t = "ipv6address"
}
var res []obj
err = ib.do(ctx, "GET", t, url.Values{"ip_address": {ip}, "network_view": {ib.networkView}, "_return_fields": {"status,types,objects"}}, nil, &res)
if err != nil || len(res) == 0 {
return "", nil, nil, err
}
for _, r := range toList(res[0]["objects"]) {
refs = append(refs, str(r))
}
for _, x := range toList(res[0]["types"]) {
types = append(types, str(x))
}
return str(res[0]["status"]), refs, types, nil
}
func (ib *infoblox) Reserve(ctx context.Context, a extAddr) (bool, error) {
hosts, err := ib.hostsAt(ctx, a.IP)
if err != nil {
return false, err
}
mine := map[string]bool{}
var cur obj
for _, h := range hosts {
if ib.owner(h) == "" {
return true, nil // someone else's host
}
mine[str(h["_ref"])] = true
cur = h
}
status, refs, types, err := ib.used(ctx, a.IP)
if err != nil {
return false, err
}
for _, t := range types {
switch t {
case "NETWORK", "BROADCAST", "DHCP_RANGE", "RESERVED_RANGE":
return true, nil
}
}
others := 0
for _, r := range refs {
if !mine[r] {
others++
}
}
if others > 0 || (status == "USED" && len(refs) == 0 && len(mine) == 0) {
return true, nil // a lease, a fixed address, a discovered or conflicting use
}
if cur != nil {
e := ib.toExt(cur)
a.ID = e.ID
if e.DNSName != a.DNSName || e.Machine != a.Machine || e.Desc != a.Desc {
return false, ib.Update(ctx, a)
}
return false, nil
}
return false, ib.do(ctx, "POST", "record:host", nil, ib.hostBody(a, true), nil)
}
func (ib *infoblox) Owned(ctx context.Context) ([]extAddr, error) {
hs, err := ib.all(ctx, "record:host", url.Values{"*" + ib.field + "~": {"."}, "network_view": {ib.networkView}, "_return_fields": {ibHostFields}})
if err != nil {
return nil, err
}
out := []extAddr{}
for _, h := range hs {
if e := ib.toExt(h); e.Machine != "" && e.IP != "" {
out = append(out, e)
}
}
return out, nil
}
// Update renames, re-owns and re-describes a host; switching DNS on or off
// re-creates it (a host's DNS view is fixed at creation).
func (ib *infoblox) Update(ctx context.Context, a extAddr) error {
var cur obj
if err := ib.do(ctx, "GET", a.ID, url.Values{"_return_fields": {ibHostFields}}, nil, &cur); err != nil {
return err
}
if ib.owner(cur) == "" {
return fmt.Errorf("%s is no longer Rollcall's", a.IP)
}
if (cur["configure_for_dns"] == true) != (a.DNSName != "" && ib.dnsView != "") {
if err := ib.do(ctx, "DELETE", a.ID, nil, nil, nil); err != nil {
return err
}
return ib.do(ctx, "POST", "record:host", nil, ib.hostBody(a, true), nil)
}
return ib.do(ctx, "PUT", a.ID, nil, ib.hostBody(a, false), nil)
}
func (ib *infoblox) Delete(ctx context.Context, a extAddr) error {
var cur obj // re-read: only delete what is still ours
if err := ib.do(ctx, "GET", a.ID, url.Values{"_return_fields": {ibHostFields}}, nil, &cur); err != nil {
if e, ok := err.(*ibError); ok && (e.Code == 404 || e.Code == 400) {
return nil // gone (WAPI answers 400 for a reference that no longer exists)
}
return err
}
if ib.owner(cur) == "" {
return nil
}
return ib.do(ctx, "DELETE", a.ID, nil, nil, nil)
}
func (ib *infoblox) Prefixes(ctx context.Context) ([]extPrefix, error) {
out := []extPrefix{}
for _, t := range []string{"network", "ipv6network"} {
ns, err := ib.all(ctx, t, url.Values{"*" + ib.tag + "~": {"."}, "network_view": {ib.networkView}, "_return_fields": {"network,comment,extattrs"}})
if err != nil {
return nil, err
}
for _, n := range ns {
p, err := netip.ParsePrefix(str(n["network"]))
if err != nil {
continue
}
ea := asObj(n["extattrs"])
e := extPrefix{Prefix: p.Masked().String(), Desc: str(n["comment"]), Site: str(asObj(ea["Site"])["value"])}
e.VID, _ = strconv.Atoi(fmt.Sprint(asObj(ea["VLAN"])["value"]))
out = append(out, e)
}
}
return out, nil
}