package netbox import ( "context" "encoding/json" "fmt" "strings" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" ) // maxLocationDepth stops walking up a broken (cyclic) location tree. const maxLocationDepth = 16 type locationNode struct { ref config.Ref parent int } type netboxLocation struct { ID int `json:"id"` Name string `json:"name"` Slug string `json:"slug"` Parent *struct { ID int `json:"id"` } `json:"parent"` } // rackUnit formats a NetBox rack position (a decimal such as 20.0 or 20.5). func rackUnit(n json.Number) string { if n == "" { return "" } s := n.String() if strings.Contains(s, ".") { s = strings.TrimRight(strings.TrimRight(s, "0"), ".") } return s } // locationChain returns the locations from the outermost to id. NetBox nests // locations through "parent"; each location is fetched once per client. func (c *Client) locationChain(ctx context.Context, id int) ([]config.Ref, error) { var chain []config.Ref for depth := 0; id > 0 && depth < maxLocationDepth; depth++ { node, err := c.location(ctx, id) if err != nil { return nil, err } chain = append([]config.Ref{node.ref}, chain...) id = node.parent } return chain, nil } func (c *Client) location(ctx context.Context, id int) (locationNode, error) { c.locMu.Lock() node, ok := c.locations[id] c.locMu.Unlock() if ok { return node, nil } var raw netboxLocation if err := c.get(ctx, fmt.Sprintf("%s/api/dcim/locations/%d/", c.baseURL, id), &raw); err != nil { return locationNode{}, err } node = locationNode{ref: config.Ref{Name: raw.Name, Slug: raw.Slug}} if raw.Parent != nil { node.parent = raw.Parent.ID } c.locMu.Lock() if c.locations == nil { c.locations = map[int]locationNode{} } c.locations[id] = node c.locMu.Unlock() return node, nil } // fillLocations replaces each device's own location with the full chain of // parent locations. A failed lookup keeps the device's own location: the // location is informational and must not break a search or a connection. func (c *Client) fillLocations(ctx context.Context, entries []HostEntry) { for i := range entries { if entries[i].locationID <= 0 { continue } if chain, err := c.locationChain(ctx, entries[i].locationID); err == nil && len(chain) > 0 { entries[i].Location = chain } } }