diff --git a/CHANGELOG.md b/CHANGELOG.md index 53ce6cc..a5f9451 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ publish a tag that has no section here. ## [Unreleased] ### Added +- Sites page: sites on an OpenStreetMap map (Leaflet shipped in the binary), a site's rooms, and a + room's floor plan with racks on 600 mm tiles coloured by their machines; a rack opens its front. + Racks are placed by dragging and rotated in an edit mode; unplaced ones are laid out + automatically. With NetBox, sites (with coordinates), locations and racks are read from it; + otherwise, or without coordinates there, sites are placed on the map. `/api/v1/sites`, + `/api/v1/rooms`, `POST /api/v1/racks/positions`. The web UI's CSP allows OSM tile images. - Server heights without typing them in: SMBIOS chassis height from commissioning, else a model table checked against vendor documentation (Dell, HPE, Lenovo, xFusion, Fujitsu, Inspur/KAYTUS, GIGABYTE; not Supermicro, whose model numbers do not carry it), else `rack_units` per model in diff --git a/README.md b/README.md index a55fcb6..1539bab 100644 --- a/README.md +++ b/README.md @@ -308,6 +308,22 @@ units: the elevation draws them as one block, and NetBox gets a device type of height 0 placed in the rack without a position. The elevation spans each server over its height, marks unknown heights `?U` and warns about overlaps. +**Sites, rooms and floor plans.** The **Sites** page puts sites on an +OpenStreetMap map (Leaflet, shipped in the binary; the browser loads tiles +from `tile.openstreetmap.org`), coloured by the worst machine state; a site +opens its rooms, a room its floor plan: racks on 600 mm floor tiles, one wide +and two deep, a thick edge for the front, coloured by their machines with a +bar for the units used; a rack opens its front (the elevation above), and +`#/sites/SITE/ROOM/RACK` links to it. **Edit layout** drags racks to their +place and rotates them; racks nobody placed are laid out in rows facing +alternate aisles (drawn dashed). 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; without NetBox, or +for a site NetBox has no coordinates for, sites are placed by clicking the +map. Rack positions are Rollcall's either way (NetBox has no floor +coordinates). API: `/api/v1/sites`, `/api/v1/rooms`, `POST +/api/v1/racks/positions`. + ## Network and rack controllers ### Model diff --git a/cmd/rollcall/ipam.go b/cmd/rollcall/ipam.go index b4028e8..3521802 100644 --- a/cmd/rollcall/ipam.go +++ b/cmd/rollcall/ipam.go @@ -327,6 +327,11 @@ func (a *App) reconcileIPAM(ctx context.Context, dry bool) ipamReport { return rep } a.reconcileAddrs(ctx, local, &rep) + if !dry { // the map and floor plans follow NetBox's sites, locations and racks + if err := a.syncLayout(ctx); err != nil { + rep.fail("layout: " + err.Error()) + } + } if nb, ok := a.ipam.(*netBox); ok && a.cfg.IPAM.DeviceSync != nil && !dry { // after the addresses: the sync assigns them to the interfaces if ms, err := a.store.List(ctx); err != nil { diff --git a/cmd/rollcall/layout.go b/cmd/rollcall/layout.go new file mode 100644 index 0000000..b802e93 --- /dev/null +++ b/cmd/rollcall/layout.go @@ -0,0 +1,289 @@ +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 +} diff --git a/cmd/rollcall/layout_test.go b/cmd/rollcall/layout_test.go new file mode 100644 index 0000000..e78b4b8 --- /dev/null +++ b/cmd/rollcall/layout_test.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + "testing" +) + +func TestNetBoxLayout(t *testing.T) { + nb, f := testDCIM(t) // sites Ev and DC1, location Hall A (DC1), rack R12 in both + dc := f.find("dcim/sites/", "slug", "dc1") + dc["latitude"], dc["longitude"], dc["physical_address"] = 41.0082, 28.9784, "Hall Street 1\nIstanbul" + for _, r := range f.objs["dcim/racks/"] { + r["u_height"] = float64(48) + if r["site"] == dc["id"] { + r["location"] = f.find("dcim/locations/", "name", "Hall A")["id"] + } + } + sites, rooms, racks, err := nb.layout(t.Context()) + if err != nil { + t.Fatal(err) + } + got := map[string]Site{} + for _, s := range sites { + got[s.Name] = s + } + if d := got["DC1"]; d.Lat == nil || *d.Lat != 41.0082 || *d.Lon != 28.9784 || d.Address != "Hall Street 1 · Istanbul" || d.Slug != "dc1" || d.Source != "netbox" { + t.Fatalf("DC1: %+v", d) + } + if e := got["Ev"]; e.Lat != nil { + t.Fatalf("a site without coordinates got some: %+v", e) + } + if fmt.Sprint(rooms) != "[{DC1 Hall A 0 0 netbox}]" { + t.Fatalf("rooms %v", rooms) + } + want := map[string]string{"DC1": "Hall A", "Ev": ""} + for _, r := range racks { + if r.Name != "R12" || r.Height != 48 || want[r.Building] != r.Room { + t.Fatalf("rack %+v", r) + } + } + if len(racks) != 2 { + t.Fatalf("racks %v", racks) + } +} diff --git a/cmd/rollcall/location.go b/cmd/rollcall/location.go index c7daab6..9a7c584 100644 --- a/cmd/rollcall/location.go +++ b/cmd/rollcall/location.go @@ -50,6 +50,10 @@ type Rack struct { Height int `json:"height"` Comment string `json:"comment"` Machines int `json:"machines,omitempty"` + // on the room's floor (layout.go): tiles from the room's corner, front facing N/E/S/W + X *int `json:"x"` + Y *int `json:"y"` + Facing string `json:"facing,omitempty"` } // ---------------------------------------------------------------- store @@ -67,7 +71,7 @@ func (s *Store) SetLocation(ctx context.Context, id string, l Location) error { } func (s *Store) Racks(ctx context.Context) ([]Rack, error) { - rows, err := s.pool.Query(ctx, `SELECT building, room, name, height, coalesce(comment,'') FROM racks ORDER BY building, room, name`) + rows, err := s.pool.Query(ctx, `SELECT building, room, name, height, coalesce(comment,''), x, y, coalesce(facing,'') FROM racks ORDER BY building, room, name`) if err != nil { return nil, err } @@ -75,7 +79,7 @@ func (s *Store) Racks(ctx context.Context) ([]Rack, error) { out := []Rack{} for rows.Next() { var r Rack - if err := rows.Scan(&r.Building, &r.Room, &r.Name, &r.Height, &r.Comment); err != nil { + if err := rows.Scan(&r.Building, &r.Room, &r.Name, &r.Height, &r.Comment, &r.X, &r.Y, &r.Facing); err != nil { return nil, err } out = append(out, r) diff --git a/cmd/rollcall/server.go b/cmd/rollcall/server.go index 63e9d83..836cae5 100644 --- a/cmd/rollcall/server.go +++ b/cmd/rollcall/server.go @@ -285,6 +285,12 @@ func (a *App) routes() http.Handler { mux.HandleFunc("GET /api/v1/racks", a.adminAuth(a.handleRacks)) mux.HandleFunc("POST /api/v1/racks", a.adminAuth(a.handleRacks)) mux.HandleFunc("DELETE /api/v1/racks", a.adminAuth(a.handleRacks)) + mux.HandleFunc("POST /api/v1/racks/positions", a.adminAuth(a.handleRackPositions)) + mux.HandleFunc("GET /api/v1/sites", a.adminAuth(a.handleSites)) + mux.HandleFunc("POST /api/v1/sites", a.adminAuth(a.handleSites)) + mux.HandleFunc("DELETE /api/v1/sites", a.adminAuth(a.handleSites)) + mux.HandleFunc("GET /api/v1/rooms", a.adminAuth(a.handleRooms)) + mux.HandleFunc("POST /api/v1/rooms", a.adminAuth(a.handleRooms)) // tags mux.HandleFunc("GET /api/v1/tags", a.adminAuth(a.handleTags)) mux.HandleFunc("POST /api/v1/tags", a.adminAuth(a.handleTags)) @@ -311,7 +317,7 @@ func (a *App) routes() http.Handler { func uiHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() - h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'") + h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://tile.openstreetmap.org; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'") h.Set("X-Content-Type-Options", "nosniff") h.Set("X-Frame-Options", "DENY") h.Set("Referrer-Policy", "no-referrer") diff --git a/cmd/rollcall/store.go b/cmd/rollcall/store.go index 381d015..44e54e9 100644 --- a/cmd/rollcall/store.go +++ b/cmd/rollcall/store.go @@ -101,6 +101,25 @@ CREATE TABLE IF NOT EXISTS racks ( comment text, PRIMARY KEY (building, room, name) ); +ALTER TABLE racks ADD COLUMN IF NOT EXISTS x int; +ALTER TABLE racks ADD COLUMN IF NOT EXISTS y int; +ALTER TABLE racks ADD COLUMN IF NOT EXISTS facing text; +CREATE TABLE IF NOT EXISTS sites ( + name text PRIMARY KEY, + slug text, + lat double precision, + lon double precision, + address text, + source text NOT NULL DEFAULT 'local' +); +CREATE TABLE IF NOT EXISTS rooms ( + building text NOT NULL, + name text NOT NULL, + width int NOT NULL DEFAULT 0, + depth int NOT NULL DEFAULT 0, + source text NOT NULL DEFAULT 'local', + PRIMARY KEY (building, name) +); ALTER TABLE machines ADD COLUMN IF NOT EXISTS rack_controller text; ALTER TABLE machines ADD COLUMN IF NOT EXISTS net_layout text; ALTER TABLE tags ADD COLUMN IF NOT EXISTS net_layout text; diff --git a/cmd/rollcall/web/app.js b/cmd/rollcall/web/app.js index f9e622e..b135313 100644 --- a/cmd/rollcall/web/app.js +++ b/cmd/rollcall/web/app.js @@ -14,7 +14,7 @@ let token = ''; try { token = localStorage.getItem('rollcall.token') || ''; } catch (e) { /* storage unavailable */ } // ?token=… on the URL signs in once and is removed from the address bar (for bookmarks/kiosks) { const u = new URL(location.href); const t = u.searchParams.get('token'); if (t) { token = t; try { localStorage.setItem('rollcall.token', t); } catch (e) { /* ignore */ } u.searchParams.delete('token'); history.replaceState(null, '', u.pathname + u.search + u.hash); } } -const S = { machines: [], tags: [], profiles: [], os: [], jobs: [], events: [], racks: [], subnets: [], controllers: [], layouts: [], fabrics: [], ips: [], ipam: null, sel: new Set(), q: '', states: new Set(), tagf: new Set(), loc: { building: '', room: '', rack: '' }, page: 0, per: 50, sort: 'name', dir: 1, loaded: false }; +const S = { sites: [], rooms: [], machines: [], tags: [], profiles: [], os: [], jobs: [], events: [], racks: [], subnets: [], controllers: [], layouts: [], fabrics: [], ips: [], ipam: null, sel: new Set(), q: '', states: new Set(), tagf: new Set(), loc: { building: '', room: '', rack: '' }, page: 0, per: 50, sort: 'name', dir: 1, loaded: false }; const locStr = l => { if (!l) return ''; const p = [l.building, l.room, l.rack].filter(Boolean).join(' / '); return p + (l.unit ? ` U${l.unit}` : ''); }; let timer = null; @@ -77,6 +77,7 @@ async function refresh(full) { const page = route().page; if (full || page === 'overview' || page === 'jobs') S.jobs = await api('GET', '/api/v1/jobs'); if (full || page === 'overview') S.events = await api('GET', '/api/v1/events'); + if (full || page === 'sites') [S.sites, S.rooms] = await Promise.all([api('GET', '/api/v1/sites'), api('GET', '/api/v1/rooms')]); if (full || page === 'overview' || page === 'network') { [S.ips, S.ipam] = await Promise.all([api('GET', '/api/v1/ips'), api('GET', '/api/v1/ipam').catch(() => null)]); } @@ -102,7 +103,7 @@ function schedule() { function route() { const h = location.hash.replace(/^#\/?/, '').split('/'); if (h[0] === 'machine' && h[1]) return { page: 'machine', id: h[1], tab: h[2] || 'overview' }; - return { page: h[0] || 'overview', arg: h[1] }; + return { page: h[0] || 'overview', arg: h[1], arg2: h[2], arg3: h[3] }; } window.addEventListener('hashchange', () => { S.sel.clear(); render(); }); function nav(page) { location.hash = '#/' + page; } @@ -117,11 +118,13 @@ function render() { const r = route(); $$('.side a[data-nav]').forEach(a => a.classList.toggle('active', a.dataset.nav === r.page || (r.page === 'machine' && a.dataset.nav === 'machines'))); const main = $('#main'); + if (r.page !== 'sites') { main.dataset.view = ''; if (SITE.map) { SITE.map.remove(); SITE.map = null; } SITE.edit = null; } switch (r.page) { case 'machines': main.innerHTML = pageMachines(); wireMachines(); break; case 'machine': if (!detailCache[r.id]) { main.innerHTML = '
loading…
'; loadDetail(r.id); } else { main.innerHTML = pageMachine(detailCache[r.id], r.tab); wireMachine(detailCache[r.id]); } break; case 'jobs': main.innerHTML = pageJobs(); wireJobs(); break; case 'racks': main.innerHTML = pageRacks(); wireRacks(); break; + case 'sites': renderSites(); break; case 'network': main.innerHTML = pageNetwork(); wireNetwork(); break; case 'tags': main.innerHTML = pageTags(); wireTags(); break; case 'profiles': main.innerHTML = pageProfiles(); wireProfiles(); break; @@ -597,6 +600,41 @@ function pageJobs() { function wireJobs() { $('#refresh').onclick = () => refresh(true); } // ---------------------------------------------------------------- racks +// rackElev: a rack's front, servers spanning their height (shared by the +// Racks page and the floor plans in sites.js) +function rackElev(rk) { + const keyOf = (b, rm, n) => `${b}|${rm}|${n}`; + const placed = S.machines.filter(m => m.location && m.location.rack); + const ms = placed.filter(m => (m.location.building || '') === rk.building && (m.location.room || '') === rk.room && m.location.rack === rk.name); + // blocks of units: a server spans its height (size from the firmware or the + // model, ?U when unknown); sleds of one multi-node chassis share one block + const H = rk.height || 42, noU = [], blocks = []; + for (const m of ms) { + if (!(m.location.unit > 0)) { noU.push(m); continue; } + const sz = m.size || {}, h = Math.max(1, sz.u || 1), unit = m.location.unit; + const b = sz.node && blocks.find(x => x.node && x.unit === unit); + if (b) b.ms.push(m); else blocks.push({ unit, h, node: !!sz.node, known: !!sz.u, ms: [m] }); + } + const clash = []; + blocks.forEach((a, i) => blocks.slice(i + 1).forEach(b => { if (a.unit <= b.unit + b.h - 1 && b.unit <= a.unit + a.h - 1) clash.push(`${a.ms.map(nameOf).join('+')} and ${b.ms.map(nameOf).join('+')} overlap at U${Math.max(a.unit, b.unit)}`); })); + const top = {}, covered = new Set(); + for (const b of blocks) { const t = Math.min(H, b.unit + b.h - 1); if (top[t] || [...Array(t - b.unit + 1).keys()].some(k => covered.has(b.unit + k))) continue; top[t] = b; for (let u = b.unit; u <= t; u++) covered.add(u); } + let rows = ''; + for (let u = H; u >= 1; u--) { + rows += `