Sort the structs returned by /api/topology

This commit is contained in:
Tom Wilkie
2015-10-17 16:02:06 +00:00
parent f26f998b09
commit 258e2c153d
2 changed files with 42 additions and 20 deletions

View File

@@ -38,21 +38,21 @@ func makeTopologyList(rep xfer.Reporter) func(w http.ResponseWriter, r *http.Req
rpt = rep.Report()
topologies = []APITopologyDesc{}
)
topologyRegistry.walk(func(name string, def topologyView, subDefs map[string]topologyView) {
topologyRegistry.walk(func(def topologyViewAndID, subDefs topologyViewAndIDs) {
describedSubDefs := []APITopologyDesc{}
for subName, subDef := range subDefs {
for _, subDef := range subDefs {
describedSubDefs = append(describedSubDefs, APITopologyDesc{
Name: subDef.human,
URL: "/api/topology/" + subName,
Options: makeTopologyOptions(subDef),
URL: "/api/topology/" + subDef.id,
Options: makeTopologyOptions(subDef.topologyView),
Stats: stats(subDef.renderer, rpt),
})
}
topologies = append(topologies, APITopologyDesc{
Name: def.human,
URL: "/api/topology/" + name,
URL: "/api/topology/" + def.id,
SubTopologies: describedSubDefs,
Options: makeTopologyOptions(def),
Options: makeTopologyOptions(def.topologyView),
Stats: stats(def.renderer, rpt),
})
})

View File

@@ -5,6 +5,7 @@ import (
"encoding/gob"
"net/http"
"net/url"
"sort"
"strings"
"sync"
@@ -143,6 +144,32 @@ type registry struct {
items map[string]topologyView
}
type topologyViewAndID struct {
topologyView
id string
}
type topologyViewAndIDs []topologyViewAndID
func (a topologyViewAndIDs) Len() int { return len(a) }
func (a topologyViewAndIDs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a topologyViewAndIDs) Less(i, j int) bool { return a[i].id < a[j].id }
func (r *registry) collectTopologyViews(f func(topologyView) bool) topologyViewAndIDs {
result := topologyViewAndIDs{}
for name, def := range r.items {
if !f(def) {
continue
}
result = append(result, topologyViewAndID{
topologyView: def,
id: name,
})
}
sort.Sort(result)
return result
}
func (r *registry) add(ts map[string]topologyView) {
r.Lock()
defer r.Unlock()
@@ -163,23 +190,18 @@ func (r *registry) get(name string) (topologyView, bool) {
return t, ok
}
func (r *registry) walk(f func(string, topologyView, map[string]topologyView)) {
func (r *registry) walk(f func(topologyViewAndID, topologyViewAndIDs)) {
r.RLock()
defer r.RUnlock()
for name, def := range r.items {
if def.parent != "" {
continue
}
parents := r.collectTopologyViews(func(def topologyView) bool {
return def.parent == ""
})
subDefs := map[string]topologyView{}
for subName, subDef := range r.items {
if subDef.parent != name {
continue
}
subDefs[subName] = subDef
}
f(name, def, subDefs)
for _, parent := range parents {
subDefs := r.collectTopologyViews(func(def topologyView) bool {
return def.parent == parent.id
})
f(parent, subDefs)
}
}