yanic/collector.go

115 lines
2.1 KiB
Go
Raw Normal View History

2015-12-29 04:08:03 +01:00
package main
import (
"encoding/json"
"log"
"net"
2015-12-29 14:05:47 +01:00
"reflect"
"strings"
2015-12-29 04:08:03 +01:00
"time"
)
const (
maxDatagramSize = 8192
)
type Collector struct {
2015-12-29 14:05:47 +01:00
collectType string
connection *net.UDPConn // UDP socket
queue chan string // received responses
2015-12-29 04:08:03 +01:00
}
2015-12-29 14:05:47 +01:00
func NewCollector(collectType string) *Collector {
2015-12-29 04:08:03 +01:00
// Parse address
2015-12-29 14:05:47 +01:00
addr, err := net.ResolveUDPAddr("udp", "[::]:0")
2015-12-29 04:08:03 +01:00
if err != nil {
log.Panic(err)
}
// Open socket
conn, err := net.ListenUDP("udp", addr)
if err != nil {
log.Panic(err)
}
conn.SetReadBuffer(maxDatagramSize)
collector := &Collector{
2015-12-29 14:05:47 +01:00
collectType: collectType,
connection: conn,
queue: make(chan string, 100),
2015-12-29 04:08:03 +01:00
}
2015-12-29 14:05:47 +01:00
go collector.sendOnce()
go collector.sender()
2015-12-29 04:08:03 +01:00
go collector.receiver()
go collector.parser()
return collector
}
func (coll *Collector) Close() {
coll.connection.Close()
close(coll.queue)
}
2015-12-29 14:05:47 +01:00
func (coll *Collector) sendOnce() {
coll.sendPacket("[2a06:8782:ffbb:1337:c24a:ff:fe2c:c7ac]:1001")
coll.sendPacket("[2001:bf7:540:0:32b5:c2ff:fe6e:99d5]:1001")
}
func (coll *Collector) sendPacket(address string) {
2015-12-29 04:08:03 +01:00
addr, err := net.ResolveUDPAddr("udp", address)
2015-12-29 14:05:47 +01:00
check(err)
coll.connection.WriteToUDP([]byte(coll.collectType), addr)
2015-12-29 04:08:03 +01:00
}
2015-12-29 14:05:47 +01:00
func (coll *Collector) sender() {
c := time.Tick(collectInterval)
for range c {
coll.sendOnce()
2015-12-29 04:08:03 +01:00
}
}
func (coll *Collector) parser() {
for str := range coll.queue {
coll.parseSingle(str)
}
}
// Parst die Rückgabe
func (coll *Collector) parseSingle(str string) {
var result map[string]interface{}
json.Unmarshal([]byte(str), &result)
nodeId, _ := result["node_id"].(string)
if nodeId == "" {
log.Println("unable to parse node_id")
return
}
2015-12-29 14:05:47 +01:00
node := nodes.get(nodeId)
2015-12-29 04:08:03 +01:00
2015-12-29 14:05:47 +01:00
// Set result
elem := reflect.ValueOf(node).Elem()
field := elem.FieldByName(strings.Title(coll.collectType))
field.Set(reflect.ValueOf(result))
2015-12-29 04:08:03 +01:00
}
func (coll *Collector) receiver() {
b := make([]byte, maxDatagramSize)
for {
2015-12-29 14:05:47 +01:00
n, src, err := coll.connection.ReadFromUDP(b)
2015-12-29 04:08:03 +01:00
if err != nil {
log.Println("ReadFromUDP failed:", err)
2015-12-29 14:05:47 +01:00
return
2015-12-29 04:08:03 +01:00
}
2015-12-29 14:05:47 +01:00
coll.queue <- string(b[:n])
log.Println("received", coll.collectType, "from", src)
2015-12-29 04:08:03 +01:00
}
}