forked from evilsocket/opensnitch
/
nodes.go
98 lines (82 loc) · 2.15 KB
/
nodes.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
95
96
97
98
package nodes
import (
"github.com/gustavo-iniguez-goya/opensnitch/daemon/log"
"github.com/gustavo-iniguez-goya/opensnitch/daemon/ui/protocol"
"golang.org/x/net/context"
"google.golang.org/grpc/peer"
)
type nodeStats struct {
events []*protocol.Event
n *node
}
var (
nodeList = make(map[string]*node)
statsList = make(map[string]*nodeStats)
)
// Add a new node the list of nodes.
func Add(ctx context.Context, nodeConf *protocol.ClientConfig) {
p := GetPeer(ctx)
addr := p.Addr.String()
nodeList[addr] = NewNode(ctx, nodeConf)
}
// SetNotificationsChannel sets the communication channel for a given node.
// https://github.com/grpc/grpc-go/blob/master/stream.go
func SetNotificationsChannel(notificationsStream protocol.UI_NotificationsServer) *node {
ctx := notificationsStream.Context()
addr := GetAddr(ctx)
// ctx.AddCallback() ?
if !isConnected(addr) {
log.Warning("nodes.SetNotificationsChannel() not found: %s", addr)
return nil
}
nodeList[addr].NotificationsStream = notificationsStream
return nodeList[addr]
}
// UpdateStats of a node.
func UpdateStats(ctx context.Context, stats *protocol.Statistics) {
addr := GetAddr(ctx)
if !isConnected(addr) {
log.Warning("nodes.UpdateStats() not found: %s", addr)
return
}
nodeList[addr].UpdateStats(stats)
}
// Delete a node from the list of nodes.
func Delete(n *node) bool {
n.Close()
delete(nodeList, n.Addr())
return true
}
// Get a node from the list of nodes.
func Get(addr string) *node {
return nodeList[addr]
}
// GetPeer gets the address:port of a node.
func GetPeer(ctx context.Context) *peer.Peer {
p, _ := peer.FromContext(ctx)
return p
}
// GetAddr of a node from the context
func GetAddr(ctx context.Context) string {
p := GetPeer(ctx)
return p.Addr.String()
}
// GetAll nodes.
func GetAll() *map[string]*node {
return &nodeList
}
// GetStats returns the stats of all nodes combined.
func GetStats() (stats []*protocol.Statistics) {
for addr, node := range *GetAll() {
println(addr, node)
}
return stats
}
// Total returns the number of saved nodes.
func Total() int {
return len(nodeList)
}
func isConnected(addr string) bool {
_, found := nodeList[addr]
return found
}