yanic/respond/collector.go

234 lines
5.2 KiB
Go
Raw Normal View History

2016-02-26 08:28:31 +00:00
package respond
2015-12-29 03:08:03 +00:00
import (
2016-03-19 00:50:23 +00:00
"bytes"
"compress/flate"
2016-03-11 23:59:36 +00:00
"encoding/json"
2015-12-29 03:08:03 +00:00
"log"
"net"
"time"
2016-03-19 22:18:26 +00:00
"github.com/FreifunkBremen/respond-collector/data"
2016-10-03 17:55:37 +00:00
"github.com/FreifunkBremen/respond-collector/database"
"github.com/FreifunkBremen/respond-collector/jsontime"
2016-10-03 17:55:37 +00:00
"github.com/FreifunkBremen/respond-collector/models"
2015-12-29 03:08:03 +00:00
)
// Collector for a specificle respond messages
2015-12-29 03:08:03 +00:00
type Collector struct {
connection *net.UDPConn // UDP socket
queue chan *Response // received responses
iface string
db *database.DB
nodes *models.Nodes
interval time.Duration // Interval for multicast packets
stop chan interface{}
2015-12-29 03:08:03 +00:00
}
// NewCollector creates a Collector struct
func NewCollector(db *database.DB, nodes *models.Nodes, iface string) *Collector {
2015-12-29 03:08:03 +00:00
// Parse address
addr, err := net.ResolveUDPAddr("udp", "[::]:0")
2015-12-29 03:08:03 +00:00
if err != nil {
log.Panic(err)
}
// Open socket
conn, err := net.ListenUDP("udp", addr)
if err != nil {
log.Panic(err)
}
conn.SetReadBuffer(maxDataGramSize)
2015-12-29 03:08:03 +00:00
collector := &Collector{
connection: conn,
db: db,
nodes: nodes,
iface: iface,
queue: make(chan *Response, 400),
stop: make(chan interface{}),
2015-12-29 03:08:03 +00:00
}
go collector.receiver()
go collector.parser()
2016-03-12 00:04:22 +00:00
if collector.db != nil {
go collector.globalStatsWorker()
}
return collector
}
// Start Collector
func (coll *Collector) Start(interval time.Duration) {
2017-01-29 21:26:16 +00:00
if coll.interval != 0 {
panic("already started")
}
2017-01-29 21:26:16 +00:00
if interval <= 0 {
panic("invalid collector interval")
}
coll.interval = interval
2016-03-12 17:26:51 +00:00
go func() {
coll.sendOnce() // immediately
coll.sender() // periodically
2016-03-12 17:26:51 +00:00
}()
2015-12-29 03:08:03 +00:00
}
2016-03-11 22:56:23 +00:00
// Close Collector
2015-12-29 03:08:03 +00:00
func (coll *Collector) Close() {
2017-01-29 21:26:16 +00:00
close(coll.stop)
2015-12-29 03:08:03 +00:00
coll.connection.Close()
close(coll.queue)
}
2015-12-29 13:05:47 +00:00
func (coll *Collector) sendOnce() {
now := jsontime.Now()
coll.sendMulticast()
// Wait for the multicast responses to be processed and send unicasts
time.Sleep(coll.interval / 2)
coll.sendUnicasts(now)
2015-12-29 13:05:47 +00:00
}
func (coll *Collector) sendMulticast() {
log.Println("sending multicast")
coll.SendPacket(net.ParseIP(multiCastGroup))
}
// Send unicast packets to nodes that did not answer the multicast
func (coll *Collector) sendUnicasts(seenBefore jsontime.Time) {
seenAfter := seenBefore.Add(-time.Minute * 10)
// Select online nodes that has not been seen recently
nodes := coll.nodes.Select(func(n *models.Node) bool {
return n.Lastseen.After(seenAfter) && n.Lastseen.Before(seenBefore) && n.Address != nil
})
// Send unicast packets
log.Printf("sending unicast to %d nodes", len(nodes))
for _, node := range nodes {
coll.SendPacket(node.Address)
time.Sleep(10 * time.Millisecond)
}
}
// SendPacket sends a UDP request to the given unicast or multicast address
func (coll *Collector) SendPacket(address net.IP) {
addr := net.UDPAddr{
IP: address,
Port: port,
Zone: coll.iface,
2016-02-19 10:13:30 +00:00
}
2015-12-29 13:05:47 +00:00
if _, err := coll.connection.WriteToUDP([]byte("GET nodeinfo statistics neighbours"), &addr); err != nil {
2016-03-07 00:37:07 +00:00
log.Println("WriteToUDP failed:", err)
}
2015-12-29 03:08:03 +00:00
}
2016-03-11 22:56:23 +00:00
// send packets continously
func (coll *Collector) sender() {
2017-01-29 21:26:16 +00:00
ticker := time.NewTicker(coll.interval)
2016-03-11 22:56:23 +00:00
for {
select {
case <-coll.stop:
2017-01-29 21:26:16 +00:00
ticker.Stop()
2016-03-11 22:56:23 +00:00
return
2017-01-29 21:26:16 +00:00
case <-ticker.C:
2016-10-03 23:05:18 +00:00
// send the multicast packet to request per-node statistics
2016-03-11 22:56:23 +00:00
coll.sendOnce()
}
2015-12-29 03:08:03 +00:00
}
}
func (coll *Collector) parser() {
2016-01-04 01:07:09 +00:00
for obj := range coll.queue {
2016-10-03 17:55:37 +00:00
if data, err := obj.parse(); err != nil {
log.Println("unable to decode response from", obj.Address.String(), err, "\n", string(obj.Raw))
2016-10-03 17:55:37 +00:00
} else {
coll.saveResponse(obj.Address, data)
2016-03-11 23:59:36 +00:00
}
2015-12-29 03:08:03 +00:00
}
}
2016-10-03 17:55:37 +00:00
func (res *Response) parse() (*data.ResponseData, error) {
2016-03-19 22:27:07 +00:00
// Deflate
2016-10-03 17:55:37 +00:00
deflater := flate.NewReader(bytes.NewReader(res.Raw))
2016-03-19 22:27:07 +00:00
defer deflater.Close()
2016-03-19 14:07:44 +00:00
2016-03-19 22:27:07 +00:00
// Unmarshal
2016-10-03 17:55:37 +00:00
rdata := &data.ResponseData{}
err := json.NewDecoder(deflater).Decode(rdata)
return rdata, err
}
func (coll *Collector) saveResponse(addr net.UDPAddr, res *data.ResponseData) {
// Search for NodeID
var nodeID string
2016-10-03 17:55:37 +00:00
if val := res.NodeInfo; val != nil {
nodeID = val.NodeID
2016-10-03 17:55:37 +00:00
} else if val := res.Neighbours; val != nil {
nodeID = val.NodeID
2016-10-03 17:55:37 +00:00
} else if val := res.Statistics; val != nil {
nodeID = val.NodeID
2016-10-03 17:55:37 +00:00
}
2017-01-29 21:26:16 +00:00
// Check length of nodeID
if len(nodeID) != 12 {
log.Printf("invalid NodeID '%s' from %s", nodeID, addr.String())
2016-10-03 17:55:37 +00:00
return
2016-03-19 14:07:44 +00:00
}
2017-01-29 21:26:16 +00:00
// Process the data and update IP address
node := coll.nodes.Update(nodeID, res)
node.Address = addr.IP
2016-03-19 14:07:44 +00:00
2017-01-29 21:26:16 +00:00
// Store statistics in InfluxDB
2016-10-03 17:55:37 +00:00
if coll.db != nil && node.Statistics != nil {
coll.db.Add(nodeID, node)
2016-10-03 17:55:37 +00:00
}
2016-03-19 00:50:23 +00:00
}
2015-12-29 03:08:03 +00:00
func (coll *Collector) receiver() {
buf := make([]byte, maxDataGramSize)
2015-12-29 03:08:03 +00:00
for {
2016-01-04 01:07:09 +00:00
n, src, err := coll.connection.ReadFromUDP(buf)
2015-12-29 03:08:03 +00:00
if err != nil {
log.Println("ReadFromUDP failed:", err)
2015-12-29 13:05:47 +00:00
return
2015-12-29 03:08:03 +00:00
}
2016-01-04 01:07:09 +00:00
raw := make([]byte, n)
copy(raw, buf)
coll.queue <- &Response{
Address: *src,
Raw: raw,
}
2015-12-29 03:08:03 +00:00
}
}
func (coll *Collector) globalStatsWorker() {
ticker := time.NewTicker(time.Minute)
for {
select {
case <-coll.stop:
2017-01-29 21:26:16 +00:00
ticker.Stop()
return
case <-ticker.C:
coll.saveGlobalStats()
}
}
}
// saves global statistics
func (coll *Collector) saveGlobalStats() {
stats := models.NewGlobalStats(coll.nodes)
coll.db.AddPoint(database.MeasurementGlobal, nil, stats.Fields(), time.Now())
coll.db.AddCounterMap(database.MeasurementFirmware, stats.Firmwares)
coll.db.AddCounterMap(database.MeasurementModel, stats.Models)
}