-
Notifications
You must be signed in to change notification settings - Fork 1
/
cleanup.go
96 lines (77 loc) · 2.6 KB
/
cleanup.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
package main
import (
"database/sql"
"errors"
"fmt"
"time"
)
const IcingaPrefix = "icinga_"
type Table struct {
Name string
TimeColumn string
}
// Known tables from the IDO with their time column
// Compare with DbConnection::CleanUpHandler()
// https://github.com/Icinga/icinga2/blob/master/lib/db_ido/dbconnection.cpp
var knownTables = []Table{
{"acknowledgements", "entry_time"},
{"commenthistory", "entry_time"},
{"contactnotifications", "start_time"},
{"contactnotificationmethods", "start_time"},
{"downtimehistory", "entry_time"},
{"eventhandlers", "start_time"},
{"externalcommands", "entry_time"},
{"flappinghistory", "event_time"},
{"hostchecks", "start_time"},
{"logentries", "logentry_time"},
{"notifications", "start_time"},
{"processevents", "event_time"},
{"statehistory", "state_time"},
{"servicechecks", "start_time"},
{"systemcommands", "start_time"},
}
// OldestTime retrieves the timestamp of the oldest row in the table.
func (t Table) OldestTime(db *sql.DB, instanceID int) (ts time.Time, err error) {
query := fmt.Sprintf("SELECT %s FROM %s%s WHERE instance_id = ? ORDER BY %s ASC LIMIT 1", //nolint:gosec
t.TimeColumn, IcingaPrefix, t.Name, t.TimeColumn)
row := db.QueryRow(query, instanceID)
var tsString string
err = row.Scan(&tsString)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
err = nil
return
}
err = fmt.Errorf("could not get oldest time for %s: %w", t.Name, err)
return
}
ts, err = time.Parse("2006-01-02 15:04:05", tsString)
if err != nil {
err = fmt.Errorf("could not parse date: %s - %w", tsString, err)
return
}
return
}
// Cleanup purges old entries, filtered by instanceID, any entry older then since, limited by limit.
func (t Table) Cleanup(db *sql.DB, instanceID int, since time.Time, limit int) (rows int64, err error) {
query := fmt.Sprintf("DELETE FROM %s%s WHERE instance_id = ? AND %s < ? LIMIT %d", //nolint:gosec
IcingaPrefix, t.Name, t.TimeColumn, limit)
result, err := db.Exec(query, instanceID, since)
if err != nil {
err = fmt.Errorf("could not purge rows for %s: %w", t.Name, err)
return
}
return result.RowsAffected() //nolint:wrapcheck
}
// Count returns the number of rows that should be deleted based on since.
func (t Table) Count(db *sql.DB, instanceID int, since time.Time) (rows int64, err error) {
query := fmt.Sprintf("SELECT count(*) FROM %s%s WHERE instance_id = ? AND %s < ?", //nolint:gosec
IcingaPrefix, t.Name, t.TimeColumn)
row := db.QueryRow(query, instanceID, since)
err = row.Scan(&rows)
if err != nil {
err = fmt.Errorf("could not purge rows for %s: %w", t.Name, err)
return
}
return
}