2016-05-14 12:31:43 +02:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
2016-05-29 21:41:58 +02:00
|
|
|
"sync"
|
2016-05-14 12:31:43 +02:00
|
|
|
"time"
|
2016-05-29 21:41:58 +02:00
|
|
|
|
|
|
|
"github.com/FreifunkBremen/respond-collector/data"
|
2016-05-14 12:31:43 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type Alias struct {
|
2016-06-29 00:04:33 +02:00
|
|
|
Hostname string `json:"hostname,omitempty"`
|
|
|
|
Location *data.Location `json:"location,omitempty"`
|
|
|
|
Wireless *data.Wireless `json:"wireless,omitempty"`
|
2016-05-29 21:41:58 +02:00
|
|
|
}
|
|
|
|
|
2016-05-14 12:31:43 +02:00
|
|
|
// Nodes struct: cache DB of Node's structs
|
|
|
|
type Aliases struct {
|
2016-05-29 21:41:58 +02:00
|
|
|
List map[string]*Alias `json:"nodes"` // the current nodemap, indexed by node ID
|
|
|
|
config *Config
|
2016-05-14 12:31:43 +02:00
|
|
|
sync.Mutex
|
|
|
|
}
|
2016-05-29 21:41:58 +02:00
|
|
|
|
2016-05-14 12:31:43 +02: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 13:21:10 +02:00
|
|
|
path := e.config.Nodes.AliasesPath
|
|
|
|
log.Println("loading", path)
|
2016-05-14 12:31:43 +02:00
|
|
|
|
2016-05-14 13:21:10 +02: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 12:31:43 +02:00
|
|
|
|
2016-05-14 13:21:10 +02:00
|
|
|
} else {
|
|
|
|
log.Println("failed loading cached nodes:", err)
|
|
|
|
}
|
2016-05-14 12:31:43 +02: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()
|
|
|
|
}
|
|
|
|
}
|