Files
rollcall/cmd/rollcall/layout.go
T
Ilker ManapandClaude Opus 5.5 148c602b82
CI / go (push) Successful in 42s
CI / agent (push) Successful in 3s
CI / site (push) Successful in 2s
Sites on a map, rooms, floor plans with racks you can place
The Sites page shows sites on an OpenStreetMap map (Leaflet 1.9.4 in the
binary, checked against cdnjs's SRI; the CSP allows OSM tiles and the
tile layer sends a referrer as OSM's policy asks). A site opens its
rooms, a room its floor plan: racks on 600 mm tiles, one wide and two
deep, front edge marked, coloured by their machines with a bar for the
units used; a rack opens its front, and the rack is part of the URL.
An edit mode drags racks into place and rotates them; racks nobody
placed are laid out in rows facing alternate aisles.

With NetBox as the IPAM authority, sites (coordinates, address),
locations and racks are read on every reconcile, never written back.
Otherwise sites are placed by clicking the map. Rack positions are
Rollcall's (NetBox has none).

Checked in headless Chrome with a synthetic site, including a scripted
drag, rotate and save of a rack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 00:20:56 +01:00

290 lines
9.2 KiB
Go

package main
// Physical layout: sites with coordinates (the map), rooms and where each
// rack stands in its room (the floor plan). With NetBox as the IPAM
// authority, sites (name, coordinates, address), locations (rooms) and racks
// (name, height) are read from it on every reconcile and never written back;
// otherwise they are entered here. Rack positions are Rollcall's either way:
// NetBox has no floor coordinates. A position is in floor tiles (600 mm): a
// rack is one tile wide and two deep, its front facing N, E, S or W.
//
// A machine's building is matched to a site by name or slug, ignoring case.
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
)
type Site struct {
Name string `json:"name"`
Slug string `json:"slug,omitempty"`
Lat *float64 `json:"lat"`
Lon *float64 `json:"lon"`
Address string `json:"address,omitempty"`
Source string `json:"source"` // local | netbox
}
type Room struct {
Building string `json:"building"`
Name string `json:"name"`
Width int `json:"width"` // floor tiles; 0 = from the racks
Depth int `json:"depth"`
Source string `json:"source"`
}
// ---------------------------------------------------------------- store
func (s *Store) Sites(ctx context.Context) ([]Site, error) {
rows, err := s.pool.Query(ctx, `SELECT name, coalesce(slug,''), lat, lon, coalesce(address,''), source FROM sites ORDER BY name`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Site{}
for rows.Next() {
var x Site
if err := rows.Scan(&x.Name, &x.Slug, &x.Lat, &x.Lon, &x.Address, &x.Source); err != nil {
return nil, err
}
out = append(out, x)
}
return out, rows.Err()
}
// PutSite stores a site; coordinates that are nil keep the stored ones.
func (s *Store) PutSite(ctx context.Context, x Site) error {
_, err := s.pool.Exec(ctx, `INSERT INTO sites(name, slug, lat, lon, address, source) VALUES ($1, nullif($2,''), $3, $4, nullif($5,''), $6)
ON CONFLICT (name) DO UPDATE SET slug=coalesce(nullif($2,''), sites.slug), lat=coalesce($3, sites.lat), lon=coalesce($4, sites.lon),
address=coalesce(nullif($5,''), sites.address), source=$6`, x.Name, x.Slug, x.Lat, x.Lon, x.Address, orDefault(x.Source, "local"))
return err
}
func (s *Store) DeleteSite(ctx context.Context, name string) error {
_, err := s.pool.Exec(ctx, `DELETE FROM sites WHERE name=$1`, name)
return err
}
func (s *Store) Rooms(ctx context.Context) ([]Room, error) {
rows, err := s.pool.Query(ctx, `SELECT building, name, width, depth, source FROM rooms ORDER BY building, name`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Room{}
for rows.Next() {
var x Room
if err := rows.Scan(&x.Building, &x.Name, &x.Width, &x.Depth, &x.Source); err != nil {
return nil, err
}
out = append(out, x)
}
return out, rows.Err()
}
// PutRoom stores a room; a size of 0 keeps the stored one.
func (s *Store) PutRoom(ctx context.Context, x Room) error {
_, err := s.pool.Exec(ctx, `INSERT INTO rooms(building, name, width, depth, source) VALUES ($1,$2,$3,$4,$5)
ON CONFLICT (building, name) DO UPDATE SET width=CASE WHEN $3>0 THEN $3 ELSE rooms.width END,
depth=CASE WHEN $4>0 THEN $4 ELSE rooms.depth END, source=$5`, x.Building, x.Name, x.Width, x.Depth, orDefault(x.Source, "local"))
return err
}
// SetRackPosition places a rack on its room's floor (nil x/y: back to automatic).
func (s *Store) SetRackPosition(ctx context.Context, building, room, name string, x, y *int, facing string) error {
tag, err := s.pool.Exec(ctx, `UPDATE racks SET x=$4, y=$5, facing=nullif($6,'') WHERE building=$1 AND room=$2 AND name=$3`, building, room, name, x, y, facing)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return errNotFound
}
return nil
}
// ---------------------------------------------------------------- handlers
func (a *App) handleSites(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
xs, err := a.store.Sites(r.Context())
if err != nil {
fail(w, 500, err)
return
}
writeJSON(w, 200, xs)
case http.MethodPost:
var x Site
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16)).Decode(&x); err != nil || strings.TrimSpace(x.Name) == "" {
fail(w, 400, errors.New("name is required"))
return
}
x.Name, x.Source = strings.TrimSpace(x.Name), "local"
if (x.Lat == nil) != (x.Lon == nil) || x.Lat != nil && (*x.Lat < -90 || *x.Lat > 90 || *x.Lon < -180 || *x.Lon > 180) {
fail(w, 400, errors.New("lat and lon go together: -90..90, -180..180"))
return
}
if cur, _ := a.store.Sites(r.Context()); a.ipamIsNetBox() {
for _, c := range cur {
if c.Name == x.Name && c.Source == "netbox" {
x.Source = "netbox" // coordinates set here stand until NetBox has its own
}
}
}
if err := a.store.PutSite(r.Context(), x); err != nil {
fail(w, 500, err)
return
}
writeJSON(w, 200, x)
case http.MethodDelete:
if err := a.store.DeleteSite(r.Context(), r.URL.Query().Get("name")); err != nil {
fail(w, 500, err)
return
}
writeJSON(w, 200, obj{"deleted": r.URL.Query().Get("name")})
}
}
func (a *App) handleRooms(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
xs, err := a.store.Rooms(r.Context())
if err != nil {
fail(w, 500, err)
return
}
writeJSON(w, 200, xs)
case http.MethodPost:
var x Room
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16)).Decode(&x); err != nil || strings.TrimSpace(x.Building) == "" {
fail(w, 400, errors.New("building is required"))
return
}
if x.Width < 0 || x.Depth < 0 || x.Width > 500 || x.Depth > 500 {
fail(w, 400, errors.New("width and depth are floor tiles, 0..500"))
return
}
x.Source = "local"
if err := a.store.PutRoom(r.Context(), x); err != nil {
fail(w, 500, err)
return
}
writeJSON(w, 200, x)
}
}
// handleRackPositions places racks: [{"building","room","name","x","y","facing"}].
func (a *App) handleRackPositions(w http.ResponseWriter, r *http.Request) {
var req []struct {
Building, Room, Name string
X, Y *int
Facing string
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
fail(w, 400, err)
return
}
for _, p := range req {
if p.Facing != "" && !strings.Contains("NESW", p.Facing) || len(p.Facing) > 1 {
fail(w, 400, fmt.Errorf("%s: facing is N, E, S or W", p.Name))
return
}
if (p.X == nil) != (p.Y == nil) || p.X != nil && (*p.X < 0 || *p.Y < 0 || *p.X > 500 || *p.Y > 500) {
fail(w, 400, fmt.Errorf("%s: x and y go together, 0..500 tiles", p.Name))
return
}
if err := a.store.SetRackPosition(r.Context(), p.Building, p.Room, p.Name, p.X, p.Y, p.Facing); err != nil {
fail(w, 400, fmt.Errorf("%s: %w", p.Name, err))
return
}
}
writeJSON(w, 200, obj{"placed": len(req)})
}
func (a *App) ipamIsNetBox() bool { _, ok := a.ipam.(*netBox); return ok }
// ---------------------------------------------------------------- NetBox
// syncLayout copies NetBox's sites, locations and racks: what Rollcall shows
// on the map and the floor plans. Nothing is deleted here: a site, room or
// rack that left NetBox stays until removed by hand.
func (a *App) syncLayout(ctx context.Context) error {
nb, ok := a.ipam.(*netBox)
if !ok {
return nil
}
sites, rooms, racks, err := nb.layout(ctx)
if err != nil {
return err
}
for _, x := range sites {
if err := a.store.PutSite(ctx, x); err != nil {
return err
}
}
for _, x := range rooms {
if err := a.store.PutRoom(ctx, x); err != nil {
return err
}
}
have, _ := a.store.Racks(ctx)
for _, x := range racks {
for _, h := range have { // keep the comment written here
if h.Building == x.Building && h.Room == x.Room && h.Name == x.Name {
x.Comment = h.Comment
}
}
if err := a.store.PutRack(ctx, x); err != nil {
return err
}
}
return nil
}
// layout reads NetBox's sites (coordinates when set), locations as rooms and racks.
func (n *netBox) layout(ctx context.Context) ([]Site, []Room, []Rack, error) {
ss, err := n.all(ctx, "dcim/sites/", nil)
if err != nil {
return nil, nil, nil, err
}
var sites []Site
byID := map[int64]string{}
for _, s := range ss {
name := str(s["name"])
byID[nbID(s)] = name
x := Site{Name: name, Slug: str(s["slug"]), Address: oneLine(str(s["physical_address"])), Source: "netbox"}
if lat, ok := s["latitude"].(float64); ok {
if lon, ok := s["longitude"].(float64); ok {
x.Lat, x.Lon = &lat, &lon
}
}
sites = append(sites, x)
}
ls, err := n.all(ctx, "dcim/locations/", nil)
if err != nil {
return nil, nil, nil, fmt.Errorf("locations: %w", err)
}
var rooms []Room
locName := map[int64]string{}
for _, l := range ls {
locName[nbID(l)] = str(l["name"])
if site := byID[nbRef(l, "site")]; site != "" {
rooms = append(rooms, Room{Building: site, Name: str(l["name"]), Source: "netbox"})
}
}
rs, err := n.all(ctx, "dcim/racks/", nil)
if err != nil {
return nil, nil, nil, fmt.Errorf("racks: %w", err)
}
var racks []Rack
for _, rk := range rs {
if site := byID[nbRef(rk, "site")]; site != "" {
racks = append(racks, Rack{Building: site, Room: locName[nbRef(rk, "location")], Name: str(rk["name"]), Height: int(num(rk["u_height"]))})
}
}
return sites, rooms, racks, nil
}