-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdb_maintenance.go
More file actions
249 lines (223 loc) · 6.13 KB
/
db_maintenance.go
File metadata and controls
249 lines (223 loc) · 6.13 KB
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
package server
import (
"context"
"encoding/binary"
"hash/fnv"
mathrand "math/rand"
"regexp"
"slices"
"strings"
"sync"
"time"
"github.com/urnetwork/glog"
)
const DbReindexEpochs = uint64(8)
// per the posgres docs, remove indexes that end in _ccnew\d* or _ccold\d*
var incompleteIndexNamePattern = sync.OnceValue(func() *regexp.Regexp {
return regexp.MustCompile("^(?:.*_ccnew\\d*|.*_ccold\\d*)$")
})
func isIncompleteIndexName(indexName string) bool {
return incompleteIndexNamePattern().MatchString(indexName)
}
func DefaultDbMaintenanceOptions() *DbMaintenanceOptions {
return &DbMaintenanceOptions{
Reindex: true,
Cleanup: true,
Analyze: true,
}
}
type DbMaintenanceOptions struct {
Reindex bool
Cleanup bool
Analyze bool
}
func DbMaintenanceWithDefaults(ctx context.Context, epoch uint64) {
DbMaintenance(ctx, epoch, DefaultDbMaintenanceOptions())
}
func DbMaintenance(ctx context.Context, epoch uint64, opts *DbMaintenanceOptions) {
// regularly reindex tables to avoid bloat:
// 1. tables are reindexed over `DbReindexEpochs` epochs
// e.g. `DbReindexEpochs=4` means all tables will be reindexed over 4 maintenance epochs
// 2. ANALYZE is called after each maintenance to update the planner stats
// note `REINDEX CONCURRENTLY` can be safely run in the background
// see https://www.postgresql.org/docs/current/sql-reindex.html
// these tables are too large are updated too frequently to reindex regularly
// each table here should have some alternate management strategy
skipReindexTables := map[string]bool{
"client_reliability": true,
"network_client_location_reliability": true,
"network_client_connection": true,
}
reindex := func(conn PgConn, tableName string) {
if !skipReindexTables[tableName] {
// note "reindex concurrently" can in some rare cases cause a deadlock with autovacuum
// use a timeout to recover from these cases
// any reindex taking longer than the timeout should generally be added to `skipReindexTables`
timeoutCtx, timeoutCancel := context.WithTimeout(ctx, 2*time.Hour)
defer timeoutCancel()
RaisePgResult(conn.Exec(
timeoutCtx,
`
REINDEX TABLE CONCURRENTLY
`+tableName,
))
}
}
cleanUpIncompleteIndexes := func(conn PgConn, tableName string) {
incompleteIndexNames := []string{}
result, err := conn.Query(
ctx,
`
SELECT
pg_class.relname AS index_name
FROM
pg_class
INNER JOIN
pg_index ON pg_index.indexrelid = pg_class.oid
INNER JOIN
pg_class t ON t.oid = pg_index.indrelid
WHERE
pg_index.indisvalid = false AND
t.relname = $1
`,
tableName,
)
WithPgResult(result, err, func() {
for result.Next() {
var indexName string
Raise(result.Scan(&indexName))
if isIncompleteIndexName(indexName) {
incompleteIndexNames = append(incompleteIndexNames, indexName)
}
}
})
for i, incompleteIndexName := range incompleteIndexNames {
glog.Infof(
"[db]maintenance found incomplete index[%d/%d] %s on table %s\n",
i+1,
len(incompleteIndexNames),
incompleteIndexName,
tableName,
)
RaisePgResult(conn.Exec(
ctx,
`
DROP INDEX CONCURRENTLY IF EXISTS
`+incompleteIndexName,
))
}
}
tableNames := []string{}
reindexTableNames := []string{}
MaintenanceDb(ctx, func(conn PgConn) {
result, err := conn.Query(
ctx,
`
SELECT
table_name
FROM information_schema.tables
WHERE
table_schema = 'public' AND
table_type = 'BASE TABLE'
`,
)
WithPgResult(result, err, func() {
for result.Next() {
var tableName string
Raise(result.Scan(&tableName))
tableNames = append(tableNames, tableName)
}
})
for _, tableName := range tableNames {
hash := fnv.New64()
hash.Write([]byte(tableName))
b := make([]byte, 8)
// cycle the hash each generation
binary.BigEndian.PutUint64(b, epoch/DbReindexEpochs)
hash.Write(b)
h := hash.Sum64()
if h%DbReindexEpochs == epoch%DbReindexEpochs {
reindexTableNames = append(reindexTableNames, tableName)
}
}
})
slices.Sort(reindexTableNames)
glog.Infof(
"[db]maintenance %d/%d tables (in random order): %s\n",
len(reindexTableNames),
len(tableNames),
strings.Join(reindexTableNames, ", "),
)
mathrand.Shuffle(len(reindexTableNames), func(i int, j int) {
reindexTableNames[i], reindexTableNames[j] = reindexTableNames[j], reindexTableNames[i]
})
if opts.Reindex {
// reindex concurrently
for i, reindexTableName := range reindexTableNames {
glog.Infof(
"[db]maintenance reindex[%d/%d] %s\n",
i+1,
len(reindexTableNames),
reindexTableName,
)
// pg might raise a deadlock or other unrecoverable error during reindex
HandleError(func() {
MaintenanceDb(ctx, func(conn PgConn) {
// reindex
startTime := time.Now()
reindex(conn, reindexTableName)
endTime := time.Now()
glog.Infof(
"[db]maintenance reindex[%d/%d] %s reindex took %.2fs\n",
i+1,
len(reindexTableNames),
reindexTableName,
float64(endTime.Sub(startTime)/time.Millisecond)/1000.0,
)
}, OptNoRetry())
})
}
}
if opts.Cleanup {
for i, reindexTableName := range reindexTableNames {
glog.Infof(
"[db]maintenance reindex[%d/%d] cleanup %s\n",
i+1,
len(reindexTableNames),
reindexTableName,
)
HandleError(func() {
MaintenanceDb(ctx, func(conn PgConn) {
startTime := time.Now()
cleanUpIncompleteIndexes(conn, reindexTableName)
endTime := time.Now()
glog.Infof(
"[db]maintenance reindex[%d/%d] cleanup %s took %.2fs\n",
i+1,
len(reindexTableNames),
reindexTableName,
float64(endTime.Sub(startTime)/time.Millisecond)/1000.0,
)
}, OptNoRetry())
})
}
}
if opts.Analyze {
HandleError(func() {
MaintenanceDb(ctx, func(conn PgConn) {
glog.Infof("[db]maintenance final analyze\n")
// final analyze
startTime := time.Now()
RaisePgResult(conn.Exec(
ctx,
`ANALYZE`,
))
endTime := time.Now()
glog.Infof(
"[db]maintenance final analyze took %.2fs\n",
float64(endTime.Sub(startTime)/time.Millisecond)/1000.0,
)
}, OptNoRetry())
})
}
}