-
Notifications
You must be signed in to change notification settings - Fork 429
/
flush.go
279 lines (244 loc) · 8.8 KB
/
flush.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
package database
import (
"errors"
"fmt"
"time"
"github.com/go-co-op/gocron"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/alert"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/bouncer"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/event"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
func (c *Client) StartFlushScheduler(config *csconfig.FlushDBCfg) (*gocron.Scheduler, error) {
maxItems := 0
maxAge := ""
if config.MaxItems != nil && *config.MaxItems <= 0 {
return nil, errors.New("max_items can't be zero or negative number")
}
if config.MaxItems != nil {
maxItems = *config.MaxItems
}
if config.MaxAge != nil && *config.MaxAge != "" {
maxAge = *config.MaxAge
}
// Init & Start cronjob every minute for alerts
scheduler := gocron.NewScheduler(time.UTC)
job, err := scheduler.Every(1).Minute().Do(c.FlushAlerts, maxAge, maxItems)
if err != nil {
return nil, fmt.Errorf("while starting FlushAlerts scheduler: %w", err)
}
job.SingletonMode()
// Init & Start cronjob every hour for bouncers/agents
if config.AgentsGC != nil {
if config.AgentsGC.Cert != nil {
duration, err := ParseDuration(*config.AgentsGC.Cert)
if err != nil {
return nil, fmt.Errorf("while parsing agents cert auto-delete duration: %w", err)
}
config.AgentsGC.CertDuration = &duration
}
if config.AgentsGC.LoginPassword != nil {
duration, err := ParseDuration(*config.AgentsGC.LoginPassword)
if err != nil {
return nil, fmt.Errorf("while parsing agents login/password auto-delete duration: %w", err)
}
config.AgentsGC.LoginPasswordDuration = &duration
}
if config.AgentsGC.Api != nil {
log.Warning("agents auto-delete for API auth is not supported (use cert or login_password)")
}
}
if config.BouncersGC != nil {
if config.BouncersGC.Cert != nil {
duration, err := ParseDuration(*config.BouncersGC.Cert)
if err != nil {
return nil, fmt.Errorf("while parsing bouncers cert auto-delete duration: %w", err)
}
config.BouncersGC.CertDuration = &duration
}
if config.BouncersGC.Api != nil {
duration, err := ParseDuration(*config.BouncersGC.Api)
if err != nil {
return nil, fmt.Errorf("while parsing bouncers api auto-delete duration: %w", err)
}
config.BouncersGC.ApiDuration = &duration
}
if config.BouncersGC.LoginPassword != nil {
log.Warning("bouncers auto-delete for login/password auth is not supported (use cert or api)")
}
}
baJob, err := scheduler.Every(1).Minute().Do(c.FlushAgentsAndBouncers, config.AgentsGC, config.BouncersGC)
if err != nil {
return nil, fmt.Errorf("while starting FlushAgentsAndBouncers scheduler: %w", err)
}
baJob.SingletonMode()
scheduler.StartAsync()
return scheduler, nil
}
func (c *Client) FlushOrphans() {
/* While it has only been linked to some very corner-case bug : https://github.com/crowdsecurity/crowdsec/issues/778 */
/* We want to take care of orphaned events for which the parent alert/decision has been deleted */
eventsCount, err := c.Ent.Event.Delete().Where(event.Not(event.HasOwner())).Exec(c.CTX)
if err != nil {
c.Log.Warningf("error while deleting orphan events: %s", err)
return
}
if eventsCount > 0 {
c.Log.Infof("%d deleted orphan events", eventsCount)
}
eventsCount, err = c.Ent.Decision.Delete().Where(
decision.Not(decision.HasOwner())).Where(decision.UntilLTE(time.Now().UTC())).Exec(c.CTX)
if err != nil {
c.Log.Warningf("error while deleting orphan decisions: %s", err)
return
}
if eventsCount > 0 {
c.Log.Infof("%d deleted orphan decisions", eventsCount)
}
}
func (c *Client) flushBouncers(bouncersCfg *csconfig.AuthGCCfg) {
if bouncersCfg == nil {
return
}
if bouncersCfg.ApiDuration != nil {
log.Debug("trying to delete old bouncers from api")
deletionCount, err := c.Ent.Bouncer.Delete().Where(
bouncer.LastPullLTE(time.Now().UTC().Add(-*bouncersCfg.ApiDuration)),
).Where(
bouncer.AuthTypeEQ(types.ApiKeyAuthType),
).Exec(c.CTX)
if err != nil {
c.Log.Errorf("while auto-deleting expired bouncers (api key): %s", err)
} else if deletionCount > 0 {
c.Log.Infof("deleted %d expired bouncers (api auth)", deletionCount)
}
}
if bouncersCfg.CertDuration != nil {
log.Debug("trying to delete old bouncers from cert")
deletionCount, err := c.Ent.Bouncer.Delete().Where(
bouncer.LastPullLTE(time.Now().UTC().Add(-*bouncersCfg.CertDuration)),
).Where(
bouncer.AuthTypeEQ(types.TlsAuthType),
).Exec(c.CTX)
if err != nil {
c.Log.Errorf("while auto-deleting expired bouncers (api key): %s", err)
} else if deletionCount > 0 {
c.Log.Infof("deleted %d expired bouncers (api auth)", deletionCount)
}
}
}
func (c *Client) flushAgents(agentsCfg *csconfig.AuthGCCfg) {
if agentsCfg == nil {
return
}
if agentsCfg.CertDuration != nil {
log.Debug("trying to delete old agents from cert")
deletionCount, err := c.Ent.Machine.Delete().Where(
machine.LastHeartbeatLTE(time.Now().UTC().Add(-*agentsCfg.CertDuration)),
).Where(
machine.Not(machine.HasAlerts()),
).Where(
machine.AuthTypeEQ(types.TlsAuthType),
).Exec(c.CTX)
log.Debugf("deleted %d entries", deletionCount)
if err != nil {
c.Log.Errorf("while auto-deleting expired machine (cert): %s", err)
} else if deletionCount > 0 {
c.Log.Infof("deleted %d expired machine (cert auth)", deletionCount)
}
}
if agentsCfg.LoginPasswordDuration != nil {
log.Debug("trying to delete old agents from password")
deletionCount, err := c.Ent.Machine.Delete().Where(
machine.LastHeartbeatLTE(time.Now().UTC().Add(-*agentsCfg.LoginPasswordDuration)),
).Where(
machine.Not(machine.HasAlerts()),
).Where(
machine.AuthTypeEQ(types.PasswordAuthType),
).Exec(c.CTX)
log.Debugf("deleted %d entries", deletionCount)
if err != nil {
c.Log.Errorf("while auto-deleting expired machine (password): %s", err)
} else if deletionCount > 0 {
c.Log.Infof("deleted %d expired machine (password auth)", deletionCount)
}
}
}
func (c *Client) FlushAgentsAndBouncers(agentsCfg *csconfig.AuthGCCfg, bouncersCfg *csconfig.AuthGCCfg) error {
log.Debug("starting FlushAgentsAndBouncers")
c.flushBouncers(bouncersCfg)
c.flushAgents(agentsCfg)
return nil
}
func (c *Client) FlushAlerts(MaxAge string, MaxItems int) error {
var deletedByAge int
var deletedByNbItem int
var totalAlerts int
var err error
if !c.CanFlush {
c.Log.Debug("a list is being imported, flushing later")
return nil
}
c.Log.Debug("Flushing orphan alerts")
c.FlushOrphans()
c.Log.Debug("Done flushing orphan alerts")
totalAlerts, err = c.TotalAlerts()
if err != nil {
c.Log.Warningf("FlushAlerts (max items count): %s", err)
return fmt.Errorf("unable to get alerts count: %w", err)
}
c.Log.Debugf("FlushAlerts (Total alerts): %d", totalAlerts)
if MaxAge != "" {
filter := map[string][]string{
"created_before": {MaxAge},
}
nbDeleted, err := c.DeleteAlertWithFilter(filter)
if err != nil {
c.Log.Warningf("FlushAlerts (max age): %s", err)
return fmt.Errorf("unable to flush alerts with filter until=%s: %w", MaxAge, err)
}
c.Log.Debugf("FlushAlerts (deleted max age alerts): %d", nbDeleted)
deletedByAge = nbDeleted
}
if MaxItems > 0 {
//We get the highest id for the alerts
//We subtract MaxItems to avoid deleting alerts that are not old enough
//This gives us the oldest alert that we want to keep
//We then delete all the alerts with an id lower than this one
//We can do this because the id is auto-increment, and the database won't reuse the same id twice
lastAlert, err := c.QueryAlertWithFilter(map[string][]string{
"sort": {"DESC"},
"limit": {"1"},
//we do not care about fetching the edges, we just want the id
"with_decisions": {"false"},
})
c.Log.Debugf("FlushAlerts (last alert): %+v", lastAlert)
if err != nil {
c.Log.Errorf("FlushAlerts: could not get last alert: %s", err)
return fmt.Errorf("could not get last alert: %w", err)
}
if len(lastAlert) != 0 {
maxid := lastAlert[0].ID - MaxItems
c.Log.Debugf("FlushAlerts (max id): %d", maxid)
if maxid > 0 {
//This may lead to orphan alerts (at least on MySQL), but the next time the flush job will run, they will be deleted
deletedByNbItem, err = c.Ent.Alert.Delete().Where(alert.IDLT(maxid)).Exec(c.CTX)
if err != nil {
c.Log.Errorf("FlushAlerts: Could not delete alerts: %s", err)
return fmt.Errorf("could not delete alerts: %w", err)
}
}
}
}
if deletedByNbItem > 0 {
c.Log.Infof("flushed %d/%d alerts because the max number of alerts has been reached (%d max)", deletedByNbItem, totalAlerts, MaxItems)
}
if deletedByAge > 0 {
c.Log.Infof("flushed %d/%d alerts because they were created %s ago or more", deletedByAge, totalAlerts, MaxAge)
}
return nil
}