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
package main import ( "fmt" "log" "sync" "github.com/hashicorp/serf/serf" ) // Agent starts and manages a Serf & adds // service discovery type Agent struct { // conf *Config serfConf *serf.Config eventCh chan serf.Event // i doubt we care about handling events, // but i'm leaving this here just in case // eventHandlerList []EventHandler // eventHandlersLock sync.Mutex // This is the underlying Serf we are wrapping serf *serf.Serf // this channel receiving a signal = shutdown shutdown bool shutdownCh chan struct{} shutdownLock sync.Mutex } func Create(serfConf *serf.Config) *Agent { // Create a channel to listen for events from Serf eventCh := make(chan serf.Event, 64) serfConf.EventCh = eventCh // Setup the agent agent := &Agent{ serfConf: serfConf, eventCh: eventCh, shutdownCh: make(chan struct{}), } return agent } func (a *Agent) eventLoop() { serfShutdownCh := a.serf.ShutdownCh() for { select { case e := <-a.eventCh: log.Printf("[INFO] cascade: Received event: %s", e.String()) case <-serfShutdownCh: log.Printf("[WARN] cascade: Serf shutdown detected, quitting") a.Shutdown() return case <-a.shutdownCh: return } } } func (a *Agent) Start() error { log.Printf("[INFO] cascade: Serf agent starting") // Create serf first serf, err := serf.Create(a.serfConf) if err != nil { return fmt.Errorf("Error creating Serf: %s", err) } a.serf = serf // Start event loop go a.eventLoop() return nil } // Shutdown closes this agent and all of its processes. Should be preceded // by a Leave for a graceful shutdown. func (a *Agent) Shutdown() error { a.shutdownLock.Lock() defer a.shutdownLock.Unlock() if a.shutdown { return nil } if a.serf == nil { goto EXIT } log.Println("[INFO] cascade: requesting serf shutdown") if err := a.serf.Shutdown(); err != nil { return err } EXIT: log.Println("[INFO] cascade: shutdown complete") a.shutdown = true close(a.shutdownCh) return nil } // Join asks the Serf instance to join. See the Serf.Join function. func (a *Agent) Join(addrs []string) (n int, err error) { log.Printf("[INFO] cascade: joining: %v", addrs) // we always ignore old events because cascade don't // care about the past n, err = a.serf.Join(addrs, true) if n > 0 { log.Printf("[INFO] cascade: joined: %d nodes", n) } if err != nil { log.Printf("[WARN] cascade: error joining: %v", err) } return n, err } // Leave prepares for a graceful shutdown of the agent and its processes func (a *Agent) Leave() error { if a.serf == nil { return nil } log.Println("[INFO] cascade: requesting graceful leave from Serf") return a.serf.Leave() }