2016-05-14 10:31:43 +00:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
2016-05-29 19:41:58 +00:00
|
|
|
"sync"
|
2016-05-14 10:31:43 +00:00
|
|
|
"time"
|
2016-05-29 19:41:58 +00:00
|
|
|
|
|
|
|
"github.com/FreifunkBremen/respond-collector/data"
|
2016-05-14 10:31:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Alias struct {
|
2016-06-28 22:04:33 +00:00
|
|
|
Hostname string `json:"hostname,omitempty"`
|
|
|
|
Location *data.Location `json:"location,omitempty"`
|
|
|
|
Wireless *data.Wireless `json:"wireless,omitempty"`
|
2016-07-09 00:33:34 +00:00
|
|
|
Owner string `json:"owner,omitempty"`
|
2016-05-29 19:41:58 +00:00
|
|
|
}
|
|
|
|
|
2016-05-14 10:31:43 +00:00
|
|
|
// Nodes struct: cache DB of Node's structs
|
|
|
|
type Aliases struct {
|
2016-05-29 19:41:58 +00:00
|
|
|
List map[string]*Alias `json:"nodes"` // the current nodemap, indexed by node ID
|
|
|
|
config *Config
|
2016-05-14 10:31:43 +00:00
|
|
|
sync.Mutex
|
|
|
|
}
|
2016-05-29 19:41:58 +00:00
|
|
|
|
2016-05-14 10:31:43 +00:00
|
|
|
// NewNodes create Nodes structs
|
|
|
|
func NewAliases(config *Config) *Aliases {
|
|
|
|
aliases := &Aliases{
|
|
|
|
List: make(map[string]*Alias),
|
|
|
|
config: config,
|
|
|
|
}
|
|
|
|
|
|
|
|
if config.Nodes.AliasesPath != "" {
|
|
|
|
aliases.load()
|
|
|
|
}
|
|
|
|
go aliases.worker()
|
|
|
|
|
|
|
|
return aliases
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Aliases) Update(nodeID string, newalias *Alias) {
|
|
|
|
e.Lock()
|
|
|
|
e.List[nodeID] = newalias
|
|
|
|
e.Unlock()
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Aliases) load() {
|
2016-05-14 11:21:10 +00:00
|
|
|
path := e.config.Nodes.AliasesPath
|
|
|
|
log.Println("loading", path)
|
2016-05-14 10:31:43 +00:00
|
|
|
|
2016-05-14 11:21:10 +00:00
|
|
|
if data, err := ioutil.ReadFile(path); err == nil {
|
|
|
|
if err := json.Unmarshal(data, e); err == nil {
|
|
|
|
log.Println("loaded", len(e.List), "aliases")
|
|
|
|
} else {
|
|
|
|
log.Println("failed to unmarshal nodes:", err)
|
|
|
|
}
|
2016-05-14 10:31:43 +00:00
|
|
|
|
2016-05-14 11:21:10 +00:00
|
|
|
} else {
|
|
|
|
log.Println("failed loading cached nodes:", err)
|
|
|
|
}
|
2016-05-14 10:31:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Periodically saves the cached DB to json file
|
|
|
|
func (e *Aliases) worker() {
|
|
|
|
c := time.Tick(time.Second * 5)
|
|
|
|
|
|
|
|
for range c {
|
|
|
|
log.Println("saving", len(e.List), "aliases")
|
|
|
|
e.Lock()
|
|
|
|
save(e, e.config.Nodes.AliasesPath)
|
|
|
|
e.Unlock()
|
|
|
|
}
|
|
|
|
}
|