agent/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
// design touchstones // simple to configure/implement // - minimal configurable options // - sparse use of commands/flags/env vars // - fast to start/join a cluster // - http-only api // api auth/encryption is best implemented by a reverse proxy (like caddy or nginx) // - no RPC (it's too annoying to deal with) // predictable state // - no runtime configuration allowed (no reload support) // for a gossip cluster to work, nodes in the cluster must // be the source of truth. we do not allow the user to change // the cluster's view of reality in any way - the user may // only inspect it. // - HTTP API only supports read-only commands // this ensures that cascade's starting state never // diverges from its running state. // (restarts are very fast + interruptionless) // this also helps with security // one massive global cluster // - for simplicity, operability, and because gossip can handle it // compatability // - attempt to have a consul-compatible API where it matters? // todo // dns resolver for services // read-write exception for maintenance mode? // opentelemetry metrics // key differences from consul // - services are gossip'd // in cascade, node == member, and catalog == agent // agent api (http-only) // GET /v1/agent/metrics -> opentelemetry metrics for this agent // GET /v1/agent/members -> show serf cluster membership state // GET /v1/agent/services -> show services this agent owns // aliases: GET /v1/catalog/nodes // catalog api (http & dns) // GET /v1/catalog/nodes // GET /v1/catalog/services // dns: dig @127.0.0.1 -p 8600 nostromo.node.cascade. ANY // dns: dig @127.0.0.1 -p 8600 redis.service.cascade. ANY // consul uses /catalog because the masters maintain a service // catalog separate than the agent state // in cascade, the agents _are_ expected to maintain service catalogues, // so we do away with the catalog concept entirely. package agent import ( "fmt" "os" "os/signal" "strings" "sync" "syscall" "time" "github.com/hashicorp/memberlist" "github.com/hashicorp/serf/serf" "golang.org/x/exp/slog" ) const ( // gracefulTimeout controls how long we wait before forcefully terminating // note that this value interacts with serfConfig.LeavePropagateDelay gracefulTimeout = 10 * time.Second ) func Run() { config := readConfig() logger := config.SetupLogger() agent := setupAgent(config, logger) if err := agent.Start(); err != nil { fmt.Println(err) os.Exit(1) } defer agent.Shutdown() // join any specified startup nodes if err := startupJoin(config, agent); err != nil { fmt.Println(err) os.Exit(1) } if err := handleSignals(config, agent); err != nil { fmt.Println(err) os.Exit(1) } } // handleSignals blocks until we get an exit-causing signal func handleSignals(config *Config, agent *Agent) error { signalCh := make(chan os.Signal, 4) signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM) // Wait for a signal var sig os.Signal select { case s := <-signalCh: sig = s case <-agent.ShutdownCh(): // Agent is already shutdown! return nil } agent.logger.Info("caught signal", "signal", sig) // Check if we should do a graceful leave graceful := false if sig == os.Interrupt || sig == syscall.SIGTERM { graceful = true } // Bail fast if not doing a graceful leave if !graceful { agent.logger.Warn("leave cluster with zero grace") return nil } // Attempt a graceful leave gracefulCh := make(chan struct{}) agent.logger.Info("shut down agent gracefully") go func() { if err := agent.Leave(); err != nil { agent.logger.Error("Error: %s", err) return } close(gracefulCh) }() // Wait for leave or another signal select { case <-signalCh: return fmt.Errorf("idfk") case <-time.After(gracefulTimeout): return fmt.Errorf("leave timed out") case <-gracefulCh: return nil } } func readConfig() *Config { config := DefaultConfig() // CASCADE_LOGLEVEL=info l := os.Getenv("CASCADE_LOGLEVEL") if l != "" { config.LogLevel = l if l == "DEBUG" { // config. } } // CASCADE_BIND=192.168.0.15:12345 if os.Getenv("CASCADE_BIND") != "" { config.BindAddr = os.Getenv("CASCADE_BIND") } // CASCADE_JOIN=127.0.0.1,127.0.0.5 if os.Getenv("CASCADE_JOIN") != "" { config.StartJoin = strings.Split(os.Getenv("CASCADE_JOIN"), ",") } // CASCADE_NAME=nostromo.j3s.sh if os.Getenv("CASCADE_NAME") != "" { config.NodeName = os.Getenv("CASCADE_NAME") } return config } func startupJoin(config *Config, agent *Agent) error { if len(config.StartJoin) == 0 { return nil } n, err := agent.Join(config.StartJoin) if err != nil { return err } if n > 0 { agent.logger.Info("issue join request", "nodes", n) } return nil } func setupAgent(config *Config, logger *slog.Logger) *Agent { bindIP, bindPort, err := config.AddrParts(config.BindAddr) if err != nil { panic(err) } serfConfig := serf.DefaultConfig() // logLogger is just a bridge from the old logger to the // new slog handler. logLogger := slog.NewLogLogger(logger.Handler(), config.GetLogLevel()) serfConfig.Logger = logLogger serfConfig.NodeName = config.NodeName serfConfig.ProtocolVersion = uint8(serf.ProtocolVersionMax) // TODO: how should cascade handle name conflicts? // defaulting to just blowing up for now, but // we _could_ take the tailscale route & append // -1 or whatever to the node. that would be more user friendly. // TODO: some of these serf settings were pulled // from consul[1]. re-examine them eventually. serfConfig.EnableNameConflictResolution = false serfConfig.LeavePropagateDelay = 3 * time.Second serfConfig.MinQueueDepth = 4096 serfConfig.QueueDepthWarning = 1000000 serfConfig.ReconnectTimeout = 3 * 24 * time.Hour serfConfig.MemberlistConfig = memberlist.DefaultWANConfig() serfConfig.MemberlistConfig.Logger = logLogger serfConfig.MemberlistConfig.DeadNodeReclaimTime = 30 * time.Second serfConfig.MemberlistConfig.BindAddr = bindIP serfConfig.MemberlistConfig.BindPort = bindPort agent := Create(config, serfConfig, logger) agent.logger.Info("setup cascade agent", "nodename", config.NodeName, "bindport", bindPort, "bindip", bindIP, "loglevel", config.GetLogLevel()) return agent } // [1]: sources for consul serf tweaks // https://github.com/hashicorp/consul/blob/v1.14.4/agent/consul/config.go // https://github.com/hashicorp/consul/blob/v1.14.4/lib/serf/serf.go // Agent starts and manages a Serf & adds service discovery (TODO) type Agent struct { serfConf *serf.Config eventCh chan serf.Event // This is the underlying Serf we are wrapping serf *serf.Serf // a lil logger used by the agent, you know how it be logger *slog.Logger // this channel receiving a signal = shutdown shutdown bool shutdownCh chan struct{} shutdownLock sync.Mutex } func Create(config *Config, serfConf *serf.Config, logger *slog.Logger) *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, logger: logger, shutdownCh: make(chan struct{}), } return agent } func (a *Agent) eventLoop() { serfShutdownCh := a.serf.ShutdownCh() for { select { case e := <-a.eventCh: a.logger.Info("receive event", "event", e.String()) case <-serfShutdownCh: a.logger.Info("detect serf shutdown, turning off event loop") a.Shutdown() return case <-a.shutdownCh: return } } } func (a *Agent) Start() error { // Create serf first serf, err := serf.Create(a.serfConf) if err != nil { return 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 } a.logger.Info("request serf shutdown") if err := a.serf.Shutdown(); err != nil { return err } EXIT: a.logger.Info("complete serf shutdown") 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) { a.logger.Info("issue join request", "addrs", addrs) // we always ignore old events because cascade don't // care about the past n, err = a.serf.Join(addrs, true) if err != nil { return n, fmt.Errorf("Error joining: %v\n", err) } // TODO: when joining fails, we don't get an error here - serf & memberlist // just print to stdout and serf.Join returns without issue. 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 } a.logger.Info("request graceful serf leave") return a.serf.Leave() } // ShutdownCh returns a channel that can be selected to wait // for the agent to perform a shutdown. func (a *Agent) ShutdownCh() <-chan struct{} { return a.shutdownCh } func (c *Config) SetupLogger() *slog.Logger { opts := slog.HandlerOptions{ Level: c.GetLogLevel(), } if c.LogLevel == "DEBUG" { opts.AddSource = true } handler := opts.NewTextHandler(os.Stderr) logger := slog.New(handler) slog.SetDefault(logger) return logger }