forked from neuvector/neuvector
/
cluster.go
369 lines (314 loc) · 10.1 KB
/
cluster.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
"github.com/neuvector/neuvector/controller/cache"
"github.com/neuvector/neuvector/controller/kv"
"github.com/neuvector/neuvector/controller/rest"
"github.com/neuvector/neuvector/controller/scan"
"github.com/neuvector/neuvector/share"
"github.com/neuvector/neuvector/share/cluster"
"github.com/neuvector/neuvector/share/global"
"github.com/neuvector/neuvector/share/system"
)
var ClusterConnected bool = false
var selfRejoin bool = false
var clusterFailed bool = false
var leadFailTime time.Time
const recoveryThreshold = time.Duration(time.Second * 6)
const clusterCheckInterval time.Duration = time.Second * 2
const clusterCheckRetryMax = 150
func recordLeadChangeEvent(ev share.TLogEvent, newLead, oldLead string) {
var msg string
switch ev {
case share.CLUSEvControllerLeadLost:
msg = fmt.Sprintf("Controller lead lost. Old Lead: %s", oldLead)
case share.CLUSEvControllerLeadElect:
if oldLead == "" {
// initial lead
msg = fmt.Sprintf("New controller lead elected. New Lead: %s", newLead)
} else {
// lost lead then re-elected
msg = fmt.Sprintf("New controller lead elected. New Lead: %s; Old Lead: %s", newLead, oldLead)
}
default:
return
}
clog := share.CLUSEventLog{
Event: ev,
ControllerID: Ctrler.ID,
ControllerName: Ctrler.Name,
ReportedAt: time.Now().UTC(),
Msg: msg,
}
evqueue.Append(&clog)
}
func setConfigLoaded() {
log.Info("Set config loaded flag.")
clusHelper := kv.GetClusterHelper()
for {
if err := clusHelper.SetCtrlState(share.CLUSCtrlConfigLoadedKey); err == nil {
break
} else {
time.Sleep(time.Second)
}
}
}
func waitConfigLoaded(isNewCluster bool) {
log.Info("Wait config loaded flag ...")
clusHelper := kv.GetClusterHelper()
for {
if ok := clusHelper.GetCtrlState(share.CLUSCtrlConfigLoadedKey); ok {
log.Info("Got config loaded flag.")
break
} else if !isNewCluster {
// In case that we upgrade from the version has no config-loaded flag, ignore the check.
log.Info("Skip checking config loaded flag.")
break
} else {
time.Sleep(time.Second)
}
}
}
func leadChangeHandler(newLead, oldLead string) {
log.WithFields(log.Fields{"newLead": newLead, "oldLead": oldLead}).Info()
if atomic.LoadInt32(&exitingFlag) != 0 {
return
}
if newLead == "" {
leadFailTime = time.Now()
clusterFailed = true
Ctrler.Leader = false
cluster.PauseAllWatchers(true)
cache.LeadChangeNotify(false, "")
cache.ScannerChangeNotify(false)
scan.LeadChangeNotify(false)
scan.ScannerChangeNotify(false)
orchConnector.LeadChangeNotify(false)
rest.LeadChangeNotify(false)
// It is possible that the lead is gone, so everyone has to report lead lost event.
recordLeadChangeEvent(share.CLUSEvControllerLeadLost, "", oldLead)
} else {
Ctrler.Leader = (newLead == Ctrler.ClusterIP)
// update self ctrl key
value, _ := json.Marshal(Ctrler)
key := share.CLUSControllerKey(Host.ID, Ctrler.ID)
if err := cluster.Put(key, value); err != nil {
log.WithFields(log.Fields{"error": err}).Error("")
}
if Ctrler.Leader {
// This is used when upgrade from version that has no config-loaded flag
setConfigLoaded()
rest.HandleAdminUserUpdate()
// Only the lead backup config to the disk. When self becomes lead, run a full backup.
kv.GetConfigHelper().BackupAll()
}
cache.LeadChangeNotify(Ctrler.Leader, newLead)
cache.ScannerChangeNotify(Ctrler.Leader)
scan.LeadChangeNotify(Ctrler.Leader)
scan.ScannerChangeNotify(Ctrler.Leader)
orchConnector.LeadChangeNotify(Ctrler.Leader)
rest.LeadChangeNotify(Ctrler.Leader)
if clusterFailed {
// We will need to sync data from the oldest controller, not simply from the lead.
if time.Since(leadFailTime) > recoveryThreshold {
// Fail recovery is costy to do. Assume short lost of connection is due
// to network instability and skip recovery for now. Will need
// a lightweight method to check if recovery is needed later
cache.CtrlFailRecovery()
}
leadFailTime = time.Time{}
cluster.ResumeAllWatchers()
}
clusterFailed = false
if Ctrler.Leader {
recordLeadChangeEvent(share.CLUSEvControllerLeadElect, newLead, oldLead)
//for rolling upgrade case, especially with mixed version controller,
//old still use 16bit loose factor for mask while new use 8bit loose
//factor, here we push internal subnet to enforcer after lead change
cache.PutInternalIPNetToCluseterUpgrade()
}
}
}
func ctlrMemberUpdateHandler(nType cluster.ClusterNotifyType, memberAddr string, member string) {
log.WithFields(log.Fields{
"type": cluster.ClusterNotifyName[nType], "member": memberAddr,
}).Info("")
if nType == cluster.ClusterNotifyAdd {
if !ClusterConnected {
ClusterConnected = true
}
if selfRejoin && Ctrler.ClusterIP == memberAddr {
log.Info("Rejoin")
time.Sleep(time.Second)
selfRejoin = false
ctlrPutLocalInfo()
logController(share.CLUSEvControllerJoin)
}
} else if nType == cluster.ClusterNotifyDelete {
if Ctrler.ClusterIP == memberAddr {
log.Info("Left")
ClusterConnected = false
selfRejoin = true
} else {
cache.ClusterMemberStateUpdateHandler(nType, member, "")
}
}
}
func clusterStart(clusterCfg *cluster.ClusterConfig) (string, string, error) {
if err := cluster.FillClusterAddrs(clusterCfg, global.SYS); err != nil {
return "", "", err
}
lead, err := cluster.StartCluster(clusterCfg)
if err != nil {
log.WithFields(log.Fields{
"error": err, "waited": clusterCheckInterval * clusterCheckRetryMax,
}).Error("Cluster failed")
os.Exit(-1)
}
ClusterConnected = true
return cluster.GetSelfAddress(), lead, nil
}
func logController(ev share.TLogEvent) {
clog := share.CLUSEventLog{
Event: ev,
HostID: Host.ID,
HostName: Host.Name,
ControllerID: Ctrler.ID,
ControllerName: Ctrler.Name,
}
switch ev {
case share.CLUSEvControllerStart:
clog.ReportedAt = ctrlEnv.startsAt
default:
clog.ReportedAt = time.Now().UTC()
}
evqueue.Append(&clog)
}
var curMemoryPressure uint64
func memoryPressureNotification(rpt *system.MemoryPressureReport) {
log.WithFields(log.Fields{"rpt": rpt}).Info()
if rpt.Level > 2 { // cap its maximum
rpt.Level = 2
}
if rpt.Level == curMemoryPressure {
return // skip report
}
// launch falling-edge watcher, there is not actual level=0 event
if curMemoryPressure == 0 {
go func() {
var err error
var mStats *system.CgroupMemoryStats
acc := 0
for(acc < 7) {
time.Sleep(time.Minute*1)
if mStats, err = global.SYS.GetContainerMemoryStats(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("mem stat")
continue
}
limit := mStats.Usage.Limit
if mStats.Usage.Limit == 0 { // it's hitting node's limit
limit = uint64(Host.Memory)
}
ratio := uint64(rpt.Stats.WorkingSet * 100 / limit)
// log.WithFields(log.Fields{"ratio": ratio, "acc": acc, "limit": limit}).Debug()
if ratio <= 50 { // what is the reasonable threshold?
acc++
} else {
acc = 0
}
}
rptt := &system.MemoryPressureReport{
Level: 0, // assumption
Stats: *mStats,
}
putMemoryPressureEvent(rptt, false)
curMemoryPressure = 0 // reset
}()
}
curMemoryPressure = rpt.Level
//
putMemoryPressureEvent(rpt, true)
}
func putMemoryPressureEvent(rpt *system.MemoryPressureReport, setRisingEdge bool) {
var description string
if rpt.Stats.Usage.Limit == 0 {
// it's hitting node's limit
ratio := uint64(rpt.Stats.WorkingSet * 100 / uint64(Host.Memory))
if setRisingEdge {
description = fmt.Sprintf("Memory usage[%d kB] is more than %d %% of the node memory[%d kB]", rpt.Stats.WorkingSet/1024, ratio, Host.Memory/1024)
} else {
description = fmt.Sprintf("Memory usage[%d kB] is normal, %d %% of the node memory[%d kB]", rpt.Stats.WorkingSet/1024, ratio, Host.Memory/1024)
}
} else {
ratio := uint64(rpt.Stats.WorkingSet * 100 / rpt.Stats.Usage.Limit)
if setRisingEdge {
description = fmt.Sprintf("Memory usage[%d kB] is more than %d %% of the container memory limit[%d kB]", rpt.Stats.WorkingSet/1024, ratio, rpt.Stats.Usage.Limit/1024)
} else {
description = fmt.Sprintf("Memory usage[%d kB] is normal, %d %% of the container memory limit[%d kB]", rpt.Stats.WorkingSet/1024, ratio, rpt.Stats.Usage.Limit/1024)
}
}
report := map[string]interface{} {
"Description": description,
"Level": rpt.Level,
"UsageLimit": rpt.Stats.Usage.Limit,
"NetUsage": rpt.Stats.WorkingSet,
"MaxUsage": rpt.Stats.Usage.MaxUsage,
"ActiveAnon": rpt.Stats.Stats["active_anon"],
"InactiveAnon": rpt.Stats.Stats["inactive_anon"],
"Cache": rpt.Stats.Stats["cache"],
"PageFaults": rpt.Stats.Stats["pgfault"],
"RSS": rpt.Stats.Stats["rss"],
"Failcnt": rpt.Stats.Usage.Failcnt,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(report)
msg := b.String()
// log.WithFields(log.Fields{"msg": msg}).Debug()
clog := share.CLUSEventLog{
Event: share.CLUSEvMemoryPressureController,
ControllerID: Ctrler.ID,
ControllerName: Ctrler.Name,
ReportedAt: time.Now().UTC(),
Msg: msg,
}
evqueue.Append(&clog)
}
func ctlrPutLocalInfo() {
log.Debug("")
Ctrler.JoinedAt = time.Now().UTC()
var value []byte
var key string
// Don't report host for controller
/*
value, _ = json.Marshal(Host)
key = share.CLUSHostKey(Host.ID, "controller")
if err := cluster.Put(key, value); err != nil {
log.WithFields(log.Fields{"error": err}).Error("")
}
*/
value, _ = json.Marshal(Ctrler)
key = share.CLUSControllerKey(Host.ID, Ctrler.ID)
if err := cluster.Put(key, value); err != nil {
log.WithFields(log.Fields{"error": err}).Error("")
}
}
func ctrlDeleteLocalInfo() {
log.Debug("")
var key string
key = share.CLUSControllerKey(Host.ID, Ctrler.ID)
if err := cluster.Delete(key); err != nil {
log.WithFields(log.Fields{"error": err}).Error("")
}
key = share.CLUSUniconfControllerKey(Ctrler.ID, Ctrler.ID)
if err := cluster.Delete(key); err != nil {
log.WithFields(log.Fields{"error": err}).Error("")
}
clusHelper := kv.GetClusterHelper()
clusHelper.DeleteScanner(Ctrler.ID)
}