-
Notifications
You must be signed in to change notification settings - Fork 394
/
handler.go
386 lines (313 loc) · 11 KB
/
handler.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// Copyright 2021 FerretDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package handler provides a universal handler implementation for all backends.
package handler
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
"github.com/FerretDB/FerretDB/internal/backends"
"github.com/FerretDB/FerretDB/internal/backends/decorators/oplog"
"github.com/FerretDB/FerretDB/internal/clientconn/conninfo"
"github.com/FerretDB/FerretDB/internal/clientconn/connmetrics"
"github.com/FerretDB/FerretDB/internal/clientconn/cursor"
"github.com/FerretDB/FerretDB/internal/types"
"github.com/FerretDB/FerretDB/internal/util/iterator"
"github.com/FerretDB/FerretDB/internal/util/lazyerrors"
"github.com/FerretDB/FerretDB/internal/util/must"
"github.com/FerretDB/FerretDB/internal/util/state"
)
// Parts of Prometheus metric names.
const (
namespace = "ferretdb"
subsystem = "handler"
)
// Handler provides a set of methods to process clients' requests sent over wire protocol.
//
// MsgXXX methods handle OP_MSG commands.
// CmdQuery handles a limited subset of OP_QUERY messages.
//
// Handler instance is shared between all client connections.
type Handler struct {
*NewOpts
b backends.Backend
cursors *cursor.Registry
commands map[string]command
wg sync.WaitGroup
cappedCleanupStop chan struct{}
cleanupCappedCollectionsDocs *prometheus.CounterVec
cleanupCappedCollectionsBytes *prometheus.CounterVec
}
// NewOpts represents handler configuration.
//
//nolint:vet // for readability
type NewOpts struct {
Backend backends.Backend
TCPHost string
ReplSetName string
L *zap.Logger
ConnMetrics *connmetrics.ConnMetrics
StateProvider *state.Provider
// test options
DisablePushdown bool
EnableNestedPushdown bool
CappedCleanupInterval time.Duration
CappedCleanupPercentage uint8
EnableNewAuth bool
BatchSize int
}
// New returns a new handler.
func New(opts *NewOpts) (*Handler, error) {
b := oplog.NewBackend(opts.Backend, opts.L.Named("oplog"))
if opts.CappedCleanupPercentage >= 100 || opts.CappedCleanupPercentage <= 0 {
return nil, fmt.Errorf(
"percentage of documents to cleanup must be in range (0, 100), but %d given",
opts.CappedCleanupPercentage,
)
}
h := &Handler{
b: b,
NewOpts: opts,
cursors: cursor.NewRegistry(opts.L.Named("cursors")),
cappedCleanupStop: make(chan struct{}),
cleanupCappedCollectionsDocs: prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "cleanup_capped_docs",
Help: "Total number of documents deleted in capped collections during cleanup.",
},
[]string{"db", "collection"},
),
cleanupCappedCollectionsBytes: prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "cleanup_capped_bytes",
Help: "Total number of bytes freed in capped collections during cleanup.",
},
[]string{"db", "collection"},
),
}
h.initCommands()
h.wg.Add(1)
go func() {
defer h.wg.Done()
h.runCappedCleanup()
}()
return h, nil
}
// runCapppedCleanup calls capped collections cleanup function according to the given interval.
func (h *Handler) runCappedCleanup() {
if h.CappedCleanupInterval <= 0 {
h.L.Info("Capped collections cleanup disabled.")
return
}
h.L.Info("Capped collections cleanup enabled.", zap.Duration("interval", h.CappedCleanupInterval))
ticker := time.NewTicker(h.CappedCleanupInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := h.cleanupAllCappedCollections(context.Background()); err != nil {
h.L.Error("Failed to cleanup capped collections.", zap.Error(err))
}
case <-h.cappedCleanupStop:
h.L.Info("Capped collections cleanup stopped.")
return
}
}
}
// Close gracefully shutdowns handler.
// It should be called after listener closes all client connections and stops listening.
func (h *Handler) Close() {
h.cursors.Close()
close(h.cappedCleanupStop)
h.wg.Wait()
}
// Describe implements prometheus.Collector interface.
func (h *Handler) Describe(ch chan<- *prometheus.Desc) {
h.b.Describe(ch)
h.cursors.Describe(ch)
h.cleanupCappedCollectionsDocs.Describe(ch)
h.cleanupCappedCollectionsBytes.Describe(ch)
}
// Collect implements prometheus.Collector interface.
func (h *Handler) Collect(ch chan<- prometheus.Metric) {
h.b.Collect(ch)
h.cursors.Collect(ch)
h.cleanupCappedCollectionsDocs.Collect(ch)
h.cleanupCappedCollectionsBytes.Collect(ch)
}
// cleanupAllCappedCollections drops the given percent of documents from all capped collections.
func (h *Handler) cleanupAllCappedCollections(ctx context.Context) error {
h.L.Debug("cleanupAllCappedCollections: started", zap.Uint8("percentage", h.CappedCleanupPercentage))
start := time.Now()
defer func() {
h.L.Debug("cleanupAllCappedCollections: finished", zap.Duration("duration", time.Since(start)))
}()
connInfo := conninfo.New()
connInfo.SetBypassBackendAuth()
ctx = conninfo.Ctx(ctx, connInfo)
dbList, err := h.b.ListDatabases(ctx, nil)
if err != nil {
return lazyerrors.Error(err)
}
for _, dbInfo := range dbList.Databases {
db, err := h.b.Database(dbInfo.Name)
if err != nil {
return lazyerrors.Error(err)
}
cList, err := db.ListCollections(ctx, nil)
if err != nil {
return lazyerrors.Error(err)
}
for _, cInfo := range cList.Collections {
if !cInfo.Capped() {
continue
}
deleted, bytesFreed, err := h.cleanupCappedCollection(ctx, db, &cInfo, false)
if err != nil {
if backends.ErrorCodeIs(err, backends.ErrorCodeCollectionDoesNotExist) ||
backends.ErrorCodeIs(err, backends.ErrorCodeDatabaseDoesNotExist) {
continue
}
return lazyerrors.Error(err)
}
if deleted > 0 || bytesFreed > 0 {
h.L.Info("Capped collection cleaned up.",
zap.String("db", dbInfo.Name), zap.String("collection", cInfo.Name),
zap.Int32("deleted", deleted), zap.Int64("bytesFreed", bytesFreed),
)
}
h.cleanupCappedCollectionsDocs.WithLabelValues(dbInfo.Name, cInfo.Name).Add(float64(deleted))
h.cleanupCappedCollectionsBytes.WithLabelValues(dbInfo.Name, cInfo.Name).Add(float64(bytesFreed))
}
}
return nil
}
// cleanupCappedCollection drops a percent of documents from the given capped collection and compacts it.
func (h *Handler) cleanupCappedCollection(ctx context.Context, db backends.Database, cInfo *backends.CollectionInfo, force bool) (int32, int64, error) { //nolint:lll // for readability
must.BeTrue(cInfo.Capped())
var docsDeleted int32
var bytesFreed int64
var statsBefore, statsAfter *backends.CollectionStatsResult
coll, err := db.Collection(cInfo.Name)
if err != nil {
return 0, 0, lazyerrors.Error(err)
}
statsBefore, err = coll.Stats(ctx, &backends.CollectionStatsParams{Refresh: true})
if err != nil {
return 0, 0, lazyerrors.Error(err)
}
h.L.Debug("cleanupCappedCollection: stats before", zap.Any("stats", statsBefore))
// In order to be more precise w.r.t number of documents getting dropped and to avoid
// deleting too many documents unnecessarily,
//
// - First, drop the surplus documents, if document count exceeds capped configuration.
// - Collect stats again.
// - If collection size still exceeds the capped size, then drop the documents based on
// CappedCleanupPercentage.
if count := getDocCleanupCount(cInfo, statsBefore); count > 0 {
err = deleteFirstNDocuments(ctx, coll, count)
if err != nil {
return 0, 0, lazyerrors.Error(err)
}
statsAfter, err = coll.Stats(ctx, &backends.CollectionStatsParams{Refresh: true})
if err != nil {
return 0, 0, lazyerrors.Error(err)
}
h.L.Debug("cleanupCappedCollection: stats after document count reduction", zap.Any("stats", statsAfter))
docsDeleted += int32(count)
bytesFreed += (statsBefore.SizeTotal - statsAfter.SizeTotal)
statsBefore = statsAfter
}
if count := getSizeCleanupCount(cInfo, statsBefore, h.CappedCleanupPercentage); count > 0 {
err = deleteFirstNDocuments(ctx, coll, count)
if err != nil {
return 0, 0, lazyerrors.Error(err)
}
docsDeleted += int32(count)
}
if _, err = coll.Compact(ctx, &backends.CompactParams{Full: force}); err != nil {
return 0, 0, lazyerrors.Error(err)
}
statsAfter, err = coll.Stats(ctx, &backends.CollectionStatsParams{Refresh: true})
if err != nil {
return 0, 0, lazyerrors.Error(err)
}
h.L.Debug("cleanupCappedCollection: stats after compact", zap.Any("stats", statsAfter))
bytesFreed += (statsBefore.SizeTotal - statsAfter.SizeTotal)
// There's a possibility that the size of a collection might be greater at the
// end of a compact operation if the collection is being actively written to at
// the time of compaction.
if bytesFreed < 0 {
bytesFreed = 0
}
return docsDeleted, bytesFreed, nil
}
// getDocCleanupCount returns the number of documents to be deleted during capped collection cleanup
// based on document count of the collection and capped configuration.
func getDocCleanupCount(cInfo *backends.CollectionInfo, cStats *backends.CollectionStatsResult) int64 {
if cInfo.CappedDocuments == 0 || cInfo.CappedDocuments >= cStats.CountDocuments {
return 0
}
return (cStats.CountDocuments - cInfo.CappedDocuments)
}
// getSizeCleanupCount returns the number of documents to be deleted during capped collection cleanup
// based collection size, capped configuration and cleanup percentage.
func getSizeCleanupCount(cInfo *backends.CollectionInfo, cStats *backends.CollectionStatsResult, cleanupPercent uint8) int64 {
if cInfo.CappedSize >= cStats.SizeCollection {
return 0
}
return int64(float64(cStats.CountDocuments) * float64(cleanupPercent) / 100)
}
// deleteFirstNDocuments drops first n documents (based on order of insertion) from the collection.
func deleteFirstNDocuments(ctx context.Context, coll backends.Collection, n int64) error {
if n == 0 {
return nil
}
res, err := coll.Query(ctx, &backends.QueryParams{
Sort: must.NotFail(types.NewDocument("$natural", int64(1))),
Limit: n,
OnlyRecordIDs: true,
})
if err != nil {
return lazyerrors.Error(err)
}
defer res.Iter.Close()
var recordIDs []int64
for {
var doc *types.Document
_, doc, err = res.Iter.Next()
if err != nil {
if errors.Is(err, iterator.ErrIteratorDone) {
break
}
return lazyerrors.Error(err)
}
recordIDs = append(recordIDs, doc.RecordID())
}
if len(recordIDs) > 0 {
_, err := coll.DeleteAll(ctx, &backends.DeleteAllParams{RecordIDs: recordIDs})
if err != nil {
return lazyerrors.Error(err)
}
}
return nil
}