mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* volume: never compact a volume tiered to remote storage A tiered volume's data backend is the remote object, but compaction reads the local .dat path. When tiering removed the local .dat, every vacuum of a tiered volume with garbage fails with "no such file or directory", and the master's sweep and the worker's vacuum task keep selecting it. When the local .dat was kept, the compaction succeeds against the stale copy and the commit reloads the volume to read the remote object (old layout) through the compacted index, so live needles stop reading. Mirror the Rust volume server (#11545): - CompactByIndex and CompactByVolumeData refuse a volume with a remote file before creating .cpd/.cpx ("volume N is tiered to remote storage, cannot compact"). - CommitCompact refuses under the data-file locks when the volume became tiered during the copy, and removes .cpd/.cpx. - Store.CheckCompactVolume reports no garbage for a tiered volume, so the master's vacuum and volume.vacuum do not select it. - The worker's vacuum detection skips a volume with a remote copy, as balance and EC detection already do. Tests (each fails on master): TestCompactRefusesTieredVolume, TestCommitCompactRefusesVolumeTieredDuringCopy (on master the commit succeeds and a surviving needle no longer reads), TestPickPrimaryReplicaSkipsTieredVolumes. * volume: skip tiered replicas in vacuum selection, keep their real ratio Reporting a zero garbage ratio for a tiered volume hid it from volume.tier.compact, whose preflight reads that ratio while the volume is still remote, and did not exclude it from a vacuum with a zero threshold. Report the real ratio again, as the Rust volume server does, and have the master's vacuum check skip a replica whose volume info names remote storage, whatever the threshold or request. When CommitCompact refuses a volume tiered during the copy, also close the temporary needle map and remove .cpldb: nothing else would, since no later vacuum selects the volume. The tiered-compaction test no longer depends on random needle sizes reaching a 0.3 garbage ratio. * volume tier: do not attach a copy of a .dat a compaction replaced The upload copies the .dat, then records the remote file in the .vif and switches the backend. A compaction commit in between swaps in a compacted .dat and index; the upload then served the old-layout remote object through the new index, so live needles stopped reading. CommitCompact's tiered check cannot see this: the volume is not tiered until the switch. AttachRemoteDatFile records the remote file and switches the backend under the data-file locks, and refuses when the backend is no longer the file that was copied. The upload then removes the unused remote copy. * volume tier: keep a committed .vif entry when only the dir fsync fails AttachRemoteDatFile rolled back the in-memory remote entry on any SaveVolumeInfo error. A NotCrashDurableError comes after the rename, so the .vif on disk already names the copy; with the entry gone, the upload handler deleted that object, and a reload would serve from a missing remote file. Keep the entry and switch to the copy as the .vif says, and still return the error so the caller keeps the local .dat. * vacuum worker: filter tiered replicas instead of skipping the volume A partially tiered volume is the leftover of an interrupted volume.tier.upload; skipping the whole volume left garbage on its local replicas unreclaimed. Per-replica filtering matches the master's batchVacuumVolumeCheck and is safe: a tiered replica refuses both compaction and commit. * filer: sync leveldb entry writes when the path rule asks for fsync The fsync storage rule only reached the volume upload; the metadata writes behind an acknowledged create, update or delete still went to the leveldb journal with Sync:false, so a power loss could roll back an acknowledged bucket or object entry. A write-side flag on the entry context carries the request: the filer sets it from the path's storage rule in CreateEntry, UpdateEntry, EnsureDirectoryEntry and DeleteEntryMetaAndData, and the HTTP write path sets it for an explicit ?fsync=true. The leveldb stores write with Sync:true when the flag is present. * volume: flush the .idx before acknowledging a durable write A write with fsync synced only the .dat: the index row written on publish stayed in the page cache, so a power loss could leave the needle's bytes durable with nothing indexing them. The durable paths now run one .idx sync after publish, before the requests complete — one per syncWrite and one per batch run, paired with the .dat sync, the same split the Rust volume server makes between flush_dat and flush_idx. A failed .idx sync cannot be rolled back, so it stops the volume taking writes and fails the requests instead of acknowledging an index entry that may not survive. --------- Co-authored-by: Javier de la Torre <jatorre@lakehousebox.com>
454 lines
12 KiB
Go
454 lines
12 KiB
Go
package leveldb
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/md5"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/syndtr/goleveldb/leveldb"
|
|
leveldb_errors "github.com/syndtr/goleveldb/leveldb/errors"
|
|
"github.com/syndtr/goleveldb/leveldb/filter"
|
|
"github.com/syndtr/goleveldb/leveldb/opt"
|
|
leveldb_util "github.com/syndtr/goleveldb/leveldb/util"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/filer"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
weed_util "github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
const (
|
|
DEFAULT = "_main"
|
|
)
|
|
|
|
func init() {
|
|
filer.Stores = append(filer.Stores, &LevelDB3Store{})
|
|
}
|
|
|
|
type LevelDB3Store struct {
|
|
dir string
|
|
dbs map[string]*leveldb.DB
|
|
dbsLock sync.RWMutex
|
|
ReadOnly bool
|
|
|
|
blockCacheSizeMB int
|
|
writeBufferSizeMB int
|
|
blockSizeKB int
|
|
compactionTableSizeMB int
|
|
}
|
|
|
|
func (store *LevelDB3Store) GetName() string {
|
|
return "leveldb3"
|
|
}
|
|
|
|
func (store *LevelDB3Store) Initialize(configuration weed_util.Configuration, prefix string) (err error) {
|
|
dir := configuration.GetString(prefix + "dir")
|
|
store.blockCacheSizeMB = configuration.GetInt(prefix + "block_cache_size_mb")
|
|
store.writeBufferSizeMB = configuration.GetInt(prefix + "write_buffer_size_mb")
|
|
store.blockSizeKB = configuration.GetInt(prefix + "block_size_kb")
|
|
store.compactionTableSizeMB = configuration.GetInt(prefix + "compaction_table_size_mb")
|
|
if err := store.validateSizeOptions(); err != nil {
|
|
return err
|
|
}
|
|
return store.initialize(dir)
|
|
}
|
|
|
|
// validateSizeOptions rejects sizes too large to convert to bytes without
|
|
// overflowing int on this platform.
|
|
func (store *LevelDB3Store) validateSizeOptions() error {
|
|
for name, kv := range map[string][2]int{
|
|
"block_cache_size_mb": {store.blockCacheSizeMB, 1 << 20},
|
|
"write_buffer_size_mb": {store.writeBufferSizeMB, 1 << 20},
|
|
"block_size_kb": {store.blockSizeKB, 1 << 10},
|
|
"compaction_table_size_mb": {store.compactionTableSizeMB, 1 << 20},
|
|
} {
|
|
if kv[0] > math.MaxInt/kv[1] {
|
|
return fmt.Errorf("leveldb3 option %s=%d overflows int", name, kv[0])
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (store *LevelDB3Store) buildOptions(name string) *opt.Options {
|
|
opts := &opt.Options{
|
|
BlockCacheCapacity: 32 * 1024 * 1024, // default value is 8MiB
|
|
WriteBuffer: 16 * 1024 * 1024, // default value is 4MiB
|
|
Filter: filter.NewBloomFilter(8),
|
|
ReadOnly: store.ReadOnly,
|
|
}
|
|
if name != DEFAULT {
|
|
opts.BlockCacheCapacity = 16 * 1024 * 1024 // default value is 8MiB
|
|
opts.WriteBuffer = 8 * 1024 * 1024 // default value is 4MiB
|
|
}
|
|
if store.blockCacheSizeMB > 0 {
|
|
opts.BlockCacheCapacity = store.blockCacheSizeMB * 1024 * 1024
|
|
}
|
|
if store.writeBufferSizeMB > 0 {
|
|
opts.WriteBuffer = store.writeBufferSizeMB * 1024 * 1024
|
|
}
|
|
if store.blockSizeKB > 0 {
|
|
opts.BlockSize = store.blockSizeKB * 1024
|
|
}
|
|
if store.compactionTableSizeMB > 0 {
|
|
opts.CompactionTableSize = store.compactionTableSizeMB * 1024 * 1024
|
|
}
|
|
return opts
|
|
}
|
|
|
|
func (store *LevelDB3Store) initialize(dir string) (err error) {
|
|
glog.Infof("filer store leveldb3 dir: %s", dir)
|
|
os.MkdirAll(dir, 0755)
|
|
if err := weed_util.TestFolderWritable(dir); err != nil {
|
|
return fmt.Errorf("Check Level Folder %s Writable: %s", dir, err)
|
|
}
|
|
store.dir = dir
|
|
|
|
db, loadDbErr := store.loadDB(DEFAULT)
|
|
if loadDbErr != nil {
|
|
return loadDbErr
|
|
}
|
|
store.dbs = make(map[string]*leveldb.DB)
|
|
store.dbs[DEFAULT] = db
|
|
|
|
return
|
|
}
|
|
|
|
func (store *LevelDB3Store) loadDB(name string) (*leveldb.DB, error) {
|
|
opts := store.buildOptions(name)
|
|
|
|
dbFolder := fmt.Sprintf("%s/%s", store.dir, name)
|
|
os.MkdirAll(dbFolder, 0755)
|
|
db, dbErr := leveldb.OpenFile(dbFolder, opts)
|
|
if leveldb_errors.IsCorrupted(dbErr) {
|
|
db, dbErr = leveldb.RecoverFile(dbFolder, opts)
|
|
}
|
|
if dbErr != nil {
|
|
glog.Errorf("filer store open dir %s: %v", dbFolder, dbErr)
|
|
return nil, dbErr
|
|
}
|
|
return db, nil
|
|
}
|
|
|
|
func (store *LevelDB3Store) findDB(fullpath weed_util.FullPath, isForChildren bool) (*leveldb.DB, string, weed_util.FullPath, error) {
|
|
|
|
store.dbsLock.RLock()
|
|
|
|
defaultDB := store.dbs[DEFAULT]
|
|
if !strings.HasPrefix(string(fullpath), "/buckets/") {
|
|
store.dbsLock.RUnlock()
|
|
return defaultDB, DEFAULT, fullpath, nil
|
|
}
|
|
|
|
// detect bucket
|
|
bucketAndObjectKey := string(fullpath)[len("/buckets/"):]
|
|
t := strings.Index(bucketAndObjectKey, "/")
|
|
if t < 0 && !isForChildren {
|
|
store.dbsLock.RUnlock()
|
|
return defaultDB, DEFAULT, fullpath, nil
|
|
}
|
|
bucket := bucketAndObjectKey
|
|
shortPath := weed_util.FullPath("/")
|
|
if t > 0 {
|
|
bucket = bucketAndObjectKey[:t]
|
|
shortPath = weed_util.FullPath(bucketAndObjectKey[t:])
|
|
}
|
|
|
|
// Dot-prefixed entries directly under /buckets (e.g. .system) are internal
|
|
// folders, not S3 buckets; keep them in the default DB by full path.
|
|
if strings.HasPrefix(bucket, ".") {
|
|
store.dbsLock.RUnlock()
|
|
return defaultDB, DEFAULT, fullpath, nil
|
|
}
|
|
|
|
if db, found := store.dbs[bucket]; found {
|
|
store.dbsLock.RUnlock()
|
|
return db, bucket, shortPath, nil
|
|
}
|
|
|
|
store.dbsLock.RUnlock()
|
|
|
|
db, err := store.createDB(bucket)
|
|
|
|
return db, bucket, shortPath, err
|
|
}
|
|
|
|
func (store *LevelDB3Store) createDB(bucket string) (*leveldb.DB, error) {
|
|
|
|
store.dbsLock.Lock()
|
|
defer store.dbsLock.Unlock()
|
|
|
|
// double check after getting the write lock
|
|
if db, found := store.dbs[bucket]; found {
|
|
return db, nil
|
|
}
|
|
|
|
// create db
|
|
db, err := store.loadDB(bucket)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
store.dbs[bucket] = db
|
|
|
|
return db, nil
|
|
}
|
|
|
|
func (store *LevelDB3Store) closeDB(bucket string) {
|
|
|
|
store.dbsLock.Lock()
|
|
defer store.dbsLock.Unlock()
|
|
|
|
if db, found := store.dbs[bucket]; found {
|
|
db.Close()
|
|
delete(store.dbs, bucket)
|
|
}
|
|
|
|
}
|
|
|
|
func (store *LevelDB3Store) BeginTransaction(ctx context.Context) (context.Context, error) {
|
|
return ctx, nil
|
|
}
|
|
func (store *LevelDB3Store) CommitTransaction(ctx context.Context) error {
|
|
return nil
|
|
}
|
|
func (store *LevelDB3Store) RollbackTransaction(ctx context.Context) error {
|
|
return nil
|
|
}
|
|
|
|
var syncWriteOptions = &opt.WriteOptions{Sync: true}
|
|
|
|
func writeOptions(ctx context.Context) *opt.WriteOptions {
|
|
if filer.SyncWrite(ctx) {
|
|
return syncWriteOptions
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (store *LevelDB3Store) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
|
|
|
|
db, _, shortPath, err := store.findDB(entry.FullPath, false)
|
|
if err != nil {
|
|
return fmt.Errorf("findDB %s : %v", entry.FullPath, err)
|
|
}
|
|
|
|
dir, name := shortPath.DirAndName()
|
|
key := genKey(dir, name)
|
|
|
|
value, err := entry.EncodeAttributesAndChunks()
|
|
if err != nil {
|
|
return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
|
|
}
|
|
|
|
if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
|
|
value = weed_util.MaybeGzipData(value)
|
|
}
|
|
|
|
err = db.Put(key, value, writeOptions(ctx))
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
|
|
}
|
|
|
|
// println("saved", entry.FullPath, "chunks", len(entry.GetChunks()))
|
|
|
|
return nil
|
|
}
|
|
|
|
func (store *LevelDB3Store) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
|
|
|
|
return store.InsertEntry(ctx, entry)
|
|
}
|
|
|
|
func (store *LevelDB3Store) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
|
|
|
|
db, _, shortPath, err := store.findDB(fullpath, false)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("findDB %s : %v", fullpath, err)
|
|
}
|
|
|
|
dir, name := shortPath.DirAndName()
|
|
key := genKey(dir, name)
|
|
|
|
data, err := db.Get(key, nil)
|
|
|
|
if err == leveldb.ErrNotFound {
|
|
return nil, filer_pb.ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get %s : %v", fullpath, err)
|
|
}
|
|
|
|
entry = &filer.Entry{
|
|
FullPath: fullpath,
|
|
}
|
|
err = entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(data))
|
|
if err != nil {
|
|
return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
|
|
}
|
|
|
|
// println("read", entry.FullPath, "chunks", len(entry.GetChunks()), "data", len(data), string(data))
|
|
|
|
return entry, nil
|
|
}
|
|
|
|
func (store *LevelDB3Store) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
|
|
|
|
db, _, shortPath, err := store.findDB(fullpath, false)
|
|
if err != nil {
|
|
return fmt.Errorf("findDB %s : %v", fullpath, err)
|
|
}
|
|
|
|
dir, name := shortPath.DirAndName()
|
|
key := genKey(dir, name)
|
|
|
|
err = db.Delete(key, writeOptions(ctx))
|
|
if err != nil {
|
|
return fmt.Errorf("delete %s : %v", fullpath, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (store *LevelDB3Store) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath) (err error) {
|
|
|
|
db, bucket, shortPath, err := store.findDB(fullpath, true)
|
|
if err != nil {
|
|
return fmt.Errorf("findDB %s : %v", fullpath, err)
|
|
}
|
|
|
|
if bucket != DEFAULT && shortPath == "/" {
|
|
store.closeDB(bucket)
|
|
if bucket != "" { // just to make sure
|
|
os.RemoveAll(store.dir + "/" + bucket)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
directoryPrefix := genDirectoryKeyPrefix(shortPath, "")
|
|
|
|
batch := new(leveldb.Batch)
|
|
|
|
iter := db.NewIterator(&leveldb_util.Range{Start: directoryPrefix}, nil)
|
|
for iter.Next() {
|
|
key := iter.Key()
|
|
if !bytes.HasPrefix(key, directoryPrefix) {
|
|
break
|
|
}
|
|
fileName := getNameFromKey(key)
|
|
if fileName == "" {
|
|
continue
|
|
}
|
|
batch.Delete(append(directoryPrefix, []byte(fileName)...))
|
|
}
|
|
iter.Release()
|
|
|
|
err = db.Write(batch, writeOptions(ctx))
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("delete %s : %v", fullpath, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (store *LevelDB3Store) ListDirectoryEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
|
|
return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", eachEntryFunc)
|
|
}
|
|
|
|
func (store *LevelDB3Store) ListDirectoryPrefixedEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
|
|
|
|
db, _, shortPath, err := store.findDB(dirPath, true)
|
|
if err != nil {
|
|
return lastFileName, fmt.Errorf("findDB %s : %v", dirPath, err)
|
|
}
|
|
|
|
directoryPrefix := genDirectoryKeyPrefix(shortPath, prefix)
|
|
lastFileStart := directoryPrefix
|
|
if startFileName != "" {
|
|
lastFileStart = genDirectoryKeyPrefix(shortPath, startFileName)
|
|
}
|
|
|
|
iter := db.NewIterator(&leveldb_util.Range{Start: lastFileStart}, nil)
|
|
for iter.Next() {
|
|
key := iter.Key()
|
|
if !bytes.HasPrefix(key, directoryPrefix) {
|
|
break
|
|
}
|
|
fileName := getNameFromKey(key)
|
|
if fileName == "" {
|
|
continue
|
|
}
|
|
if fileName == startFileName && !includeStartFile {
|
|
continue
|
|
}
|
|
limit--
|
|
if limit < 0 {
|
|
break
|
|
}
|
|
lastFileName = fileName
|
|
entry := &filer.Entry{
|
|
FullPath: weed_util.NewFullPath(string(dirPath), fileName),
|
|
}
|
|
|
|
// println("list", entry.FullPath, "chunks", len(entry.GetChunks()))
|
|
if decodeErr := entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(iter.Value())); decodeErr != nil {
|
|
err = decodeErr
|
|
glog.V(0).InfofCtx(ctx, "list %s : %v", entry.FullPath, err)
|
|
break
|
|
}
|
|
|
|
resEachEntryFunc, resEachEntryFuncErr := eachEntryFunc(entry)
|
|
if resEachEntryFuncErr != nil {
|
|
err = fmt.Errorf("failed to process eachEntryFunc: %w", resEachEntryFuncErr)
|
|
break
|
|
}
|
|
|
|
if !resEachEntryFunc {
|
|
break
|
|
}
|
|
}
|
|
iter.Release()
|
|
|
|
return lastFileName, err
|
|
}
|
|
|
|
func genKey(dirPath, fileName string) (key []byte) {
|
|
key = hashToBytes(dirPath)
|
|
key = append(key, []byte(fileName)...)
|
|
return key
|
|
}
|
|
|
|
func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string) (keyPrefix []byte) {
|
|
keyPrefix = hashToBytes(string(fullpath))
|
|
if len(startFileName) > 0 {
|
|
keyPrefix = append(keyPrefix, []byte(startFileName)...)
|
|
}
|
|
return keyPrefix
|
|
}
|
|
|
|
func getNameFromKey(key []byte) string {
|
|
|
|
return string(key[md5.Size:])
|
|
|
|
}
|
|
|
|
// hash directory
|
|
func hashToBytes(dir string) []byte {
|
|
h := md5.New()
|
|
io.WriteString(h, dir)
|
|
b := h.Sum(nil)
|
|
return b
|
|
}
|
|
|
|
func (store *LevelDB3Store) Shutdown() {
|
|
for _, db := range store.dbs {
|
|
db.Close()
|
|
}
|
|
}
|