-
Notifications
You must be signed in to change notification settings - Fork 2
/
nodedb.go
94 lines (81 loc) · 1.74 KB
/
nodedb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"bytes"
"log"
"net"
"sync"
"time"
)
type NodeDB struct {
mutex sync.Mutex
nodesURL, graphURL string
nodes map[string]*Node
}
func NewNodeDB(updateInterval time.Duration, nodesURL, graphURL string) *NodeDB {
ndb := &NodeDB{
nodesURL: nodesURL,
graphURL: graphURL,
}
go func() {
for {
ndb.update()
time.Sleep(updateInterval)
}
}()
return ndb
}
func (ndb *NodeDB) update() {
var nodes Nodes
err := GetJSON(ndb.nodesURL, &nodes)
if err != nil {
log.Println("Error fetching nodes:", err)
return
}
var graph Graph
err = GetJSON(ndb.graphURL, &graph)
if err != nil {
log.Println("Error fetching graph:", err)
return
}
for _, link := range graph.Batadv.Links {
if !(link.Source < len(graph.Batadv.Nodes) && link.Target < len(graph.Batadv.Nodes)) {
log.Println("Node index out of range")
return
}
nodeID := graph.Batadv.Nodes[link.Source].NodeID
if nodeID == "" {
continue
}
node, ok := nodes.Nodes[nodeID]
if ok {
node.Links = append(node.Links, link)
}
nodeID = graph.Batadv.Nodes[link.Target].NodeID
if nodeID == "" {
continue
}
node, ok = nodes.Nodes[nodeID]
if ok {
node.Links = append(node.Links, link)
}
}
ips := make(map[string]*Node)
for _, n := range nodes.Nodes {
for _, ip := range n.Nodeinfo.Network.Addresses {
nip := net.ParseIP(ip)
// Filter link-local and ULA addresses
if nip != nil && !bytes.Equal(nip[0:2], []byte{0xfe, 0x80}) && !bytes.Equal(nip[0:2], []byte{0xfd, 0xa0}) {
ips[nip.String()] = n
}
}
}
ndb.mutex.Lock()
defer ndb.mutex.Unlock()
ndb.nodes = ips
return
}
func (ndb *NodeDB) GetNode(ip net.IP) *Node {
ndb.mutex.Lock()
defer ndb.mutex.Unlock()
return ndb.nodes[ip.String()]
}