-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
sideload_disk.go
349 lines (321 loc) · 10.3 KB
/
sideload_disk.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
// Copyright 2017 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package logstore
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/fs"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/pebble/vfs"
"golang.org/x/time/rate"
)
var _ SideloadStorage = &DiskSideloadStorage{}
// DiskSideloadStorage implements SideloadStorage using the given storage
// engine.
//
// TODO(pavelkalinnikov): remove the interface, this type is the only impl.
type DiskSideloadStorage struct {
st *cluster.Settings
limiter *rate.Limiter
dir string
path []string
eng storage.Engine
}
func sideloadedPath(baseDir string, rangeID roachpb.RangeID) []string {
// Use one level of sharding to avoid too many items per directory. For
// example, ext3 and older ext4 support only 32k and 64k subdirectories
// per directory, respectively. Newer FS typically have no such limitation,
// but still.
//
// For example, r1828 will end up in baseDir/r1XXX/r1828.
return []string{
baseDir,
"sideloading",
fmt.Sprintf("r%dXXXX", rangeID/10000), // sharding
fmt.Sprintf("r%d", rangeID),
}
}
// NewDiskSideloadStorage creates a SideloadStorage for a given replica, stored
// in the specified engine.
func NewDiskSideloadStorage(
st *cluster.Settings,
rangeID roachpb.RangeID,
baseDir string,
limiter *rate.Limiter,
eng storage.Engine,
) *DiskSideloadStorage {
path := sideloadedPath(baseDir, rangeID)
return &DiskSideloadStorage{
dir: filepath.Join(path...),
path: path,
eng: eng,
st: st,
limiter: limiter,
}
}
// Dir implements SideloadStorage.
func (ss *DiskSideloadStorage) Dir() string {
return ss.dir
}
// Put implements SideloadStorage.
func (ss *DiskSideloadStorage) Put(
ctx context.Context, index kvpb.RaftIndex, term kvpb.RaftTerm, contents []byte,
) error {
filename := ss.filename(ctx, index, term)
// There's a chance the whole path is missing (for example after Clear()),
// in which case handle that transparently.
for {
// Use 0644 since that's what RocksDB uses:
// https://github.com/facebook/rocksdb/blob/56656e12d67d8a63f1e4c4214da9feeec2bd442b/env/env_posix.cc#L171
if err := kvserverbase.WriteFileSyncing(ctx, filename, contents, ss.eng, 0644, ss.st, ss.limiter); err == nil {
return nil
} else if !oserror.IsNotExist(err) {
return err
}
// Ensure that ss.dir exists. The filename() is placed directly in ss.dir,
// so the next loop iteration should succeed.
if err := mkdirAllAndSyncParents(ss.eng, ss.path[0], ss.path[1:], os.ModePerm); err != nil {
return err
}
continue
}
}
// Sync implements SideloadStorage.
func (ss *DiskSideloadStorage) Sync() error {
dir, err := ss.eng.OpenDir(ss.dir)
if err != nil {
return err
}
if err := dir.Sync(); err != nil {
_ = dir.Close()
return err
}
return dir.Close()
}
// Get implements SideloadStorage.
func (ss *DiskSideloadStorage) Get(
ctx context.Context, index kvpb.RaftIndex, term kvpb.RaftTerm,
) ([]byte, error) {
filename := ss.filename(ctx, index, term)
b, err := fs.ReadFile(ss.eng, filename)
if oserror.IsNotExist(err) {
return nil, errSideloadedFileNotFound
}
return b, err
}
// Filename implements SideloadStorage.
func (ss *DiskSideloadStorage) Filename(
ctx context.Context, index kvpb.RaftIndex, term kvpb.RaftTerm,
) (string, error) {
return ss.filename(ctx, index, term), nil
}
func (ss *DiskSideloadStorage) filename(
ctx context.Context, index kvpb.RaftIndex, term kvpb.RaftTerm,
) string {
return filepath.Join(ss.dir, fmt.Sprintf("i%d.t%d", index, term))
}
// Purge implements SideloadStorage.
func (ss *DiskSideloadStorage) Purge(
ctx context.Context, index kvpb.RaftIndex, term kvpb.RaftTerm,
) (int64, error) {
return ss.purgeFile(ctx, ss.filename(ctx, index, term))
}
func (ss *DiskSideloadStorage) fileSize(filename string) (int64, error) {
info, err := ss.eng.Stat(filename)
if err != nil {
if oserror.IsNotExist(err) {
return 0, errSideloadedFileNotFound
}
return 0, err
}
return info.Size(), nil
}
func (ss *DiskSideloadStorage) purgeFile(ctx context.Context, filename string) (int64, error) {
size, err := ss.fileSize(filename)
if err != nil {
return 0, err
}
if err := ss.eng.Remove(filename); err != nil {
if oserror.IsNotExist(err) {
return 0, errSideloadedFileNotFound
}
return 0, err
}
return size, nil
}
// Clear implements SideloadStorage.
func (ss *DiskSideloadStorage) Clear(_ context.Context) error {
return ss.eng.RemoveAll(ss.dir)
}
// TruncateTo implements SideloadStorage.
func (ss *DiskSideloadStorage) TruncateTo(
ctx context.Context, firstIndex kvpb.RaftIndex,
) (bytesFreed, bytesRetained int64, _ error) {
return ss.possiblyTruncateTo(ctx, 0, firstIndex, true /* doTruncate */)
}
// Helper for truncation or byte calculation for [from, to).
func (ss *DiskSideloadStorage) possiblyTruncateTo(
ctx context.Context, from kvpb.RaftIndex, to kvpb.RaftIndex, doTruncate bool,
) (bytesFreed, bytesRetained int64, _ error) {
deletedAll := true
if err := ss.forEach(ctx, func(index kvpb.RaftIndex, filename string) error {
if index >= to {
size, err := ss.fileSize(filename)
if err != nil {
return err
}
bytesRetained += size
deletedAll = false
return nil
}
if index < from {
return nil
}
// index is in [from, to)
var fileSize int64
var err error
if doTruncate {
fileSize, err = ss.purgeFile(ctx, filename)
} else {
fileSize, err = ss.fileSize(filename)
}
if err != nil {
return err
}
bytesFreed += fileSize
return nil
}); err != nil {
return 0, 0, err
}
if deletedAll && doTruncate {
// The directory may not exist, or it may exist and have been empty.
// Not worth trying to figure out which one, just try to delete.
err := ss.eng.Remove(ss.dir)
if err != nil && !oserror.IsNotExist(err) {
log.Infof(ctx, "unable to remove sideloaded dir %s: %v", ss.dir, err)
err = nil // handled
}
}
return bytesFreed, bytesRetained, nil
}
// BytesIfTruncatedFromTo implements SideloadStorage.
func (ss *DiskSideloadStorage) BytesIfTruncatedFromTo(
ctx context.Context, from kvpb.RaftIndex, to kvpb.RaftIndex,
) (freed, retained int64, _ error) {
return ss.possiblyTruncateTo(ctx, from, to, false /* doTruncate */)
}
func (ss *DiskSideloadStorage) forEach(
ctx context.Context, visit func(index kvpb.RaftIndex, filename string) error,
) error {
matches, err := ss.eng.List(ss.dir)
if oserror.IsNotExist(err) {
// Nothing to do.
return nil
}
if err != nil {
return err
}
for _, match := range matches {
// List returns a relative path, but we want to deal in absolute paths
// because we may pass this back to `eng.{Delete,Stat}`, etc, and those
// expect absolute paths.
match = filepath.Join(ss.dir, match)
base := filepath.Base(match)
// Extract `i<log-index>` prefix from file.
if len(base) < 1 || base[0] != 'i' {
continue
}
base = base[1:]
upToDot := strings.SplitN(base, ".", 2)
logIdx, err := strconv.ParseUint(upToDot[0], 10, 64)
if err != nil {
log.Infof(ctx, "unexpected file %s in sideloaded directory %s", match, ss.dir)
continue
}
if err := visit(kvpb.RaftIndex(logIdx), match); err != nil {
return errors.Wrapf(err, "matching pattern %q on dir %s", match, ss.dir)
}
}
return nil
}
// String lists the files in the storage without guaranteeing an ordering.
func (ss *DiskSideloadStorage) String() string {
var buf strings.Builder
var count int
if err := ss.forEach(context.Background(), func(_ kvpb.RaftIndex, filename string) error {
count++
_, _ = fmt.Fprintln(&buf, filename)
return nil
}); err != nil {
return err.Error()
}
fmt.Fprintf(&buf, "(%d files)\n", count)
return buf.String()
}
// mkdirAllAndSyncParents creates the given chain of directories, if any
// subdirectory is missing, and syncs parents of all the created directories.
// The base directory must already exist. The directories are created using the
// provided permissions mask, with the same semantics as in os.MkdirAll.
//
// For example, if dirs is [x, y, z], then this func creates all the missing
// subdirectories in base/x/y/z. If base is the lowest previously existing
// directory then base, x, and y are synced. If x existed too, then only x and y
// are synced. If y existed before then there are no syncs.
//
// NB: path syntax in the examples above may differ, because components of the
// path are combined using the provided filesystem interface.
func mkdirAllAndSyncParents(fs vfs.FS, base string, dirs []string, perm os.FileMode) error {
paths := append(make([]string, 0, len(dirs)+1), base)
for i, part := range dirs {
paths = append(paths, fs.PathJoin(paths[i], part))
}
// Find the lowest existing directory in the hierarchy.
existing := -1
for i := len(paths) - 1; i >= 0; i-- {
if _, err := fs.Stat(paths[i]); err == nil {
existing = i
break
} else if !oserror.IsNotExist(err) {
return errors.Wrapf(err, "could not get dir info: %s", paths[i])
}
}
if existing == -1 {
return errors.Newf("base dir does not exist: %s", base)
}
// Create the destination directory and any of its missing parents.
path := paths[len(paths)-1]
if err := fs.MkdirAll(path, perm); err != nil {
return errors.Wrapf(err, "could not create all directories: %s", path)
}
// Sync parent directories up to the lowest existing ancestor, included.
for i := len(paths) - 1; i > existing; i-- {
parent := paths[i-1]
if handle, err := fs.OpenDir(parent); err != nil {
return errors.Wrapf(err, "could not open parent dir: %s", parent)
} else if err := handle.Sync(); err != nil {
_ = handle.Close()
return errors.Wrapf(err, "could not sync parent dir: %s", parent)
} else if err := handle.Close(); err != nil {
return errors.Wrapf(err, "could not close parent dir: %s", parent)
}
}
return nil
}