seaweedfs/go/storage/volume_vacuum.go

83 lines
2.2 KiB
Go
Raw Normal View History

2014-05-20 10:24:35 +08:00
package storage
import (
"code.google.com/p/weed-fs/go/glog"
2014-05-20 11:54:39 +08:00
"fmt"
2014-05-20 10:24:35 +08:00
"os"
2014-05-27 08:36:41 +08:00
_ "time"
2014-05-20 10:24:35 +08:00
)
func (v *Volume) garbageLevel() float64 {
return float64(v.nm.DeletedSize()) / float64(v.ContentSize())
}
func (v *Volume) Compact() error {
2014-05-27 08:34:54 +08:00
glog.V(3).Infof("Compacting ...")
2014-05-20 10:24:35 +08:00
v.accessLock.Lock()
defer v.accessLock.Unlock()
2014-05-27 08:34:54 +08:00
glog.V(3).Infof("Got Compaction lock...")
2014-05-20 10:24:35 +08:00
filePath := v.FileName()
glog.V(3).Infof("creating copies for volume %d ...", v.Id)
return v.copyDataAndGenerateIndexFile(filePath+".cpd", filePath+".cpx")
}
func (v *Volume) commitCompact() error {
2014-05-27 08:34:54 +08:00
glog.V(3).Infof("Committing vacuuming...")
2014-05-20 10:24:35 +08:00
v.accessLock.Lock()
defer v.accessLock.Unlock()
2014-05-27 08:34:54 +08:00
glog.V(3).Infof("Got Committing lock...")
2014-05-20 10:24:35 +08:00
_ = v.dataFile.Close()
var e error
if e = os.Rename(v.FileName()+".cpd", v.FileName()+".dat"); e != nil {
return e
}
if e = os.Rename(v.FileName()+".cpx", v.FileName()+".idx"); e != nil {
return e
}
2014-05-27 08:34:54 +08:00
//glog.V(3).Infof("Pretending to be vacuuming...")
//time.Sleep(20 * time.Second)
2014-05-20 10:24:35 +08:00
if e = v.load(true, false); e != nil {
return e
}
return nil
}
2014-05-20 11:54:39 +08:00
func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string) (err error) {
var (
dst, idx *os.File
)
if dst, err = os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
return
}
defer dst.Close()
if idx, err = os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
return
}
defer idx.Close()
nm := NewNeedleMap(idx)
new_offset := int64(SuperBlockSize)
err = ScanVolumeFile(v.dir, v.Collection, v.Id, func(superBlock SuperBlock) error {
_, err = dst.Write(superBlock.Bytes())
return err
2014-06-01 08:10:51 +08:00
}, true, func(n *Needle, offset int64) error {
2014-05-20 11:54:39 +08:00
nv, ok := v.nm.Get(n.Id)
2014-05-27 08:34:54 +08:00
glog.V(4).Infoln("needle expected offset ", offset, "ok", ok, "nv", nv)
2014-05-20 11:54:39 +08:00
if ok && int64(nv.Offset)*NeedlePaddingSize == offset && nv.Size > 0 {
if _, err = nm.Put(n.Id, uint32(new_offset/NeedlePaddingSize), n.Size); err != nil {
return fmt.Errorf("cannot put needle: %s", err)
}
if _, err = n.Append(dst, v.Version()); err != nil {
return fmt.Errorf("cannot append needle: %s", err)
}
new_offset += n.DiskSize()
glog.V(3).Infoln("saving key", n.Id, "volume offset", offset, "=>", new_offset, "data_size", n.Size)
}
return nil
})
return
}