forked from ngaut/unistore
/
snap_manager.go
370 lines (344 loc) · 8.83 KB
/
snap_manager.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
// Copyright 2019-present PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package raftstore
import (
"io/ioutil"
"math"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pingcap/errors"
rspb "github.com/pingcap/kvproto/pkg/raft_serverpb"
"github.com/pingcap/log"
)
type SnapEntry int
const (
SnapEntryGenerating SnapEntry = 1
SnapEntrySending SnapEntry = 2
SnapEntryReceiving SnapEntry = 3
SnapEntryApplying SnapEntry = 4
)
func (e SnapEntry) String() string {
switch e {
case SnapEntryGenerating:
return "generating"
case SnapEntrySending:
return "sending"
case SnapEntryReceiving:
return "receiving"
case SnapEntryApplying:
return "applying"
}
return "unknown"
}
type SnapStats struct {
ReceivingCount int
SendingCount int
}
func notifyStats(router *router) {
if router != nil {
router.sendStore(NewMsg(MsgTypeStoreSnapshotStats, nil))
}
}
type SnapManager struct {
base string
snapSize *int64
registryLock sync.RWMutex
registry map[SnapKey][]SnapEntry
router *router
limiter *IOLimiter
MaxTotalSize uint64
}
func NewSnapManager(path string, router *router) *SnapManager {
return new(SnapManagerBuilder).Build(path, router)
}
func (sm *SnapManager) init() error {
fi, err := os.Stat(sm.base)
if os.IsNotExist(err) {
err = os.MkdirAll(sm.base, 0600)
if err != nil {
return errors.WithStack(err)
}
return nil
} else if err != nil {
return errors.WithStack(err)
}
if !fi.IsDir() {
return errors.Errorf("%s should be a directory", sm.base)
}
fis, err := ioutil.ReadDir(sm.base)
if err != nil {
return errors.WithStack(err)
}
for _, fi := range fis {
if !fi.IsDir() {
name := fi.Name()
if strings.HasSuffix(name, tmpFileSuffix) {
err = os.Remove(filepath.Join(sm.base, name))
if err != nil {
return errors.WithStack(err)
}
} else if strings.HasSuffix(name, sstFileSuffix) {
atomic.AddInt64(sm.snapSize, fi.Size())
}
}
}
return nil
}
func (sm *SnapManager) ListIdleSnap() ([]SnapKeyWithSending, error) {
fis, err := ioutil.ReadDir(sm.base)
if err != nil {
return nil, errors.WithStack(err)
}
results := make([]SnapKeyWithSending, 0, len(fis))
for _, fi := range fis {
if fi.IsDir() {
continue
}
name := fi.Name()
if !strings.HasSuffix(name, metaFileSuffix) {
continue
}
name = name[:len(name)-len(metaFileSuffix)]
var key SnapKeyWithSending
if strings.HasPrefix(name, snapGenPrefix) {
key.IsSending = true
}
numberStrs := strings.Split(name, "_")
if len(numberStrs) != 4 {
return nil, errors.Errorf("failed to parse file %s", name)
}
key.SnapKey.RegionID, err = strconv.ParseUint(numberStrs[1], 10, 64)
if err != nil {
return nil, errors.WithStack(err)
}
key.SnapKey.Term, err = strconv.ParseUint(numberStrs[2], 10, 64)
if err != nil {
return nil, errors.WithStack(err)
}
key.SnapKey.Index, err = strconv.ParseUint(numberStrs[3], 10, 64)
if err != nil {
return nil, errors.WithStack(err)
}
sm.registryLock.RLock()
_, ok := sm.registry[key.SnapKey]
sm.registryLock.RUnlock()
if ok {
// Skip those registered snapshot.
continue
}
results = append(results, key)
}
sort.Slice(results, func(i, j int) bool {
keyI := &results[i].SnapKey
keyJ := &results[j].SnapKey
if keyI.RegionID == keyJ.RegionID {
if keyI.Term == keyJ.Term {
if keyI.Index == keyJ.Index {
return !results[i].IsSending
}
return keyI.Index < keyJ.Index
}
return keyI.Term < keyJ.Term
}
return keyI.RegionID < keyJ.RegionID
})
return results, nil
}
func (sm *SnapManager) HasRegistered(key SnapKey) bool {
sm.registryLock.RLock()
_, ok := sm.registry[key]
sm.registryLock.RUnlock()
return ok
}
func (sm *SnapManager) GetTotalSnapSize() uint64 {
return uint64(atomic.LoadInt64(sm.snapSize))
}
func (sm *SnapManager) GetSnapshotForBuilding(key SnapKey) (Snapshot, error) {
if sm.GetTotalSnapSize() > sm.MaxTotalSize {
err := sm.deleteOldIdleSnaps()
if err != nil {
return nil, err
}
}
return NewSnapForBuilding(sm.base, key, sm.snapSize, sm, sm.limiter)
}
func (sm *SnapManager) deleteOldIdleSnaps() error {
idleSnaps, err := sm.ListIdleSnap()
if err != nil {
return err
}
type snapWithModTime struct {
key SnapKey
snap Snapshot
modTime time.Time
}
snaps := make([]snapWithModTime, 0, len(idleSnaps))
for _, idleSnap := range idleSnaps {
if !idleSnap.IsSending {
continue
}
snap, err := sm.GetSnapshotForSending(idleSnap.SnapKey)
if err != nil {
continue
}
fi, err := snap.Meta()
if err != nil {
return err
}
snaps = append(snaps, snapWithModTime{key: idleSnap.SnapKey, snap: snap, modTime: fi.ModTime()})
}
sort.Slice(snaps, func(i, j int) bool {
return snaps[i].modTime.Before(snaps[j].modTime)
})
for sm.GetTotalSnapSize() > sm.MaxTotalSize {
if len(snaps) == 0 {
return errors.New("too many snapshots")
}
oldest := snaps[0]
snaps = snaps[1:]
sm.DeleteSnapshot(oldest.key, oldest.snap, false)
}
return nil
}
func (sm *SnapManager) GetSnapshotForSending(snapKey SnapKey) (Snapshot, error) {
return NewSnapForSending(sm.base, snapKey, sm.snapSize, sm)
}
func (sm *SnapManager) GetSnapshotForReceiving(snapKey SnapKey, data []byte) (Snapshot, error) {
snapshotData := new(rspb.RaftSnapshotData)
err := snapshotData.Unmarshal(data)
if err != nil {
return nil, errors.WithStack(err)
}
return NewSnapForReceiving(sm.base, snapKey, snapshotData.Meta, sm.snapSize, sm, sm.limiter)
}
func (sm *SnapManager) GetSnapshotForApplying(snapKey SnapKey) (Snapshot, error) {
snap, err := NewSnapForApplying(sm.base, snapKey, sm.snapSize, sm)
if err != nil {
return nil, err
}
if !snap.Exists() {
return nil, errors.Errorf("snapshot of %s not exists", snapKey)
}
return snap, nil
}
func (sm *SnapManager) Register(key SnapKey, entry SnapEntry) {
log.S().Debugf("register key:%s, entry:%d", key, entry)
sm.registryLock.Lock()
defer sm.registryLock.Unlock()
entries, ok := sm.registry[key]
if ok {
for _, e := range entries {
if e == entry {
log.S().Warnf("%s is registered more than 1 time", key)
return
}
}
}
entries = append(entries, entry)
sm.registry[key] = entries
notifyStats(sm.router)
}
func (sm *SnapManager) Deregister(key SnapKey, entry SnapEntry) {
log.S().Debugf("deregister key:%s, entry:%s", key, entry)
sm.registryLock.Lock()
defer sm.registryLock.Unlock()
var handled bool
entries, ok := sm.registry[key]
if ok {
for i, e := range entries {
if e == entry {
entries = append(entries[:i], entries[i+1:]...)
handled = true
break
}
}
if handled {
if len(entries) > 0 {
sm.registry[key] = entries
} else {
delete(sm.registry, key)
}
notifyStats(sm.router)
return
}
}
log.S().Warnf("stale deregister key:%s, entry:%s", key, entry)
}
func (sm *SnapManager) Stats() SnapStats {
sm.registryLock.RLock()
defer sm.registryLock.RUnlock()
var sendingCount, receivingCount int
for _, entries := range sm.registry {
var isSending, isReceiving bool
for _, entry := range entries {
switch entry {
case SnapEntryGenerating, SnapEntrySending:
isSending = true
case SnapEntryReceiving, SnapEntryApplying:
isReceiving = true
}
}
if isSending {
sendingCount++
}
if isReceiving {
receivingCount++
}
}
return SnapStats{SendingCount: sendingCount, ReceivingCount: receivingCount}
}
func (sm *SnapManager) DeleteSnapshot(key SnapKey, snapshot Snapshot, checkEntry bool) bool {
sm.registryLock.Lock()
defer sm.registryLock.Unlock()
if checkEntry {
if e, ok := sm.registry[key]; ok {
if len(e) > 0 {
log.S().Infof("skip to delete %s since it's registered more than 1, registered entries %v",
snapshot.Path(), e)
return false
}
}
} else if _, ok := sm.registry[key]; ok {
log.S().Infof("skip to delete %s since it's registered.", snapshot.Path())
return false
}
snapshot.Delete()
return true
}
type SnapManagerBuilder struct {
maxTotalSize uint64
}
func (smb *SnapManagerBuilder) MaxTotalSize(v uint64) *SnapManagerBuilder {
smb.maxTotalSize = v
return smb
}
func (smb *SnapManagerBuilder) Build(path string, router *router) *SnapManager {
var maxTotalSize uint64 = math.MaxUint64
if smb.maxTotalSize > 0 {
maxTotalSize = smb.maxTotalSize
}
return &SnapManager{
base: path,
snapSize: new(int64),
registry: map[SnapKey][]SnapEntry{},
router: router,
limiter: NewInfLimiter(),
MaxTotalSize: maxTotalSize,
}
}