MCPcopy
hub / github.com/crowdsecurity/crowdsec / FlushAlerts

Method FlushAlerts

pkg/database/flush.go:244–330  ·  view source on GitHub ↗
(ctx context.Context, maxAge time.Duration, maxItems int)

Source from the content-addressed store, hash-verified

242}
243
244func (c *Client) FlushAlerts(ctx context.Context, maxAge time.Duration, maxItems int) error {
245 var (
246 deletedByAge int
247 deletedByNbItem int
248 totalAlerts int
249 err error
250 )
251
252 if !c.CanFlush {
253 c.Log.Debug("a list is being imported, flushing later")
254 return nil
255 }
256
257 c.Log.Debug("Flushing orphan alerts")
258 c.FlushOrphans(ctx)
259 c.Log.Debug("Done flushing orphan alerts")
260
261 totalAlerts, err = c.TotalAlerts(ctx)
262 if err != nil {
263 c.Log.Warningf("FlushAlerts (max items count): %s", err)
264 return fmt.Errorf("unable to get alerts count: %w", err)
265 }
266
267 c.Log.Debugf("FlushAlerts (Total alerts): %d", totalAlerts)
268
269 if maxAge != 0 {
270 filter := map[string][]string{
271 "created_before": {maxAge.String()},
272 }
273
274 nbDeleted, err := c.DeleteAlertWithFilter(ctx, filter)
275 if err != nil {
276 c.Log.Warningf("FlushAlerts (max age): %s", err)
277 return fmt.Errorf("unable to flush alerts with filter until=%s: %w", maxAge, err)
278 }
279
280 c.Log.Debugf("FlushAlerts (deleted max age alerts): %d", nbDeleted)
281 deletedByAge = nbDeleted
282 }
283
284 if maxItems > 0 {
285 // We get the highest id for the alerts
286 // We subtract MaxItems to avoid deleting alerts that are not old enough
287 // This gives us the oldest alert that we want to keep
288 // We then delete all the alerts with an id lower than this one
289 // We can do this because the id is auto-increment, and the database won't reuse the same id twice
290 lastAlert, err := c.QueryAlertWithFilter(ctx, map[string][]string{
291 "sort": {"DESC"},
292 "limit": {"1"},
293 // we do not care about fetching the edges, we just want the id
294 "with_decisions": {"false"},
295 })
296 c.Log.Debugf("FlushAlerts (last alert): %+v", lastAlert)
297
298 if err != nil {
299 c.Log.Errorf("FlushAlerts: could not get last alert: %s", err)
300 return fmt.Errorf("could not get last alert: %w", err)
301 }

Callers 1

newFlushCmdMethod · 0.80

Calls 10

FlushOrphansMethod · 0.95
TotalAlertsMethod · 0.95
DeleteAlertWithFilterMethod · 0.95
QueryAlertWithFilterMethod · 0.95
IDLTFunction · 0.92
DebugMethod · 0.45
StringMethod · 0.45
ExecMethod · 0.45
WhereMethod · 0.45
DeleteMethod · 0.45

Tested by

no test coverage detected