mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-26 22:27:05 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8fea19669 | ||
|
|
b0c7de186d | ||
|
|
1a7afe7e6a | ||
|
|
f2723c1bc8 | ||
|
|
ba984a4e29 | ||
|
|
446e476a11 | ||
|
|
ea26a98753 | ||
|
|
d15682b4a1 | ||
|
|
c0ee78d2fa | ||
|
|
cd9b89ba55 | ||
|
|
e2c741f76f | ||
|
|
2a0925590c | ||
|
|
3984c3962f | ||
|
|
baa6bdf4d4 | ||
|
|
3eda8d6dfc | ||
|
|
ab201c2798 | ||
|
|
75de7002ff | ||
|
|
9d4bdfcfdf | ||
|
|
1b8094ef75 | ||
|
|
12a8f5294d | ||
|
|
e60b2117c3 | ||
|
|
89a62e8007 |
No files matched your search
@@ -1,4 +1,4 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
version: 1.96
|
||||
version: 1.99
|
||||
@@ -4,7 +4,7 @@ global:
|
||||
registry: ""
|
||||
repository: ""
|
||||
imageName: chrislusf/seaweedfs
|
||||
imageTag: "1.96"
|
||||
imageTag: "1.99"
|
||||
imagePullPolicy: IfNotPresent
|
||||
imagePullSecrets: imagepullsecret
|
||||
restartPolicy: Always
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package main
|
||||
|
||||
// copied from https://github.com/apoorvam/aws-s3-multipart-upload
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
)
|
||||
|
||||
const (
|
||||
maxPartSize = int64(5 * 1024 * 1024)
|
||||
maxRetries = 3
|
||||
awsAccessKeyID = "Your access key"
|
||||
awsSecretAccessKey = "Your secret key"
|
||||
awsBucketRegion = "S3 bucket region"
|
||||
awsBucketName = "newBucket"
|
||||
)
|
||||
|
||||
var (
|
||||
filename = flag.String("f", "", "the file name")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
creds := credentials.NewStaticCredentials(awsAccessKeyID, awsSecretAccessKey, "")
|
||||
_, err := creds.Get()
|
||||
if err != nil {
|
||||
fmt.Printf("bad credentials: %s", err)
|
||||
}
|
||||
cfg := aws.NewConfig().WithRegion(awsBucketRegion).WithCredentials(creds).WithDisableSSL(true).WithEndpoint("localhost:8333")
|
||||
svc := s3.New(session.New(), cfg)
|
||||
|
||||
file, err := os.Open(*filename)
|
||||
if err != nil {
|
||||
fmt.Printf("err opening file: %s", err)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
fileInfo, _ := file.Stat()
|
||||
size := fileInfo.Size()
|
||||
buffer := make([]byte, size)
|
||||
fileType := http.DetectContentType(buffer)
|
||||
file.Read(buffer)
|
||||
|
||||
path := "/media/" + file.Name()
|
||||
input := &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(awsBucketName),
|
||||
Key: aws.String(path),
|
||||
ContentType: aws.String(fileType),
|
||||
}
|
||||
|
||||
resp, err := svc.CreateMultipartUpload(input)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
return
|
||||
}
|
||||
fmt.Println("Created multipart upload request")
|
||||
|
||||
var curr, partLength int64
|
||||
var remaining = size
|
||||
var completedParts []*s3.CompletedPart
|
||||
partNumber := 1
|
||||
for curr = 0; remaining != 0; curr += partLength {
|
||||
if remaining < maxPartSize {
|
||||
partLength = remaining
|
||||
} else {
|
||||
partLength = maxPartSize
|
||||
}
|
||||
completedPart, err := uploadPart(svc, resp, buffer[curr:curr+partLength], partNumber)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
err := abortMultipartUpload(svc, resp)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
remaining -= partLength
|
||||
partNumber++
|
||||
completedParts = append(completedParts, completedPart)
|
||||
}
|
||||
|
||||
// list parts
|
||||
parts, err := svc.ListParts(&s3.ListPartsInput{
|
||||
Bucket: input.Bucket,
|
||||
Key: input.Key,
|
||||
MaxParts: nil,
|
||||
PartNumberMarker: nil,
|
||||
RequestPayer: nil,
|
||||
UploadId: resp.UploadId,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
return
|
||||
}
|
||||
fmt.Printf("list parts: %d\n", len(parts.Parts))
|
||||
for i, part := range parts.Parts {
|
||||
fmt.Printf("part %d: %v\n", i, part)
|
||||
}
|
||||
|
||||
|
||||
completeResponse, err := completeMultipartUpload(svc, resp, completedParts)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Successfully uploaded file: %s\n", completeResponse.String())
|
||||
}
|
||||
|
||||
func completeMultipartUpload(svc *s3.S3, resp *s3.CreateMultipartUploadOutput, completedParts []*s3.CompletedPart) (*s3.CompleteMultipartUploadOutput, error) {
|
||||
completeInput := &s3.CompleteMultipartUploadInput{
|
||||
Bucket: resp.Bucket,
|
||||
Key: resp.Key,
|
||||
UploadId: resp.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{
|
||||
Parts: completedParts,
|
||||
},
|
||||
}
|
||||
return svc.CompleteMultipartUpload(completeInput)
|
||||
}
|
||||
|
||||
func uploadPart(svc *s3.S3, resp *s3.CreateMultipartUploadOutput, fileBytes []byte, partNumber int) (*s3.CompletedPart, error) {
|
||||
tryNum := 1
|
||||
partInput := &s3.UploadPartInput{
|
||||
Body: bytes.NewReader(fileBytes),
|
||||
Bucket: resp.Bucket,
|
||||
Key: resp.Key,
|
||||
PartNumber: aws.Int64(int64(partNumber)),
|
||||
UploadId: resp.UploadId,
|
||||
ContentLength: aws.Int64(int64(len(fileBytes))),
|
||||
}
|
||||
|
||||
for tryNum <= maxRetries {
|
||||
uploadResult, err := svc.UploadPart(partInput)
|
||||
if err != nil {
|
||||
if tryNum == maxRetries {
|
||||
if aerr, ok := err.(awserr.Error); ok {
|
||||
return nil, aerr
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("Retrying to upload part #%v\n", partNumber)
|
||||
tryNum++
|
||||
} else {
|
||||
fmt.Printf("Uploaded part #%v\n", partNumber)
|
||||
return &s3.CompletedPart{
|
||||
ETag: uploadResult.ETag,
|
||||
PartNumber: aws.Int64(int64(partNumber)),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func abortMultipartUpload(svc *s3.S3, resp *s3.CreateMultipartUploadOutput) error {
|
||||
fmt.Println("Aborting multipart upload for UploadId#" + *resp.UploadId)
|
||||
abortInput := &s3.AbortMultipartUploadInput{
|
||||
Bucket: resp.Bucket,
|
||||
Key: resp.Key,
|
||||
UploadId: resp.UploadId,
|
||||
}
|
||||
_, err := svc.AbortMultipartUpload(abortInput)
|
||||
return err
|
||||
}
|
||||
@@ -10,6 +10,10 @@ clean:
|
||||
go clean $(SOURCE_DIR)
|
||||
rm -f $(BINARY)
|
||||
|
||||
debug_shell:
|
||||
go build -gcflags="all=-N -l"
|
||||
dlv --listen=:2345 --headless=true --api-version=2 --accept-multiclient exec weed -- shell
|
||||
|
||||
debug_mount:
|
||||
go build -gcflags="all=-N -l"
|
||||
dlv --listen=:2345 --headless=true --api-version=2 --accept-multiclient exec weed -- mount -dir=~/tmp/mm
|
||||
@@ -17,3 +21,7 @@ debug_mount:
|
||||
debug_server:
|
||||
go build -gcflags="all=-N -l"
|
||||
dlv --listen=:2345 --headless=true --api-version=2 --accept-multiclient exec weed -- server -dir=/Volumes/mobile_disk/99 -filer -volume.port=8343 -s3 -volume.max=0
|
||||
|
||||
debug_volume:
|
||||
go build -gcflags="all=-N -l"
|
||||
dlv --listen=:2345 --headless=true --api-version=2 --accept-multiclient exec weed -- volume -dir=/Volumes/mobile_disk/100 -port 8564 -max=30
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
defaultFnFormat = `{{.Mime}}/{{.Id}}:{{.Name}}`
|
||||
defaultFnFormat = `{{.Id}}_{{.Name}}{{.Ext}}`
|
||||
timeFormat = "2006-01-02T15:04:05"
|
||||
)
|
||||
|
||||
@@ -56,7 +56,7 @@ func init() {
|
||||
|
||||
var (
|
||||
output = cmdExport.Flag.String("o", "", "output tar file name, must ends with .tar, or just a \"-\" for stdout")
|
||||
format = cmdExport.Flag.String("fileNameFormat", defaultFnFormat, "filename formatted with {{.Mime}} {{.Id}} {{.Name}} {{.Ext}}")
|
||||
format = cmdExport.Flag.String("fileNameFormat", defaultFnFormat, "filename formatted with {{.Id}} {{.Name}} {{.Ext}}")
|
||||
newer = cmdExport.Flag.String("newer", "", "export only files newer than this time, default is all files. Must be specified in RFC3339 without timezone, e.g. 2006-01-02T15:04:05")
|
||||
showDeleted = cmdExport.Flag.Bool("deleted", false, "export deleted files. only applies if -o is not specified")
|
||||
limit = cmdExport.Flag.Int("limit", 0, "only show first n entries if specified")
|
||||
@@ -111,7 +111,7 @@ func (scanner *VolumeFileScanner4Export) VisitNeedle(n *needle.Needle, offset in
|
||||
nv, ok := needleMap.Get(n.Id)
|
||||
glog.V(3).Infof("key %d offset %d size %d disk_size %d compressed %v ok %v nv %+v",
|
||||
n.Id, offset, n.Size, n.DiskSize(scanner.version), n.IsCompressed(), ok, nv)
|
||||
if ok && nv.Size.IsValid() && nv.Offset.ToAcutalOffset() == offset {
|
||||
if *showDeleted && n.Size > 0 || ok && nv.Size.IsValid() && nv.Offset.ToAcutalOffset() == offset {
|
||||
if newerThanUnix >= 0 && n.HasLastModifiedDate() && n.LastModified < uint64(newerThanUnix) {
|
||||
glog.V(3).Infof("Skipping this file, as it's old enough: LastModified %d vs %d",
|
||||
n.LastModified, newerThanUnix)
|
||||
|
||||
@@ -36,7 +36,7 @@ type SyncOptions struct {
|
||||
}
|
||||
|
||||
var (
|
||||
syncOptions SyncOptions
|
||||
syncOptions SyncOptions
|
||||
syncCpuProfile *string
|
||||
syncMemProfile *string
|
||||
)
|
||||
|
||||
+3
-9
@@ -30,7 +30,6 @@ var (
|
||||
fixVolumePath = cmdFix.Flag.String("dir", ".", "data directory to store files")
|
||||
fixVolumeCollection = cmdFix.Flag.String("collection", "", "the volume collection name")
|
||||
fixVolumeId = cmdFix.Flag.Int("volumeId", -1, "a volume id. The volume should already exist in the dir. The volume index file should not exist.")
|
||||
fixIncludeDeleted = cmdFix.Flag.Bool("includeDeleted", false, "include deleted entries in the index file")
|
||||
)
|
||||
|
||||
type VolumeFileScanner4Fix struct {
|
||||
@@ -51,14 +50,9 @@ func (scanner *VolumeFileScanner4Fix) VisitNeedle(n *needle.Needle, offset int64
|
||||
glog.V(2).Infof("key %d offset %d size %d disk_size %d compressed %v", n.Id, offset, n.Size, n.DiskSize(scanner.version), n.IsCompressed())
|
||||
if n.Size.IsValid() {
|
||||
pe := scanner.nm.Set(n.Id, types.ToOffset(offset), n.Size)
|
||||
glog.V(2).Infof("saved %s %d bytes with error %v", n.Id.String(), n.Size, pe)
|
||||
glog.V(2).Infof("saved %d with error %v", n.Size, pe)
|
||||
} else {
|
||||
if val, found := scanner.nm.Get(n.Id); *fixIncludeDeleted && found && val.Size > 0 {
|
||||
pe := scanner.nm.Set(n.Id, val.Offset, -val.Size)
|
||||
glog.V(2).Infof("update deleted %s %d bytes with error %v", n.Id.String(), -val.Size, pe)
|
||||
return nil
|
||||
}
|
||||
glog.V(1).Infof("skipping deleted file %s size %d ...", n.Id.String(), n.Size)
|
||||
glog.V(2).Infof("skipping deleted file ...")
|
||||
return scanner.nm.Delete(n.Id)
|
||||
}
|
||||
return nil
|
||||
@@ -89,7 +83,7 @@ func runFix(cmd *Command, args []string) bool {
|
||||
os.Remove(indexFileName)
|
||||
}
|
||||
|
||||
if err := nm.SaveToIdx(indexFileName, *fixIncludeDeleted); err != nil {
|
||||
if err := nm.SaveToIdx(indexFileName); err != nil {
|
||||
glog.Fatalf("save to .idx File: %v", err)
|
||||
os.Remove(indexFileName)
|
||||
}
|
||||
|
||||
@@ -391,7 +391,7 @@ default = "localhost:8888" # used by maintenance scripts if the scripts needs
|
||||
|
||||
|
||||
[master.sequencer]
|
||||
type = "memory" # Choose [memory|etcd] type for storing the file id sequence
|
||||
type = "raft" # Choose [raft|etcd] type for storing the file id sequence
|
||||
# when sequencer.type = etcd, set listen client urls of etcd cluster that store file id sequence
|
||||
# example : http://127.0.0.1:2379,http://127.0.0.1:2389
|
||||
sequencer_etcd_urls = "http://127.0.0.1:2379"
|
||||
|
||||
@@ -98,7 +98,7 @@ func init() {
|
||||
serverOptions.v.compactionMBPerSecond = cmdServer.Flag.Int("volume.compactionMBps", 0, "limit compaction speed in mega bytes per second")
|
||||
serverOptions.v.fileSizeLimitMB = cmdServer.Flag.Int("volume.fileSizeLimitMB", 1024, "limit file size to avoid out of memory")
|
||||
serverOptions.v.publicUrl = cmdServer.Flag.String("volume.publicUrl", "", "publicly accessible address")
|
||||
serverOptions.v.preStopSeconds = cmdServer.Flag.Int("volume.preStopSeconds", 30, "number of seconds between stop send heartbeats and stop volume server")
|
||||
serverOptions.v.preStopSeconds = cmdServer.Flag.Int("volume.preStopSeconds", 10, "number of seconds between stop send heartbeats and stop volume server")
|
||||
serverOptions.v.pprof = &False
|
||||
|
||||
s3Options.port = cmdServer.Flag.Int("s3.port", 8333, "s3 server http listen port")
|
||||
|
||||
@@ -67,7 +67,7 @@ func init() {
|
||||
v.publicUrl = cmdVolume.Flag.String("publicUrl", "", "Publicly accessible address")
|
||||
v.bindIp = cmdVolume.Flag.String("ip.bind", "0.0.0.0", "ip address to bind to")
|
||||
v.masters = cmdVolume.Flag.String("mserver", "localhost:9333", "comma-separated master servers")
|
||||
v.preStopSeconds = cmdVolume.Flag.Int("preStopSeconds", 30, "number of seconds between stop send heartbeats and stop volume server")
|
||||
v.preStopSeconds = cmdVolume.Flag.Int("preStopSeconds", 10, "number of seconds between stop send heartbeats and stop volume server")
|
||||
// v.pulseSeconds = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than or equal to the master's setting")
|
||||
v.idleConnectionTimeout = cmdVolume.Flag.Int("idleTimeout", 30, "connection idle seconds")
|
||||
v.dataCenter = cmdVolume.Flag.String("dataCenter", "", "current volume server's data center name")
|
||||
|
||||
@@ -72,14 +72,16 @@ func (store *AbstractSqlStore) InsertEntry(ctx context.Context, entry *filer.Ent
|
||||
}
|
||||
|
||||
res, err := store.getTxOrDB(ctx).ExecContext(ctx, store.SqlInsert, util.HashStringToLong(dir), name, dir, meta)
|
||||
if err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "duplicate") {
|
||||
return fmt.Errorf("kv insert: %s", err)
|
||||
}
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "duplicate") {
|
||||
return fmt.Errorf("kv insert: %s", err)
|
||||
}
|
||||
|
||||
// now the insert failed possibly due to duplication constraints
|
||||
glog.V(1).Infof("insert %s falls back to update: %s", entry.FullPath, err)
|
||||
glog.V(1).Infof("insert %s falls back to update: %v", entry.FullPath, err)
|
||||
|
||||
res, err = store.getTxOrDB(ctx).ExecContext(ctx, store.SqlUpdate, meta, util.HashStringToLong(dir), name, dir)
|
||||
if err != nil {
|
||||
@@ -175,7 +177,7 @@ func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context,
|
||||
sqlText = store.SqlListInclusive
|
||||
}
|
||||
|
||||
rows, err := store.getTxOrDB(ctx).QueryContext(ctx, sqlText, util.HashStringToLong(string(fullpath)), startFileName, string(fullpath), prefix, limit)
|
||||
rows, err := store.getTxOrDB(ctx).QueryContext(ctx, sqlText, util.HashStringToLong(string(fullpath)), startFileName, string(fullpath), prefix+"%", limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list %s : %v", fullpath, err)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ func (store *EtcdStore) KvPut(ctx context.Context, key []byte, value []byte) (er
|
||||
|
||||
func (store *EtcdStore) KvGet(ctx context.Context, key []byte) (value []byte, err error) {
|
||||
|
||||
resp, err := store.client.Get(ctx, string(key), nil)
|
||||
resp, err := store.client.Get(ctx, string(key))
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("kv get: %v", err)
|
||||
|
||||
@@ -87,7 +87,7 @@ func (ma *MetaAggregator) subscribeToOneFiler(f *Filer, self string, peer string
|
||||
if err := ma.updateOffset(f, peer, peerSignature, event.TsNs); err == nil {
|
||||
if event.TsNs < time.Now().Add(-2*time.Minute).UnixNano() {
|
||||
glog.V(0).Infof("sync with %s progressed to: %v %0.2f/sec", peer, time.Unix(0, event.TsNs), float64(counter)/60.0)
|
||||
} else if !synced{
|
||||
} else if !synced {
|
||||
synced = true
|
||||
glog.V(0).Infof("synced with %s", peer)
|
||||
}
|
||||
@@ -162,13 +162,13 @@ func (ma *MetaAggregator) readFilerStoreSignature(peer string) (sig int32, err e
|
||||
return
|
||||
}
|
||||
|
||||
const(
|
||||
const (
|
||||
MetaOffsetPrefix = "Meta"
|
||||
)
|
||||
|
||||
func (ma *MetaAggregator) readOffset(f *Filer, peer string, peerSignature int32) (lastTsNs int64, err error) {
|
||||
|
||||
key := []byte(MetaOffsetPrefix+"xxxx")
|
||||
key := []byte(MetaOffsetPrefix + "xxxx")
|
||||
util.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))
|
||||
|
||||
value, err := f.Store.KvGet(context.Background(), key)
|
||||
@@ -191,7 +191,7 @@ func (ma *MetaAggregator) readOffset(f *Filer, peer string, peerSignature int32)
|
||||
|
||||
func (ma *MetaAggregator) updateOffset(f *Filer, peer string, peerSignature int32, lastTsNs int64) (err error) {
|
||||
|
||||
key := []byte(MetaOffsetPrefix+"xxxx")
|
||||
key := []byte(MetaOffsetPrefix + "xxxx")
|
||||
util.Uint32toBytes(key[len(MetaOffsetPrefix):], uint32(peerSignature))
|
||||
|
||||
value := make([]byte, 8)
|
||||
|
||||
@@ -47,8 +47,8 @@ func (store *MysqlStore) initialize(user, password, hostname string, port int, d
|
||||
store.SqlFind = "SELECT meta FROM filemeta WHERE dirhash=? AND name=? AND directory=?"
|
||||
store.SqlDelete = "DELETE FROM filemeta WHERE dirhash=? AND name=? AND directory=?"
|
||||
store.SqlDeleteFolderChildren = "DELETE FROM filemeta WHERE dirhash=? AND directory=?"
|
||||
store.SqlListExclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>? AND directory=? AND name like CONCAT(?,'%') ORDER BY NAME ASC LIMIT ?"
|
||||
store.SqlListInclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>=? AND directory=? AND name like CONCAT(?,'%') ORDER BY NAME ASC LIMIT ?"
|
||||
store.SqlListExclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>? AND directory=? AND name like ? ORDER BY NAME ASC LIMIT ?"
|
||||
store.SqlListInclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=? AND name>=? AND directory=? AND name like ? ORDER BY NAME ASC LIMIT ?"
|
||||
|
||||
sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
|
||||
if interpolateParams {
|
||||
|
||||
@@ -46,8 +46,8 @@ func (store *PostgresStore) initialize(user, password, hostname string, port int
|
||||
store.SqlFind = "SELECT meta FROM filemeta WHERE dirhash=$1 AND name=$2 AND directory=$3"
|
||||
store.SqlDelete = "DELETE FROM filemeta WHERE dirhash=$1 AND name=$2 AND directory=$3"
|
||||
store.SqlDeleteFolderChildren = "DELETE FROM filemeta WHERE dirhash=$1 AND directory=$2"
|
||||
store.SqlListExclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=$1 AND name>$2 AND directory=$3 AND name like CONCAT($4,'%')ORDER BY NAME ASC LIMIT $5"
|
||||
store.SqlListInclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=$1 AND name>=$2 AND directory=$3 AND name like CONCAT($4,'%') ORDER BY NAME ASC LIMIT $5"
|
||||
store.SqlListExclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=$1 AND name>$2 AND directory=$3 AND name like $4 ORDER BY NAME ASC LIMIT $5"
|
||||
store.SqlListInclusive = "SELECT NAME, meta FROM filemeta WHERE dirhash=$1 AND name>=$2 AND directory=$3 AND name like $4 ORDER BY NAME ASC LIMIT $5"
|
||||
|
||||
sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, hostname, port, user, sslmode)
|
||||
if password != "" {
|
||||
|
||||
@@ -84,4 +84,3 @@ func ReadFilerSignature(grpcDialOption grpc.DialOption, filer string) (filerSign
|
||||
}
|
||||
return filerSignature, nil
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ func (s3a *S3ApiServer) completeMultipartUpload(input *s3.CompleteMultipartUploa
|
||||
|
||||
uploadDirectory := s3a.genUploadsFolder(*input.Bucket) + "/" + *input.UploadId
|
||||
|
||||
entries, err := s3a.list(uploadDirectory, "", "", false, 0)
|
||||
entries, _, err := s3a.list(uploadDirectory, "", "", false, 0)
|
||||
if err != nil || len(entries) == 0 {
|
||||
glog.Errorf("completeMultipartUpload %s %s error: %v, entries:%d", *input.Bucket, *input.UploadId, err, len(entries))
|
||||
return nil, ErrNoSuchUpload
|
||||
@@ -140,35 +140,50 @@ func (s3a *S3ApiServer) abortMultipartUpload(input *s3.AbortMultipartUploadInput
|
||||
|
||||
type ListMultipartUploadsResult struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListMultipartUploadsResult"`
|
||||
s3.ListMultipartUploadsOutput
|
||||
|
||||
// copied from s3.ListMultipartUploadsOutput, the Uploads is not converting to <Upload></Upload>
|
||||
Bucket *string `type:"string"`
|
||||
Delimiter *string `type:"string"`
|
||||
EncodingType *string `type:"string" enum:"EncodingType"`
|
||||
IsTruncated *bool `type:"boolean"`
|
||||
KeyMarker *string `type:"string"`
|
||||
MaxUploads *int64 `type:"integer"`
|
||||
NextKeyMarker *string `type:"string"`
|
||||
NextUploadIdMarker *string `type:"string"`
|
||||
Prefix *string `type:"string"`
|
||||
UploadIdMarker *string `type:"string"`
|
||||
Upload []*s3.MultipartUpload `locationName:"Upload" type:"list" flattened:"true"`
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput) (output *ListMultipartUploadsResult, code ErrorCode) {
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html
|
||||
|
||||
output = &ListMultipartUploadsResult{
|
||||
ListMultipartUploadsOutput: s3.ListMultipartUploadsOutput{
|
||||
Bucket: input.Bucket,
|
||||
Delimiter: input.Delimiter,
|
||||
EncodingType: input.EncodingType,
|
||||
KeyMarker: input.KeyMarker,
|
||||
MaxUploads: input.MaxUploads,
|
||||
Prefix: input.Prefix,
|
||||
},
|
||||
Bucket: input.Bucket,
|
||||
Delimiter: input.Delimiter,
|
||||
EncodingType: input.EncodingType,
|
||||
KeyMarker: input.KeyMarker,
|
||||
MaxUploads: input.MaxUploads,
|
||||
Prefix: input.Prefix,
|
||||
}
|
||||
|
||||
entries, err := s3a.list(s3a.genUploadsFolder(*input.Bucket), *input.Prefix, *input.KeyMarker, true, uint32(*input.MaxUploads))
|
||||
entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket), *input.Prefix, *input.KeyMarker, true, uint32(*input.MaxUploads))
|
||||
if err != nil {
|
||||
glog.Errorf("listMultipartUploads %s error: %v", *input.Bucket, err)
|
||||
return
|
||||
}
|
||||
output.IsTruncated = aws.Bool(!isLast)
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.Extended != nil {
|
||||
key := entry.Extended["key"]
|
||||
output.Uploads = append(output.Uploads, &s3.MultipartUpload{
|
||||
output.Upload = append(output.Upload, &s3.MultipartUpload{
|
||||
Key: objectKey(aws.String(string(key))),
|
||||
UploadId: aws.String(entry.Name),
|
||||
})
|
||||
if !isLast {
|
||||
output.NextUploadIdMarker = aws.String(entry.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,26 +192,39 @@ func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput
|
||||
|
||||
type ListPartsResult struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListPartsResult"`
|
||||
s3.ListPartsOutput
|
||||
|
||||
// copied from s3.ListPartsOutput, the Parts is not converting to <Part></Part>
|
||||
Bucket *string `type:"string"`
|
||||
IsTruncated *bool `type:"boolean"`
|
||||
Key *string `min:"1" type:"string"`
|
||||
MaxParts *int64 `type:"integer"`
|
||||
NextPartNumberMarker *int64 `type:"integer"`
|
||||
PartNumberMarker *int64 `type:"integer"`
|
||||
Part []*s3.Part `locationName:"Part" type:"list" flattened:"true"`
|
||||
StorageClass *string `type:"string" enum:"StorageClass"`
|
||||
UploadId *string `type:"string"`
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListPartsResult, code ErrorCode) {
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html
|
||||
|
||||
output = &ListPartsResult{
|
||||
ListPartsOutput: s3.ListPartsOutput{
|
||||
Bucket: input.Bucket,
|
||||
Key: objectKey(input.Key),
|
||||
UploadId: input.UploadId,
|
||||
MaxParts: input.MaxParts, // the maximum number of parts to return.
|
||||
PartNumberMarker: input.PartNumberMarker, // the part number starts after this, exclusive
|
||||
},
|
||||
Bucket: input.Bucket,
|
||||
Key: objectKey(input.Key),
|
||||
UploadId: input.UploadId,
|
||||
MaxParts: input.MaxParts, // the maximum number of parts to return.
|
||||
PartNumberMarker: input.PartNumberMarker, // the part number starts after this, exclusive
|
||||
StorageClass: aws.String("STANDARD"),
|
||||
}
|
||||
|
||||
entries, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d.part", *input.PartNumberMarker), false, uint32(*input.MaxParts))
|
||||
entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d.part", *input.PartNumberMarker), false, uint32(*input.MaxParts))
|
||||
if err != nil {
|
||||
glog.Errorf("listObjectParts %s %s error: %v", *input.Bucket, *input.UploadId, err)
|
||||
return nil, ErrNoSuchUpload
|
||||
}
|
||||
|
||||
output.IsTruncated = aws.Bool(!isLast)
|
||||
|
||||
for _, entry := range entries {
|
||||
if strings.HasSuffix(entry.Name, ".part") && !entry.IsDirectory {
|
||||
partNumberString := entry.Name[:len(entry.Name)-len(".part")]
|
||||
@@ -205,12 +233,15 @@ func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListP
|
||||
glog.Errorf("listObjectParts %s %s parse %s: %v", *input.Bucket, *input.UploadId, entry.Name, err)
|
||||
continue
|
||||
}
|
||||
output.Parts = append(output.Parts, &s3.Part{
|
||||
output.Part = append(output.Part, &s3.Part{
|
||||
PartNumber: aws.Int64(int64(partNumber)),
|
||||
LastModified: aws.Time(time.Unix(entry.Attributes.Mtime, 0).UTC()),
|
||||
Size: aws.Int64(int64(filer.FileSize(entry))),
|
||||
ETag: aws.String("\"" + filer.ETag(entry) + "\""),
|
||||
})
|
||||
if !isLast {
|
||||
output.NextPartNumberMarker = aws.Int64(int64(partNumber))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestInitiateMultipartUploadResult(t *testing.T) {
|
||||
@@ -24,3 +25,25 @@ func TestInitiateMultipartUploadResult(t *testing.T) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestListPartsResult(t *testing.T) {
|
||||
|
||||
expected := `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ListPartsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Part><ETag>"12345678"</ETag><LastModified>1970-01-01T00:00:00Z</LastModified><PartNumber>1</PartNumber><Size>123</Size></Part></ListPartsResult>`
|
||||
response := &ListPartsResult{
|
||||
Part: []*s3.Part{
|
||||
{
|
||||
PartNumber: aws.Int64(int64(1)),
|
||||
LastModified: aws.Time(time.Unix(0, 0).UTC()),
|
||||
Size: aws.Int64(int64(123)),
|
||||
ETag: aws.String("\"12345678\""),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
encoded := string(encodeResponse(response))
|
||||
if encoded != expected {
|
||||
t.Errorf("unexpected output: %s\nexpecting:%s", encoded, expected)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,10 +21,13 @@ func (s3a *S3ApiServer) mkFile(parentDirectoryPath string, fileName string, chun
|
||||
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) list(parentDirectoryPath, prefix, startFrom string, inclusive bool, limit uint32) (entries []*filer_pb.Entry, err error) {
|
||||
func (s3a *S3ApiServer) list(parentDirectoryPath, prefix, startFrom string, inclusive bool, limit uint32) (entries []*filer_pb.Entry, isLast bool, err error) {
|
||||
|
||||
err = filer_pb.List(s3a, parentDirectoryPath, prefix, func(entry *filer_pb.Entry, isLast bool) error {
|
||||
err = filer_pb.List(s3a, parentDirectoryPath, prefix, func(entry *filer_pb.Entry, isLastEntry bool) error {
|
||||
entries = append(entries, entry)
|
||||
if isLastEntry {
|
||||
isLast = true
|
||||
}
|
||||
return nil
|
||||
}, startFrom, inclusive, limit)
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ func (s3a *S3ApiServer) ListBucketsHandler(w http.ResponseWriter, r *http.Reques
|
||||
|
||||
var response ListAllMyBucketsResult
|
||||
|
||||
entries, err := s3a.list(s3a.option.BucketsPath, "", "", false, math.MaxInt32)
|
||||
entries, _, err := s3a.list(s3a.option.BucketsPath, "", "", false, math.MaxInt32)
|
||||
|
||||
if err != nil {
|
||||
writeErrorResponse(w, ErrInternalError, r.URL)
|
||||
|
||||
@@ -253,6 +253,10 @@ func mountEcShards(grpcDialOption grpc.DialOption, collection string, volumeId n
|
||||
})
|
||||
}
|
||||
|
||||
func divide(total, n int) float64 {
|
||||
return float64(total) / float64(n)
|
||||
}
|
||||
|
||||
func ceilDivide(total, n int) int {
|
||||
return int(math.Ceil(float64(total) / float64(n)))
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage/super_block"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
@@ -39,14 +40,15 @@ func (c *commandVolumeBalance) Help() string {
|
||||
}
|
||||
|
||||
func balanceWritableVolumes(){
|
||||
idealWritableVolumes = totalWritableVolumes / numVolumeServers
|
||||
idealWritableVolumeRatio = totalWritableVolumes / totalNumberOfMaxVolumes
|
||||
for hasMovedOneVolume {
|
||||
sort all volume servers ordered by the number of local writable volumes
|
||||
pick the volume server A with the lowest number of writable volumes x
|
||||
pick the volume server B with the highest number of writable volumes y
|
||||
if y > idealWritableVolumes and x +1 <= idealWritableVolumes {
|
||||
if B has a writable volume id v that A does not have {
|
||||
move writable volume v from A to B
|
||||
sort all volume servers ordered by the localWritableVolumeRatio = localWritableVolumes to localVolumeMax
|
||||
pick the volume server B with the highest localWritableVolumeRatio y
|
||||
for any the volume server A with the number of writable volumes x + 1 <= idealWritableVolumeRatio * localVolumeMax {
|
||||
if y > localWritableVolumeRatio {
|
||||
if B has a writable volume id v that A does not have, and satisfy v replication requirements {
|
||||
move writable volume v from A to B
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,38 +83,33 @@ func (c *commandVolumeBalance) Do(args []string, commandEnv *CommandEnv, writer
|
||||
return err
|
||||
}
|
||||
|
||||
typeToNodes := collectVolumeServersByType(resp.TopologyInfo, *dc)
|
||||
volumeServers := collectVolumeServersByDc(resp.TopologyInfo, *dc)
|
||||
volumeReplicas, _ := collectVolumeReplicaLocations(resp)
|
||||
|
||||
for maxVolumeCount, volumeServers := range typeToNodes {
|
||||
if len(volumeServers) < 2 {
|
||||
fmt.Printf("only 1 node is configured max %d volumes, skipping balancing\n", maxVolumeCount)
|
||||
continue
|
||||
if *collection == "EACH_COLLECTION" {
|
||||
collections, err := ListCollectionNames(commandEnv, true, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *collection == "EACH_COLLECTION" {
|
||||
collections, err := ListCollectionNames(commandEnv, true, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range collections {
|
||||
if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if *collection == "ALL_COLLECTIONS" {
|
||||
if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, "ALL_COLLECTIONS", *applyBalancing); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
|
||||
for _, c := range collections {
|
||||
if err = balanceVolumeServers(commandEnv, volumeReplicas, volumeServers, resp.VolumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
} else if *collection == "ALL_COLLECTIONS" {
|
||||
if err = balanceVolumeServers(commandEnv, volumeReplicas, volumeServers, resp.VolumeSizeLimitMb*1024*1024, "ALL_COLLECTIONS", *applyBalancing); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err = balanceVolumeServers(commandEnv, volumeReplicas, volumeServers, resp.VolumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func balanceVolumeServers(commandEnv *CommandEnv, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
|
||||
func balanceVolumeServers(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, volumeSizeLimit uint64, collection string, applyBalancing bool) error {
|
||||
|
||||
// balance writable volumes
|
||||
for _, n := range nodes {
|
||||
@@ -125,7 +122,7 @@ func balanceVolumeServers(commandEnv *CommandEnv, nodes []*Node, volumeSizeLimit
|
||||
return !v.ReadOnly && v.Size < volumeSizeLimit
|
||||
})
|
||||
}
|
||||
if err := balanceSelectedVolume(commandEnv, nodes, sortWritableVolumes, applyBalancing); err != nil {
|
||||
if err := balanceSelectedVolume(commandEnv, volumeReplicas, nodes, sortWritableVolumes, applyBalancing); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -140,22 +137,21 @@ func balanceVolumeServers(commandEnv *CommandEnv, nodes []*Node, volumeSizeLimit
|
||||
return v.ReadOnly || v.Size >= volumeSizeLimit
|
||||
})
|
||||
}
|
||||
if err := balanceSelectedVolume(commandEnv, nodes, sortReadOnlyVolumes, applyBalancing); err != nil {
|
||||
if err := balanceSelectedVolume(commandEnv, volumeReplicas, nodes, sortReadOnlyVolumes, applyBalancing); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func collectVolumeServersByType(t *master_pb.TopologyInfo, selectedDataCenter string) (typeToNodes map[uint64][]*Node) {
|
||||
typeToNodes = make(map[uint64][]*Node)
|
||||
func collectVolumeServersByDc(t *master_pb.TopologyInfo, selectedDataCenter string) (nodes []*Node) {
|
||||
for _, dc := range t.DataCenterInfos {
|
||||
if selectedDataCenter != "" && dc.Id != selectedDataCenter {
|
||||
continue
|
||||
}
|
||||
for _, r := range dc.RackInfos {
|
||||
for _, dn := range r.DataNodeInfos {
|
||||
typeToNodes[dn.MaxVolumeCount] = append(typeToNodes[dn.MaxVolumeCount], &Node{
|
||||
nodes = append(nodes, &Node{
|
||||
info: dn,
|
||||
dc: dc.Id,
|
||||
rack: r.Id,
|
||||
@@ -173,6 +169,23 @@ type Node struct {
|
||||
rack string
|
||||
}
|
||||
|
||||
func (n *Node) localVolumeRatio() float64 {
|
||||
return divide(len(n.selectedVolumes), int(n.info.MaxVolumeCount))
|
||||
}
|
||||
|
||||
func (n *Node) localVolumeNextRatio() float64 {
|
||||
return divide(len(n.selectedVolumes)+1, int(n.info.MaxVolumeCount))
|
||||
}
|
||||
|
||||
func (n *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
|
||||
n.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
|
||||
for _, v := range n.info.VolumeInfos {
|
||||
if fn(v) {
|
||||
n.selectedVolumes[v.Id] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {
|
||||
sort.Slice(volumes, func(i, j int) bool {
|
||||
return volumes[i].Size < volumes[j].Size
|
||||
@@ -185,56 +198,71 @@ func sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {
|
||||
})
|
||||
}
|
||||
|
||||
func balanceSelectedVolume(commandEnv *CommandEnv, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) error {
|
||||
selectedVolumeCount := 0
|
||||
func balanceSelectedVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) (err error) {
|
||||
selectedVolumeCount, volumeMaxCount := 0, 0
|
||||
for _, dn := range nodes {
|
||||
selectedVolumeCount += len(dn.selectedVolumes)
|
||||
volumeMaxCount += int(dn.info.MaxVolumeCount)
|
||||
}
|
||||
|
||||
idealSelectedVolumes := ceilDivide(selectedVolumeCount, len(nodes))
|
||||
idealVolumeRatio := divide(selectedVolumeCount, volumeMaxCount)
|
||||
|
||||
hasMove := true
|
||||
hasMoved := true
|
||||
|
||||
for hasMove {
|
||||
hasMove = false
|
||||
for hasMoved {
|
||||
hasMoved = false
|
||||
sort.Slice(nodes, func(i, j int) bool {
|
||||
// TODO sort by free volume slots???
|
||||
return len(nodes[i].selectedVolumes) < len(nodes[j].selectedVolumes)
|
||||
return nodes[i].localVolumeRatio() < nodes[j].localVolumeRatio()
|
||||
})
|
||||
emptyNode, fullNode := nodes[0], nodes[len(nodes)-1]
|
||||
if len(fullNode.selectedVolumes) > idealSelectedVolumes && len(emptyNode.selectedVolumes)+1 <= idealSelectedVolumes {
|
||||
|
||||
// sort the volumes to move
|
||||
var candidateVolumes []*master_pb.VolumeInformationMessage
|
||||
for _, v := range fullNode.selectedVolumes {
|
||||
candidateVolumes = append(candidateVolumes, v)
|
||||
fullNode := nodes[len(nodes)-1]
|
||||
var candidateVolumes []*master_pb.VolumeInformationMessage
|
||||
for _, v := range fullNode.selectedVolumes {
|
||||
candidateVolumes = append(candidateVolumes, v)
|
||||
}
|
||||
sortCandidatesFn(candidateVolumes)
|
||||
|
||||
for i := 0; i < len(nodes)-1; i++ {
|
||||
emptyNode := nodes[i]
|
||||
if !(fullNode.localVolumeRatio() > idealVolumeRatio && emptyNode.localVolumeNextRatio() <= idealVolumeRatio) {
|
||||
// no more volume servers with empty slots
|
||||
break
|
||||
}
|
||||
sortCandidatesFn(candidateVolumes)
|
||||
|
||||
for _, v := range candidateVolumes {
|
||||
if v.ReplicaPlacement > 0 {
|
||||
if fullNode.dc != emptyNode.dc && fullNode.rack != emptyNode.rack {
|
||||
// TODO this logic is too simple, but should work most of the time
|
||||
// Need a correct algorithm to handle all different cases
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, found := emptyNode.selectedVolumes[v.Id]; !found {
|
||||
if err := moveVolume(commandEnv, v, fullNode, emptyNode, applyBalancing); err == nil {
|
||||
delete(fullNode.selectedVolumes, v.Id)
|
||||
emptyNode.selectedVolumes[v.Id] = v
|
||||
hasMove = true
|
||||
break
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
hasMoved, err = attemptToMoveOneVolume(commandEnv, volumeReplicas, fullNode, candidateVolumes, emptyNode, applyBalancing)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if hasMoved {
|
||||
// moved one volume
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func attemptToMoveOneVolume(commandEnv *CommandEnv, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, candidateVolumes []*master_pb.VolumeInformationMessage, emptyNode *Node, applyBalancing bool) (hasMoved bool, err error) {
|
||||
|
||||
for _, v := range candidateVolumes {
|
||||
if v.ReplicaPlacement > 0 {
|
||||
replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(v.ReplicaPlacement))
|
||||
if !isGoodMove(replicaPlacement, volumeReplicas[v.Id], fullNode, emptyNode) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, found := emptyNode.selectedVolumes[v.Id]; !found {
|
||||
if err = moveVolume(commandEnv, v, fullNode, emptyNode, applyBalancing); err == nil {
|
||||
adjustAfterMove(v, volumeReplicas, fullNode, emptyNode)
|
||||
hasMoved = true
|
||||
break
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyBalancing bool) error {
|
||||
collectionPrefix := v.Collection + "_"
|
||||
if v.Collection == "" {
|
||||
@@ -247,11 +275,56 @@ func moveVolume(commandEnv *CommandEnv, v *master_pb.VolumeInformationMessage, f
|
||||
return nil
|
||||
}
|
||||
|
||||
func (node *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {
|
||||
node.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)
|
||||
for _, v := range node.info.VolumeInfos {
|
||||
if fn(v) {
|
||||
node.selectedVolumes[v.Id] = v
|
||||
func isGoodMove(placement *super_block.ReplicaPlacement, existingReplicas []*VolumeReplica, sourceNode, targetNode *Node) bool {
|
||||
for _, replica := range existingReplicas {
|
||||
if replica.location.dataNode.Id == targetNode.info.Id &&
|
||||
replica.location.rack == targetNode.rack &&
|
||||
replica.location.dc == targetNode.dc {
|
||||
// never move to existing nodes
|
||||
return false
|
||||
}
|
||||
}
|
||||
dcs, racks := make(map[string]bool), make(map[string]int)
|
||||
for _, replica := range existingReplicas {
|
||||
if replica.location.dataNode.Id != sourceNode.info.Id {
|
||||
dcs[replica.location.DataCenter()] = true
|
||||
racks[replica.location.Rack()]++
|
||||
}
|
||||
}
|
||||
|
||||
dcs[targetNode.dc] = true
|
||||
racks[fmt.Sprintf("%s %s", targetNode.dc, targetNode.rack)]++
|
||||
|
||||
if len(dcs) > placement.DiffDataCenterCount+1 {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(racks) > placement.DiffRackCount+placement.DiffDataCenterCount+1 {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, sameRackCount := range racks {
|
||||
if sameRackCount > placement.SameRackCount+1 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
}
|
||||
|
||||
func adjustAfterMove(v *master_pb.VolumeInformationMessage, volumeReplicas map[uint32][]*VolumeReplica, fullNode *Node, emptyNode *Node) {
|
||||
delete(fullNode.selectedVolumes, v.Id)
|
||||
emptyNode.selectedVolumes[v.Id] = v
|
||||
existingReplicas := volumeReplicas[v.Id]
|
||||
for _, replica := range existingReplicas {
|
||||
if replica.location.dataNode.Id == fullNode.info.Id &&
|
||||
replica.location.rack == fullNode.rack &&
|
||||
replica.location.dc == fullNode.dc {
|
||||
replica.location.dc = emptyNode.dc
|
||||
replica.location.rack = emptyNode.rack
|
||||
replica.location.dataNode = emptyNode.info
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package shell
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage/super_block"
|
||||
)
|
||||
|
||||
type testMoveCase struct {
|
||||
name string
|
||||
replication string
|
||||
replicas []*VolumeReplica
|
||||
sourceLocation location
|
||||
targetLocation location
|
||||
expected bool
|
||||
}
|
||||
|
||||
func TestIsGoodMove(t *testing.T) {
|
||||
|
||||
var tests = []testMoveCase{
|
||||
|
||||
{
|
||||
name: "test 100 move to spread into proper data centers",
|
||||
replication: "100",
|
||||
replicas: []*VolumeReplica{
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn1"}},
|
||||
},
|
||||
{
|
||||
location: &location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
},
|
||||
},
|
||||
sourceLocation: location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
targetLocation: location{"dc2", "r2", &master_pb.DataNodeInfo{Id: "dn3"}},
|
||||
expected: true,
|
||||
},
|
||||
|
||||
{
|
||||
name: "test move to the same node",
|
||||
replication: "001",
|
||||
replicas: []*VolumeReplica{
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn1"}},
|
||||
},
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
},
|
||||
},
|
||||
sourceLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
targetLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
expected: false,
|
||||
},
|
||||
|
||||
{
|
||||
name: "test move to the same rack, but existing node",
|
||||
replication: "001",
|
||||
replicas: []*VolumeReplica{
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn1"}},
|
||||
},
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
},
|
||||
},
|
||||
sourceLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
targetLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn1"}},
|
||||
expected: false,
|
||||
},
|
||||
|
||||
{
|
||||
name: "test move to the same rack, a new node",
|
||||
replication: "001",
|
||||
replicas: []*VolumeReplica{
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn1"}},
|
||||
},
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
},
|
||||
},
|
||||
sourceLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
targetLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn3"}},
|
||||
expected: true,
|
||||
},
|
||||
|
||||
{
|
||||
name: "test 010 move all to the same rack",
|
||||
replication: "010",
|
||||
replicas: []*VolumeReplica{
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn1"}},
|
||||
},
|
||||
{
|
||||
location: &location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
},
|
||||
},
|
||||
sourceLocation: location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
targetLocation: location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn3"}},
|
||||
expected: false,
|
||||
},
|
||||
|
||||
{
|
||||
name: "test 010 move to spread racks",
|
||||
replication: "010",
|
||||
replicas: []*VolumeReplica{
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn1"}},
|
||||
},
|
||||
{
|
||||
location: &location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
},
|
||||
},
|
||||
sourceLocation: location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
targetLocation: location{"dc1", "r3", &master_pb.DataNodeInfo{Id: "dn3"}},
|
||||
expected: true,
|
||||
},
|
||||
|
||||
{
|
||||
name: "test 010 move to spread racks",
|
||||
replication: "010",
|
||||
replicas: []*VolumeReplica{
|
||||
{
|
||||
location: &location{"dc1", "r1", &master_pb.DataNodeInfo{Id: "dn1"}},
|
||||
},
|
||||
{
|
||||
location: &location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
},
|
||||
},
|
||||
sourceLocation: location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn2"}},
|
||||
targetLocation: location{"dc1", "r2", &master_pb.DataNodeInfo{Id: "dn3"}},
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
replicaPlacement, _ := super_block.NewReplicaPlacementFromString(tt.replication)
|
||||
println("replication:", tt.replication, "expected", tt.expected, "name:", tt.name)
|
||||
sourceNode := &Node{
|
||||
info: tt.sourceLocation.dataNode,
|
||||
dc: tt.sourceLocation.dc,
|
||||
rack: tt.sourceLocation.rack,
|
||||
}
|
||||
targetNode := &Node{
|
||||
info: tt.targetLocation.dataNode,
|
||||
dc: tt.targetLocation.dc,
|
||||
rack: tt.targetLocation.rack,
|
||||
}
|
||||
if isGoodMove(replicaPlacement, tt.replicas, sourceNode, targetNode) != tt.expected {
|
||||
t.Errorf("%s: expect %v move from %v to %s, replication:%v",
|
||||
tt.name, tt.expected, tt.sourceLocation, tt.targetLocation, tt.replication)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -66,18 +66,7 @@ func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv,
|
||||
|
||||
// find all volumes that needs replication
|
||||
// collect all data nodes
|
||||
volumeReplicas := make(map[uint32][]*VolumeReplica)
|
||||
var allLocations []location
|
||||
eachDataNode(resp.TopologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
loc := newLocation(dc, string(rack), dn)
|
||||
for _, v := range dn.VolumeInfos {
|
||||
volumeReplicas[v.Id] = append(volumeReplicas[v.Id], &VolumeReplica{
|
||||
location: &loc,
|
||||
info: v,
|
||||
})
|
||||
}
|
||||
allLocations = append(allLocations, loc)
|
||||
})
|
||||
volumeReplicas, allLocations := collectVolumeReplicaLocations(resp)
|
||||
|
||||
if len(allLocations) == 0 {
|
||||
return fmt.Errorf("no data nodes at all")
|
||||
@@ -111,6 +100,22 @@ func (c *commandVolumeFixReplication) Do(args []string, commandEnv *CommandEnv,
|
||||
|
||||
}
|
||||
|
||||
func collectVolumeReplicaLocations(resp *master_pb.VolumeListResponse) (map[uint32][]*VolumeReplica, []location) {
|
||||
volumeReplicas := make(map[uint32][]*VolumeReplica)
|
||||
var allLocations []location
|
||||
eachDataNode(resp.TopologyInfo, func(dc string, rack RackId, dn *master_pb.DataNodeInfo) {
|
||||
loc := newLocation(dc, string(rack), dn)
|
||||
for _, v := range dn.VolumeInfos {
|
||||
volumeReplicas[v.Id] = append(volumeReplicas[v.Id], &VolumeReplica{
|
||||
location: &loc,
|
||||
info: v,
|
||||
})
|
||||
}
|
||||
allLocations = append(allLocations, loc)
|
||||
})
|
||||
return volumeReplicas, allLocations
|
||||
}
|
||||
|
||||
func (c *commandVolumeFixReplication) fixOverReplicatedVolumes(commandEnv *CommandEnv, writer io.Writer, takeAction bool, overReplicatedVolumeIds []uint32, volumeReplicas map[uint32][]*VolumeReplica, allLocations []location) error {
|
||||
for _, vid := range overReplicatedVolumeIds {
|
||||
replicas := volumeReplicas[vid]
|
||||
|
||||
@@ -21,7 +21,7 @@ const (
|
||||
type NeedleMapper interface {
|
||||
Put(key NeedleId, offset Offset, size Size) error
|
||||
Get(key NeedleId) (element *needle_map.NeedleValue, ok bool)
|
||||
Delete(key NeedleId) error
|
||||
Delete(key NeedleId, offset Offset) error
|
||||
Close()
|
||||
Destroy() error
|
||||
ContentSize() uint64
|
||||
|
||||
@@ -80,7 +80,7 @@ func (cm *MemDb) AscendingVisit(visit func(NeedleValue) error) (ret error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (cm *MemDb) SaveToIdx(idxName string, includeDeleted bool) (ret error) {
|
||||
func (cm *MemDb) SaveToIdx(idxName string) (ret error) {
|
||||
idxFile, err := os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -88,10 +88,7 @@ func (cm *MemDb) SaveToIdx(idxName string, includeDeleted bool) (ret error) {
|
||||
defer idxFile.Close()
|
||||
|
||||
return cm.AscendingVisit(func(value NeedleValue) error {
|
||||
if value.Offset.IsZero() {
|
||||
return nil
|
||||
}
|
||||
if !includeDeleted && value.Size.IsDeleted() {
|
||||
if value.Offset.IsZero() || value.Size.IsDeleted() {
|
||||
return nil
|
||||
}
|
||||
_, err := idxFile.Write(value.ToBytes())
|
||||
|
||||
@@ -74,7 +74,7 @@ func generateLevelDbFile(dbFileName string, indexFile *os.File) error {
|
||||
}
|
||||
defer db.Close()
|
||||
return idx.WalkIndexFile(indexFile, func(key NeedleId, offset Offset, size Size) error {
|
||||
if !offset.IsZero() {
|
||||
if !offset.IsZero() && size.IsValid() {
|
||||
levelDbWrite(db, key, offset, size)
|
||||
} else {
|
||||
levelDbDelete(db, key)
|
||||
@@ -123,7 +123,7 @@ func levelDbDelete(db *leveldb.DB, key NeedleId) error {
|
||||
return db.Delete(bytes, nil)
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) Delete(key NeedleId) error {
|
||||
func (m *LevelDbNeedleMap) Delete(key NeedleId, offset Offset) error {
|
||||
oldNeedle, found := m.Get(key)
|
||||
if !found || oldNeedle.Size.IsDeleted() {
|
||||
return nil
|
||||
@@ -131,7 +131,7 @@ func (m *LevelDbNeedleMap) Delete(key NeedleId) error {
|
||||
m.logDelete(oldNeedle.Size)
|
||||
|
||||
// write to index file first
|
||||
if err := m.appendToIndexFile(key, oldNeedle.Offset, -oldNeedle.Size); err != nil {
|
||||
if err := m.appendToIndexFile(key, offset, TombstoneFileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -30,18 +30,13 @@ func LoadCompactNeedleMap(file *os.File) (*NeedleMap, error) {
|
||||
func doLoading(file *os.File, nm *NeedleMap) (*NeedleMap, error) {
|
||||
e := idx.WalkIndexFile(file, func(key NeedleId, offset Offset, size Size) error {
|
||||
nm.MaybeSetMaxFileKey(key)
|
||||
if !offset.IsZero() {
|
||||
if !offset.IsZero() && size.IsValid() {
|
||||
nm.FileCounter++
|
||||
nm.FileByteCounter = nm.FileByteCounter + uint64(size)
|
||||
|
||||
oldOffset, oldSize := nm.m.Set(NeedleId(key), offset, size)
|
||||
if !oldOffset.IsZero() && oldSize.IsValid() {
|
||||
nm.DeletionCounter++
|
||||
nm.DeletionByteCounter = nm.DeletionByteCounter + uint64(oldSize)
|
||||
} else if size < 0 {
|
||||
// deletion
|
||||
nm.DeletionCounter++
|
||||
nm.DeletionByteCounter = nm.DeletionByteCounter + uint64(-size)
|
||||
}
|
||||
} else {
|
||||
oldSize := nm.m.Delete(NeedleId(key))
|
||||
@@ -59,18 +54,14 @@ func (nm *NeedleMap) Put(key NeedleId, offset Offset, size Size) error {
|
||||
nm.logPut(key, oldSize, size)
|
||||
return nm.appendToIndexFile(key, offset, size)
|
||||
}
|
||||
func (nm *NeedleMap) Get(key NeedleId) (existingValue *needle_map.NeedleValue, ok bool) {
|
||||
existingValue, ok = nm.m.Get(NeedleId(key))
|
||||
func (nm *NeedleMap) Get(key NeedleId) (element *needle_map.NeedleValue, ok bool) {
|
||||
element, ok = nm.m.Get(NeedleId(key))
|
||||
return
|
||||
}
|
||||
func (nm *NeedleMap) Delete(key NeedleId) error {
|
||||
existingValue, ok := nm.m.Get(NeedleId(key))
|
||||
if !ok || existingValue.Size.IsDeleted(){
|
||||
return nil
|
||||
}
|
||||
func (nm *NeedleMap) Delete(key NeedleId, offset Offset) error {
|
||||
deletedBytes := nm.m.Delete(NeedleId(key))
|
||||
nm.logDelete(deletedBytes)
|
||||
return nm.appendToIndexFile(key, existingValue.Offset, -existingValue.Size)
|
||||
return nm.appendToIndexFile(key, offset, TombstoneFileSize)
|
||||
}
|
||||
func (nm *NeedleMap) Close() {
|
||||
indexFileName := nm.indexFile.Name()
|
||||
|
||||
@@ -17,7 +17,7 @@ func TestFastLoadingNeedleMapMetrics(t *testing.T) {
|
||||
for i := 0; i < 10000; i++ {
|
||||
nm.Put(Uint64ToNeedleId(uint64(i+1)), Uint32ToOffset(uint32(0)), Size(1))
|
||||
if rand.Float32() < 0.2 {
|
||||
nm.Delete(Uint64ToNeedleId(uint64(rand.Int63n(int64(i))+1)))
|
||||
nm.Delete(Uint64ToNeedleId(uint64(rand.Int63n(int64(i))+1)), Uint32ToOffset(uint32(0)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,9 +69,9 @@ func (m *SortedFileNeedleMap) Put(key NeedleId, offset Offset, size Size) error
|
||||
return os.ErrInvalid
|
||||
}
|
||||
|
||||
func (m *SortedFileNeedleMap) Delete(key NeedleId) error {
|
||||
func (m *SortedFileNeedleMap) Delete(key NeedleId, offset Offset) error {
|
||||
|
||||
offset, size, err := erasure_coding.SearchNeedleFromSortedIndex(m.dbFile, m.dbFileSize, key, nil)
|
||||
_, size, err := erasure_coding.SearchNeedleFromSortedIndex(m.dbFile, m.dbFileSize, key, nil)
|
||||
|
||||
if err != nil {
|
||||
if err == erasure_coding.NotFoundError {
|
||||
@@ -85,7 +85,7 @@ func (m *SortedFileNeedleMap) Delete(key NeedleId) error {
|
||||
}
|
||||
|
||||
// write to index file first
|
||||
if err := m.appendToIndexFile(key, offset, -size); err != nil {
|
||||
if err := m.appendToIndexFile(key, offset, TombstoneFileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _, err = erasure_coding.SearchNeedleFromSortedIndex(m.dbFile, m.dbFileSize, key, erasure_coding.MarkNeedleDeleted)
|
||||
|
||||
@@ -256,5 +256,5 @@ func (scanner *VolumeFileScanner4GenIdx) VisitNeedle(n *needle.Needle, offset in
|
||||
if n.Size > 0 && n.Size.IsValid() {
|
||||
return scanner.v.nm.Put(n.Id, ToOffset(offset), n.Size)
|
||||
}
|
||||
return scanner.v.nm.Delete(n.Id)
|
||||
return scanner.v.nm.Delete(n.Id, ToOffset(offset))
|
||||
}
|
||||
@@ -27,11 +27,15 @@ func CheckVolumeDataIntegrity(v *Volume, indexFile *os.File) (lastAppendAtNs uin
|
||||
if offset.IsZero() {
|
||||
return 0, nil
|
||||
}
|
||||
if size.IsDeleted() {
|
||||
size = 0
|
||||
}
|
||||
if lastAppendAtNs, e = verifyNeedleIntegrity(v.DataBackend, v.Version(), offset.ToAcutalOffset(), key, size); e != nil {
|
||||
return lastAppendAtNs, fmt.Errorf("verifyNeedleIntegrity %s failed: %v", indexFile.Name(), e)
|
||||
if size < 0 {
|
||||
// read the deletion entry
|
||||
if lastAppendAtNs, e = verifyDeletedNeedleIntegrity(v.DataBackend, v.Version(), key); e != nil {
|
||||
return lastAppendAtNs, fmt.Errorf("verifyNeedleIntegrity %s failed: %v", indexFile.Name(), e)
|
||||
}
|
||||
} else {
|
||||
if lastAppendAtNs, e = verifyNeedleIntegrity(v.DataBackend, v.Version(), offset.ToAcutalOffset(), key, size); e != nil {
|
||||
return lastAppendAtNs, fmt.Errorf("verifyNeedleIntegrity %s failed: %v", indexFile.Name(), e)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -65,3 +69,20 @@ func verifyNeedleIntegrity(datFile backend.BackendStorageFile, v needle.Version,
|
||||
}
|
||||
return n.AppendAtNs, err
|
||||
}
|
||||
|
||||
func verifyDeletedNeedleIntegrity(datFile backend.BackendStorageFile, v needle.Version, key NeedleId) (lastAppendAtNs uint64, err error) {
|
||||
n := new(needle.Needle)
|
||||
size := n.DiskSize(v)
|
||||
var fileSize int64
|
||||
fileSize, _, err = datFile.GetStat()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("GetStat: %v", err)
|
||||
}
|
||||
if err = n.ReadData(datFile, fileSize-size, Size(0), v); err != nil {
|
||||
return n.AppendAtNs, fmt.Errorf("read data [%d,%d) : %v", fileSize-size, size, err)
|
||||
}
|
||||
if n.Id != key {
|
||||
return n.AppendAtNs, fmt.Errorf("index key %#x does not match needle's Id %#x", key, n.Id)
|
||||
}
|
||||
return n.AppendAtNs, err
|
||||
}
|
||||
@@ -200,12 +200,12 @@ func (v *Volume) syncDelete(n *needle.Needle) (Size, error) {
|
||||
size := nv.Size
|
||||
n.Data = nil
|
||||
n.AppendAtNs = uint64(time.Now().UnixNano())
|
||||
_, _, _, err := n.Append(v.DataBackend, v.Version())
|
||||
offset, _, _, err := n.Append(v.DataBackend, v.Version())
|
||||
if err != nil {
|
||||
return size, err
|
||||
}
|
||||
v.lastAppendAtNs = n.AppendAtNs
|
||||
if err = v.nm.Delete(n.Id); err != nil {
|
||||
if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
|
||||
return size, err
|
||||
}
|
||||
return size, err
|
||||
@@ -238,12 +238,12 @@ func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
|
||||
size := nv.Size
|
||||
n.Data = nil
|
||||
n.AppendAtNs = uint64(time.Now().UnixNano())
|
||||
_, _, _, err := n.Append(v.DataBackend, v.Version())
|
||||
offset, _, _, err := n.Append(v.DataBackend, v.Version())
|
||||
if err != nil {
|
||||
return size, err
|
||||
}
|
||||
v.lastAppendAtNs = n.AppendAtNs
|
||||
if err = v.nm.Delete(n.Id); err != nil {
|
||||
if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
|
||||
return size, err
|
||||
}
|
||||
return size, err
|
||||
@@ -263,7 +263,7 @@ func (v *Volume) readNeedle(n *needle.Needle, readOption *ReadOption) (int, erro
|
||||
readSize := nv.Size
|
||||
if readSize.IsDeleted() {
|
||||
if readOption != nil && readOption.ReadDeleted && readSize != TombstoneFileSize {
|
||||
glog.V(3).Infof("reading deleted %s size %d", n.String(), readSize)
|
||||
glog.V(3).Infof("reading deleted %s", n.String())
|
||||
readSize = -readSize
|
||||
} else {
|
||||
return -1, errors.New("already deleted")
|
||||
|
||||
@@ -374,7 +374,7 @@ func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string, prealloca
|
||||
return nil
|
||||
}
|
||||
|
||||
err = nm.SaveToIdx(idxName, false)
|
||||
err = nm.SaveToIdx(idxName)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -441,7 +441,7 @@ func copyDataBasedOnIndexFile(srcDatName, srcIdxName, dstDatName, datIdxName str
|
||||
return nil
|
||||
})
|
||||
|
||||
newNm.SaveToIdx(datIdxName, false)
|
||||
newNm.SaveToIdx(datIdxName)
|
||||
|
||||
return
|
||||
}
|
||||
@@ -12,11 +12,11 @@ import (
|
||||
"github.com/klauspost/compress/zstd"
|
||||
)
|
||||
|
||||
var(
|
||||
var (
|
||||
UnsupportedCompression = fmt.Errorf("unsupported compression")
|
||||
)
|
||||
|
||||
func MaybeGzipData(input []byte) ([]byte) {
|
||||
func MaybeGzipData(input []byte) []byte {
|
||||
if IsGzippedContent(input) {
|
||||
return input
|
||||
}
|
||||
@@ -24,13 +24,13 @@ func MaybeGzipData(input []byte) ([]byte) {
|
||||
if err != nil {
|
||||
return input
|
||||
}
|
||||
if len(gzipped) * 10 > len(input) * 9 {
|
||||
if len(gzipped)*10 > len(input)*9 {
|
||||
return input
|
||||
}
|
||||
return gzipped
|
||||
}
|
||||
|
||||
func MaybeDecompressData(input []byte) ([]byte) {
|
||||
func MaybeDecompressData(input []byte) []byte {
|
||||
uncompressed, err := DecompressData(input)
|
||||
if err != nil {
|
||||
if err != UnsupportedCompression {
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
VERSION = fmt.Sprintf("%s %d.%d", sizeLimit, 1, 96)
|
||||
VERSION = fmt.Sprintf("%s %d.%d", sizeLimit, 1, 99)
|
||||
COMMIT = ""
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user