forked from coreos/fleet
/
agent.go
578 lines (481 loc) · 16.3 KB
/
agent.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
package agent
import (
"encoding/json"
"time"
log "github.com/coreos/fleet/Godeps/_workspace/src/github.com/golang/glog"
"github.com/coreos/fleet/job"
"github.com/coreos/fleet/machine"
"github.com/coreos/fleet/registry"
"github.com/coreos/fleet/sign"
"github.com/coreos/fleet/unit"
)
const (
// TTL to use with all state pushed to Registry
DefaultTTL = "30s"
)
// The Agent owns all of the coordination between the Registry, the local
// Machine, and the local UnitManager.
type Agent struct {
registry registry.Registry
um unit.UnitManager
Machine machine.Machine
ttl time.Duration
// verifier is used to verify the contents of a job's Unit.
// A nil verifier implies that all Units are accepted.
verifier *sign.SignatureVerifier
state *AgentState
}
func New(mgr unit.UnitManager, reg registry.Registry, mach machine.Machine, ttl string, verifier *sign.SignatureVerifier) (*Agent, error) {
ttldur, err := time.ParseDuration(ttl)
if err != nil {
return nil, err
}
a := &Agent{reg, mgr, mach, ttldur, verifier, NewState()}
return a, nil
}
func (a *Agent) MarshalJSON() ([]byte, error) {
data := struct {
UnitManager unit.UnitManager
State *AgentState
}{
UnitManager: a.um,
State: a.state,
}
return json.Marshal(data)
}
// Heartbeat updates the Registry periodically with this Agent's
// presence information as well as an acknowledgement of the jobs
// it is expected to be running.
func (a *Agent) Heartbeat(stop chan bool) {
go a.heartbeatJobs(a.ttl, stop)
}
// Initialize prepares the Agent for normal operation by doing three things:
// 1. Announce presence to the Registry
// 2. Discover any jobs that are scheduled locally, loading/starting them if they can run locally
// 3. Cache all unresolved job offers and bid for any that can be run locally
func (a *Agent) Initialize() {
log.Infof("Initializing Agent")
// Lock the state early so we can decide what the Agent needs to do
// without the risk of conflicting with any of its other moving parts
a.state.Lock()
defer a.state.Unlock()
machID := a.Machine.State().ID
loaded := map[string]job.Job{}
launched := map[string]job.Job{}
jobs, _ := a.registry.Jobs()
for _, j := range jobs {
if j.TargetMachineID == "" || j.TargetMachineID != machID {
continue
}
if !a.ableToRun(&j) {
log.Infof("Unable to run Job(%s), unscheduling", j.Name)
a.registry.ClearJobTarget(j.Name, machID)
continue
}
if j.TargetState == job.JobStateInactive {
continue
}
loaded[j.Name] = j
if j.TargetState != job.JobStateLaunched {
continue
}
launched[j.Name] = j
}
units, err := a.um.Units()
if err != nil {
log.Warningf("Failed determining what units are already loaded: %v", err)
}
for _, name := range units {
if _, ok := loaded[name]; !ok {
log.Infof("Unit(%s) should not be loaded here, unloading", name)
go func() {
a.um.Stop(name)
a.um.Unload(name)
}()
}
}
for _, j := range loaded {
a.state.TrackJob(&j)
a.loadJob(&j)
if _, ok := launched[j.Name]; !ok {
continue
}
a.startJobUnlocked(j.Name)
}
offers, _ := a.registry.UnresolvedJobOffers()
for _, jo := range offers {
// Everything we check against could change over time, so we track
// all offers starting here for future bidding even if we are
// currently unable to bid
a.state.TrackOffer(jo)
a.state.TrackJob(&jo.Job)
}
a.bidForPossibleJobs()
}
// Purge removes the Agent's state from the Registry
func (a *Agent) Purge() {
a.state.Lock()
scheduled := a.state.ScheduledJobs()
a.state.Unlock()
machID := a.Machine.State().ID
for _, jobName := range scheduled {
log.Infof("Unloading Job(%s) from local machine", jobName)
a.unloadJob(jobName)
log.Infof("Unscheduling Job(%s) from local machine", jobName)
a.registry.ClearJobTarget(jobName, machID)
}
log.Info("Removing Agent from Registry")
if err := a.registry.RemoveMachineState(machID); err != nil {
log.Errorf("Failed to remove Machine %s from Registry: %s", machID, err.Error())
}
}
func (a *Agent) heartbeatJobs(ttl time.Duration, stop chan bool) {
heartbeat := func() {
machID := a.Machine.State().ID
launched := a.state.LaunchedJobs()
for _, j := range launched {
go a.registry.JobHeartbeat(j, machID, ttl)
}
}
interval := ttl / 2
ticker := time.Tick(interval)
for {
select {
case <-stop:
log.V(1).Info("HeartbeatJobs exiting due to stop signal")
return
case <-ticker:
log.V(1).Info("HeartbeatJobs tick")
heartbeat()
}
}
}
// loadJob hands the given Job to systemd without acquiring the
// state mutex. The caller is responsible for acquiring it.
func (a *Agent) loadJob(j *job.Job) {
log.Infof("Loading Job(%s)", j.Name)
a.state.SetTargetState(j.Name, job.JobStateLoaded)
err := a.um.Load(j.Name, j.Unit)
if err != nil {
log.Errorf("Failed loading Job(%s): %v", j.Name, err)
return
}
// We must explicitly refresh the payload state, as the dbus
// event listener does not send an event when we write a unit
// file to disk.
us, err := a.um.GetUnitState(j.Name)
if err != nil {
log.Errorf("Failed fetching state of Unit(%s): %v", j.Name, err)
return
}
a.ReportUnitState(j.Name, us)
}
// StartJob starts the indicated Job after first acquiring the state mutex
func (a *Agent) StartJob(jobName string) {
a.state.Lock()
defer a.state.Unlock()
a.startJobUnlocked(jobName)
}
// startJobUnlocked starts the indicated Job without acquiring the state
// mutex. The caller is responsible for acquiring it.
func (a *Agent) startJobUnlocked(jobName string) {
a.state.SetTargetState(jobName, job.JobStateLaunched)
machID := a.Machine.State().ID
a.registry.JobHeartbeat(jobName, machID, a.ttl)
go func() {
a.um.Start(jobName)
// We explicitly refresh the payload state here as the dbus
// event listener does not send us an event if the job was
// already loaded.
us, err := a.um.GetUnitState(jobName)
if err != nil {
log.Errorf("Failed fetching state of Unit(%s): %v", jobName, err)
return
}
a.ReportUnitState(jobName, us)
}()
}
// StopJob stops the indicated Job after first acquiring the state mutex
func (a *Agent) StopJob(jobName string) {
a.state.Lock()
defer a.state.Unlock()
a.stopJobUnlocked(jobName)
}
// stopJobUnlocked stops the indicated Job without acquiring the state
// mutex. The caller is responsible for acquiring it.
func (a *Agent) stopJobUnlocked(jobName string) {
a.state.SetTargetState(jobName, job.JobStateLoaded)
a.registry.ClearJobHeartbeat(jobName)
go func() {
a.um.Stop(jobName)
// We must explicitly refresh the payload state, as the dbus
// event listener sends a nil event when a unit deactivates.
us, err := a.um.GetUnitState(jobName)
if err != nil {
log.Errorf("Failed fetching state of Unit(%s): %v", jobName, err)
return
}
a.ReportUnitState(jobName, us)
}()
}
// unloadJob stops and expunges the indicated Job without acquiring the
// state mutex. The caller is responsible for acquiring it.
func (a *Agent) unloadJob(jobName string) {
go func() {
a.um.Stop(jobName)
a.um.Unload(jobName)
}()
a.registry.ClearJobHeartbeat(jobName)
a.registry.RemoveUnitState(jobName)
// Grab the peers of the Job before we destroy the state
reversePeers := a.state.GetJobsByPeer(jobName)
a.state.PurgeJob(jobName)
// Trigger rescheduling of all the peers of the job that was just unloaded
machID := a.Machine.State().ID
for _, peer := range reversePeers {
log.Infof("Unloading Peer(%s) of Job(%s)", peer, jobName)
err := a.registry.ClearJobTarget(peer, machID)
if err != nil {
log.Errorf("Failed unloading Peer(%s) of Job(%s): %v", peer, jobName, err)
}
}
}
// ReportUnitState attaches the current state of the Agent's Machine to the given
// unit.UnitState object, then persists that state in the Registry
func (a *Agent) ReportUnitState(jobName string, us *unit.UnitState) {
if us == nil {
log.Infof("Job(%s): purging UnitState from Registry", jobName)
err := a.registry.RemoveUnitState(jobName)
if err != nil {
log.Errorf("Failed to remove UnitState for job %s from Registry: %s", jobName, err.Error())
}
} else {
us.MachineID = a.Machine.State().ID
log.Infof("Job(%s): pushing UnitState (loadState=%s, activeState=%s, subState=%s) to Registry", jobName, us.LoadState, us.ActiveState, us.SubState)
a.registry.SaveUnitState(jobName, us)
}
}
// MaybeBid bids for the given JobOffer only if the Agent determines that it is able
// to run the JobOffer's Job
func (a *Agent) MaybeBid(jo job.JobOffer) {
a.state.Lock()
defer a.state.Unlock()
// Everything we check against could change over time, so we track all
// offers starting here for future bidding even if we can't bid now
a.state.TrackOffer(jo)
a.state.TrackJob(&jo.Job)
if !a.ableToRun(&jo.Job) {
log.Infof("EventJobOffered(%s): not all criteria met, not bidding", jo.Job.Name)
return
}
log.Infof("EventJobOffered(%s): passed all criteria, submitting JobBid", jo.Job.Name)
a.bid(jo.Job.Name)
}
// bidForPossibleJobs submits bids for all unresolved offers whose Jobs
// can be run locally
func (a *Agent) bidForPossibleJobs() {
offers := a.state.GetOffersWithoutBids()
log.V(1).Infof("Checking %d unbade offers", len(offers))
for i := range offers {
offer := offers[i]
log.V(1).Infof("Checking ability to run Job(%s)", offer.Job.Name)
if a.ableToRun(&offer.Job) {
log.V(1).Infof("Able to run Job(%s), submitting bid", offer.Job.Name)
a.bid(offer.Job.Name)
} else {
log.V(1).Infof("Still unable to run Job(%s)", offer.Job.Name)
}
}
}
// Submit a bid for the given Job
func (a *Agent) bid(jobName string) {
log.Infof("Submitting JobBid for Job(%s)", jobName)
jb := job.NewBid(jobName, a.Machine.State().ID)
a.registry.SubmitJobBid(jb)
a.state.TrackBid(jb.JobName)
}
// verifyJobSignature attempts to verify the integrity of the given Job by checking the
// signature against a SignatureSet stored in its repository.
func (a *Agent) verifyJobSignature(j *job.Job) bool {
if a.verifier == nil {
return true
}
ss, _ := a.registry.JobSignatureSet(j.Name)
ok, err := a.verifier.VerifyJob(j, ss)
if err != nil {
log.V(1).Infof("Error verifying signature of Job(%s): %v", j.Name, err)
return false
} else if !ok {
log.V(1).Infof("Job(%s) does not match signature", j.Name)
return false
}
return true
}
// bidForPossiblePeers submits bids for all known peers of the provided job that can
// be run locally
func (a *Agent) bidForPossiblePeers(jobName string) {
peers := a.state.GetJobsByPeer(jobName)
for _, peer := range peers {
log.V(1).Infof("Found unresolved offer for Peer(%s) of Job(%s)", peer, jobName)
peerJob, err := a.registry.Job(peer)
if err != nil {
log.Errorf("Failed fetching Job(%s) from Registry: %v", peer, err)
return
}
if peerJob == nil {
log.V(1).Infof("Unable to find Peer(%s) of Job(%s) in Registry", peer, jobName)
return
}
if !a.ableToRun(peerJob) {
log.V(1).Infof("Unable to run Peer(%s) of Job(%s), not bidding", peer, jobName)
return
}
a.bid(peer)
}
}
// ableToRun determines if the Agent can run the provided Job, and returns a boolean indicating
// whether this is the case. There are five criteria for an Agent to be eligible to run a Job:
// - Job must pass signature verification
// - agent must have all of the Job's required metadata (if any)
// - agent must meet the Job's machine target requirement (if any)
// - agent must have all required Peers of the Job scheduled locally (if any)
// - Job must not conflict with any other Jobs scheduled to the agent
func (a *Agent) ableToRun(j *job.Job) bool {
if !a.verifyJobSignature(j) {
log.V(1).Infof("Failed to verify Job(%s)", j.Name)
return false
}
log.Infof("Job(%s) has requirements: %s", j.Name, j.Requirements())
metadata := j.RequiredTargetMetadata()
if len(metadata) == 0 {
log.V(1).Infof("Job(%s) has no required machine metadata", j.Name)
} else {
log.V(1).Infof("Job(%s) requires machine metadata: %v", j.Name, metadata)
ms := a.Machine.State()
if !machine.HasMetadata(&ms, metadata) {
log.Infof("Unable to run Job(%s): local Machine metadata insufficient", j.Name)
return false
}
}
if tgt, ok := j.RequiredTarget(); ok && !a.Machine.State().MatchID(tgt) {
log.Infof("Unable to run Job(%s): agent does not meet machine target requirement (%s)", j.Name, tgt)
return false
}
peers := j.Peers()
if len(peers) == 0 {
log.V(1).Infof("Job(%s) has no required peers", j.Name)
} else {
log.V(1).Infof("Job(%s) requires peers: %v", j.Name, peers)
for _, peer := range peers {
if !a.peerScheduledHere(j.Name, peer) {
log.Infof("Unable to run Job(%s): required Peer(%s) is not scheduled locally", j.Name, peer)
return false
}
}
}
if conflicted, conflictedJobName := a.HasConflict(j.Name, j.Conflicts()); conflicted {
log.Infof("Unable to run Job(%s): conflict with Job(%s)", j.Name, conflictedJobName)
return false
}
return true
}
// Determine if all necessary peers of a Job are scheduled to this Agent
func (a *Agent) peerScheduledHere(jobName, peerName string) bool {
log.V(1).Infof("Looking for target of Peer(%s)", peerName)
j, err := a.registry.Job(peerName)
if err != nil {
log.Errorf("Failed retrieving Job(%s) from Registry: %v", peerName, err)
return false
} else if j == nil {
return false
}
if j.TargetMachineID == "" || j.TargetMachineID != a.Machine.State().ID {
log.V(1).Infof("Peer(%s) of Job(%s) not scheduled here", peerName, jobName)
return false
}
log.V(1).Infof("Peer(%s) of Job(%s) scheduled here", peerName, jobName)
return true
}
// HasConflict determines whether there are any known conflicts with the given argument
func (a *Agent) HasConflict(potentialJobName string, potentialConflicts []string) (bool, string) {
// Iterate through each Job that is scheduled here, asserting two things
for existingJobName, existingConflicts := range a.state.Conflicts {
if !a.state.ScheduledHere(existingJobName) {
continue
}
// 1. Each tracked Job does not conflict with the potential conflicts
for _, pc := range potentialConflicts {
if globMatches(pc, existingJobName) {
return true, existingJobName
}
}
// 2. The new Job does not conflict with any of the tracked conflicts
for _, ec := range existingConflicts {
if globMatches(ec, potentialJobName) {
return true, existingJobName
}
}
}
return false, ""
}
// JobScheduledElsewhere clears all state related to the indicated
// job before bidding for all oustanding jobs that can be run locally.
func (a *Agent) JobScheduledElsewhere(jobName string) {
a.state.Lock()
defer a.state.Unlock()
log.Infof("Dropping offer and bid for Job(%s) from cache", jobName)
a.state.PurgeOffer(jobName)
log.Infof("Purging Job(%s) data from cache", jobName)
a.state.PurgeJob(jobName)
log.Infof("Checking outstanding job offers")
a.bidForPossibleJobs()
}
// JobScheduledLocally clears all state related to the indicated
// job's offers/bids before attempting to load and possibly start
// the job. The ability to run the job will be revalidated before
// loading, and unscheduled if such validation fails.
func (a *Agent) JobScheduledLocally(jobName string) {
a.state.Lock()
defer a.state.Unlock()
log.Infof("Dropping offer and bid for Job(%s) from cache", jobName)
a.state.PurgeOffer(jobName)
j, err := a.registry.Job(jobName)
if err != nil {
log.Errorf("Failed fetching Job(%s) from Registry: %v", jobName, err)
return
}
if j == nil {
log.Errorf("Unable to find Job(%s) in Registry", jobName)
return
}
if !a.ableToRun(j) {
log.Infof("Unable to run locally-scheduled Job(%s), unscheduling", jobName)
a.registry.ClearJobTarget(jobName, a.Machine.State().ID)
a.state.PurgeJob(jobName)
return
}
a.loadJob(j)
log.Infof("Bidding for all possible peers of Job(%s)", j.Name)
a.bidForPossiblePeers(j.Name)
if j.TargetState != job.JobStateLaunched {
return
}
log.Infof("Job(%s) loaded, now starting it", j.Name)
a.startJobUnlocked(j.Name)
}
// JobUnscheduled attempts to unload the indicated job only
// if it were scheduled here in the first place, otherwise
// the event is ignored. If unloading is necessary, all jobs
// that can be run locally will also be bid upon.
func (a *Agent) JobUnscheduled(jobName string) {
a.state.Lock()
defer a.state.Unlock()
if !a.state.ScheduledHere(jobName) {
log.V(1).Infof("Job(%s) not scheduled here, ignoring", jobName)
return
}
log.Infof("Unloading Job(%s)", jobName)
a.unloadJob(jobName)
log.Infof("Checking outstanding JobOffers")
a.bidForPossibleJobs()
}