yanic/models/aliases.go

78 lines
1.6 KiB
Go
Raw Normal View History

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
)
// Alias a change request for other nodes
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
}
// Aliases struct: cache DB of Node's structs
2016-05-14 10:31:43 +00:00
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
// NewAliases create Nodes structs
2016-05-14 10:31:43 +00:00
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
}
// Update a alias in aliases cache
2016-05-14 10:31:43 +00:00
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 {
2016-05-14 11:21:10 +00:00
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()
}
}