-
Notifications
You must be signed in to change notification settings - Fork 29
/
agents.go
282 lines (232 loc) · 7.81 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package agents
import (
"context"
"encoding/json"
"fmt"
"sort"
"sync"
"time"
"github.com/choria-io/go-choria/build"
"github.com/choria-io/go-choria/inter"
"github.com/choria-io/go-choria/lifecycle"
"github.com/choria-io/go-choria/protocol"
"github.com/choria-io/go-choria/providers/data/ddl"
"github.com/choria-io/go-choria/statistics"
"github.com/sirupsen/logrus"
"github.com/choria-io/go-choria/aagent"
)
// Agent is a generic choria agent
type Agent interface {
Metadata() *Metadata
Name() string
HandleMessage(context.Context, inter.Message, protocol.Request, inter.ConnectorInfo, chan *AgentReply)
SetServerInfo(ServerInfoSource)
ServerInfo() ServerInfoSource
ShouldActivate() bool
}
// ServerInfoSource provides data about a running server instance
type ServerInfoSource interface {
AgentMetadata(string) (Metadata, bool)
BuildInfo() *build.Info
Classes() []string
ConfigFile() string
ConnectedServer() string
DataFuncMap() (ddl.FuncMap, error)
Facts() json.RawMessage
Identity() string
KnownAgents() []string
LastProcessedMessage() time.Time
MachineTransition(name string, version string, path string, id string, transition string) error
MachinesStatus() ([]aagent.MachineState, error)
NewEvent(t lifecycle.Type, opts ...lifecycle.Option) error
PrepareForShutdown() error
Provisioning() bool
StartTime() time.Time
Stats() statistics.ServerStats
UpTime() int64
}
// AgentReply is a generic reply from an agent
type AgentReply struct {
Body []byte
Request protocol.Request
Message inter.Message
Error error
}
// Metadata describes an agent at a high level and is required for any agent
type Metadata struct {
License string `json:"license"`
Author string `json:"author"`
Timeout int `json:"timeout"`
Name string `json:"name"`
Version string `json:"version"`
URL string `json:"url"`
Description string `json:"description"`
Provider string `json:"provider,omitempty"`
Service bool `json:"service,omitempty"`
}
// Manager manages agents, handles registration, dispatches requests etc
type Manager struct {
agents map[string]Agent
subs map[string][]string
fw inter.Framework
log *logrus.Entry
mu *sync.Mutex
conn inter.ConnectorInfo
serverInfo ServerInfoSource
denylist []string
requests chan inter.ConnectorMessage
servicesOnly bool
}
// NewServices creates an agent manager restricted to service agents
func NewServices(requests chan inter.ConnectorMessage, fw inter.Framework, conn inter.ConnectorInfo, srv ServerInfoSource, log *logrus.Entry) *Manager {
m := New(requests, fw, conn, srv, log)
m.servicesOnly = true
m.log = m.log.WithField("service_host", true)
return m
}
// New creates a new Agent Manager
func New(requests chan inter.ConnectorMessage, fw inter.Framework, conn inter.ConnectorInfo, srv ServerInfoSource, log *logrus.Entry) *Manager {
return &Manager{
agents: make(map[string]Agent),
subs: make(map[string][]string),
fw: fw,
log: log.WithFields(logrus.Fields{"subsystem": "agents"}),
mu: &sync.Mutex{},
requests: requests,
conn: conn,
serverInfo: srv,
}
}
// DenyAgent adds an agent to the list of agent names not allowed to start
func (a *Manager) DenyAgent(agent string) {
a.denylist = append(a.denylist, agent)
}
// RegisterAgent connects a new agent to the server instance, subscribe to all its targets etc
func (a *Manager) RegisterAgent(ctx context.Context, name string, agent Agent, conn inter.AgentConnector) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.servicesOnly && !agent.Metadata().Service {
a.log.Infof("Denying non Service Agent %s", name)
return nil
}
if !agent.ShouldActivate() {
a.log.Infof("Agent %s not activating due to ShouldActivate checks", name)
return nil
}
if a.agentDenied(name) {
a.log.Infof("Denying agent %s based on agent deny list", name)
return nil
}
a.log.Infof("Registering new agent %s of type %s", name, agent.Metadata().Name)
agent.SetServerInfo(a.serverInfo)
if _, found := a.agents[name]; found {
return fmt.Errorf("agent %s is already registered", name)
}
err := a.subscribeAgent(ctx, name, agent, conn)
if err != nil {
return fmt.Errorf("could not register agent %s: %s", name, err)
}
a.agents[name] = agent
return nil
}
// KnownAgents retrieves a list of known agents
func (a *Manager) KnownAgents() []string {
a.mu.Lock()
defer a.mu.Unlock()
known := make([]string, 0, len(a.agents))
for agent := range a.agents {
known = append(known, agent)
}
sort.Strings(known)
return known
}
func (a *Manager) agentDenied(name string) bool {
for _, n := range a.denylist {
if n == name {
return true
}
}
return false
}
// Subscribes an agent to all its targets on the connector. Should any subscription fail
// all the preceding subscriptions for this agents is unsubscribed and an error returned.
// Errors during the unsub is just ignored because it's quite possible that they would fail
// too but this avoids problems of messages arriving we did not expect.
//
// In practice though this is something done during bootstrap and failure here should exit
// the whole instance, so it's probably not needed
func (a *Manager) subscribeAgent(ctx context.Context, name string, agent Agent, conn inter.AgentConnector) error {
if _, found := a.subs[name]; found {
return fmt.Errorf("could not subscribe agent %s, it's already subscribed", name)
}
a.subs[name] = []string{}
for _, collective := range a.fw.Configuration().Collectives {
var target string
group := ""
if agent.Metadata().Service {
target = conn.ServiceBroadcastTarget(collective, name)
group = name
a.log.Infof("Subscribing service agent %s to %s in group %s", name, target, group)
} else {
target = conn.AgentBroadcastTarget(collective, name)
a.log.Infof("Subscribing agent %s to %s", name, target)
}
subname := fmt.Sprintf("%s.%s", collective, name)
err := conn.QueueSubscribe(ctx, subname, target, group, a.requests)
if err != nil {
a.log.Errorf("could not subscribe agent %s to %s, rewinding all subscriptions for this agent", name, target)
for _, sub := range a.subs[name] {
conn.Unsubscribe(sub)
}
return fmt.Errorf("subscription failed: %s", err)
}
a.subs[name] = append(a.subs[name], subname)
}
return nil
}
// Get retrieves an agent by name
func (a *Manager) Get(name string) (Agent, bool) {
a.mu.Lock()
defer a.mu.Unlock()
agent, found := a.agents[name]
return agent, found
}
// Dispatch sends a request to a agent and wait for a reply
func (a *Manager) Dispatch(ctx context.Context, wg *sync.WaitGroup, replies chan *AgentReply, msg inter.Message, request protocol.Request) {
defer wg.Done()
agent, found := a.Get(msg.Agent())
if !found {
a.log.Errorf("Received a message for agent %s that does not exist, discarding", msg.Agent())
return
}
result := make(chan *AgentReply)
td := time.Duration(agent.Metadata().Timeout) * time.Second
a.log.Debugf("Handling message %s with timeout %#v", msg.RequestID(), td)
timeout, cancel := context.WithTimeout(context.Background(), td)
defer cancel()
go agent.HandleMessage(timeout, msg, request, a.conn, result)
select {
case reply := <-result:
replies <- reply
case <-ctx.Done():
replies <- &AgentReply{
Message: msg,
Request: request,
Error: fmt.Errorf("agent dispatcher for request %s exiting on interrupt", msg.RequestID()),
}
case <-timeout.Done():
replies <- &AgentReply{
Message: msg,
Request: request,
Error: fmt.Errorf("agent dispatcher for request %s exiting on %ds timeout", msg.RequestID(), agent.Metadata().Timeout),
}
}
}
// Logger is the logger the manager prefers new agents derive from
func (a *Manager) Logger() *logrus.Entry {
return a.log
}
// Choria provides an instance of the choria framework
func (a *Manager) Choria() inter.Framework {
return a.fw
}