-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathagents.go
126 lines (105 loc) · 2.35 KB
/
agents.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package store
import (
"github.com/Cepave/ops-common/model"
"sync"
)
type AgentsMap struct {
sync.RWMutex
M map[string]*model.RealAgent
}
func NewAgentsMap() *AgentsMap {
return &AgentsMap{M: make(map[string]*model.RealAgent)}
}
func (this *AgentsMap) Get(agentName string) (*model.RealAgent, bool) {
this.RLock()
defer this.RUnlock()
val, exists := this.M[agentName]
return val, exists
}
func (this *AgentsMap) Len() int {
this.RLock()
defer this.RUnlock()
return len(this.M)
}
func (this *AgentsMap) IsStale(before int64) bool {
this.RLock()
defer this.RUnlock()
for _, ra := range this.M {
if ra.Timestamp > before {
return false
}
}
return true
}
func (this *AgentsMap) Put(agentName string, realAgent *model.RealAgent) {
this.Lock()
defer this.Unlock()
this.M[agentName] = realAgent
}
type HostAgentsMap struct {
sync.RWMutex
M map[string]*AgentsMap
}
func NewHostAgentsMap() *HostAgentsMap {
return &HostAgentsMap{M: make(map[string]*AgentsMap)}
}
var HostAgents = NewHostAgentsMap()
func (this *HostAgentsMap) Get(hostname string) (*AgentsMap, bool) {
this.RLock()
defer this.RUnlock()
val, exists := this.M[hostname]
return val, exists
}
func (this *HostAgentsMap) Put(hostname string, am *AgentsMap) {
this.Lock()
defer this.Unlock()
this.M[hostname] = am
}
func (this *HostAgentsMap) Hostnames() []string {
this.RLock()
defer this.RUnlock()
count := len(this.M)
hostnames := make([]string, count)
i := 0
for hostname := range this.M {
hostnames[i] = hostname
i++
}
return hostnames
}
func (this *HostAgentsMap) Delete(hostname string) {
this.Lock()
defer this.Unlock()
delete(this.M, hostname)
}
func (this *HostAgentsMap) Status(agentName string) (ret map[string]*model.RealAgent) {
ret = make(map[string]*model.RealAgent)
this.RLock()
defer this.RUnlock()
for hostname, agents := range this.M {
ra, exists := agents.Get(agentName)
if !exists {
ret[hostname] = nil
} else {
ret[hostname] = ra
}
}
return
}
func ParseHeartbeatRequest(req *model.HeartbeatRequest) {
if req.RealAgents == nil || len(req.RealAgents) == 0 {
return
}
agentsMap, exists := HostAgents.Get(req.Hostname)
if exists {
for _, a := range req.RealAgents {
agentsMap.Put(a.Name, a)
}
} else {
am := NewAgentsMap()
for _, a := range req.RealAgents {
am.Put(a.Name, a)
}
HostAgents.Put(req.Hostname, am)
}
}