2011-12-16 22:51:26 +08:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"strconv"
|
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Volume struct {
|
2011-12-22 12:04:47 +08:00
|
|
|
Id uint32
|
|
|
|
dir string
|
|
|
|
dataFile *os.File
|
|
|
|
nm *NeedleMap
|
2011-12-16 22:51:26 +08:00
|
|
|
|
|
|
|
accessChannel chan int
|
|
|
|
}
|
|
|
|
|
2011-12-20 17:00:01 +08:00
|
|
|
func NewVolume(dirname string, id uint32) (v *Volume) {
|
2011-12-16 22:51:26 +08:00
|
|
|
var e os.Error
|
2011-12-22 12:04:47 +08:00
|
|
|
v = &Volume{dir: dirname, Id: id, nm: NewNeedleMap()}
|
2011-12-20 17:00:01 +08:00
|
|
|
fileName := strconv.Uitoa64(uint64(v.Id))
|
2011-12-22 12:04:47 +08:00
|
|
|
v.dataFile, e = os.OpenFile(path.Join(v.dir, fileName+".dat"), os.O_RDWR|os.O_CREATE, 0644)
|
2011-12-16 22:51:26 +08:00
|
|
|
if e != nil {
|
|
|
|
log.Fatalf("New Volume [ERROR] %s\n", e)
|
|
|
|
}
|
2011-12-22 12:04:47 +08:00
|
|
|
indexFile, ie := os.OpenFile(path.Join(v.dir, fileName+".idx"), os.O_RDWR|os.O_CREATE, 0644)
|
|
|
|
if ie != nil {
|
|
|
|
log.Fatalf("New Volume [ERROR] %s\n", ie)
|
2011-12-16 22:51:26 +08:00
|
|
|
}
|
2011-12-22 12:04:47 +08:00
|
|
|
v.nm = LoadNeedleMap(indexFile)
|
2011-12-16 22:51:26 +08:00
|
|
|
|
|
|
|
v.accessChannel = make(chan int, 1)
|
|
|
|
v.accessChannel <- 0
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
2011-12-18 15:22:04 +08:00
|
|
|
func (v *Volume) Size() int64 {
|
2011-12-22 12:04:47 +08:00
|
|
|
stat, e := v.dataFile.Stat()
|
|
|
|
if e == nil {
|
|
|
|
return stat.Size
|
|
|
|
}
|
|
|
|
return -1
|
2011-12-17 14:47:23 +08:00
|
|
|
}
|
2011-12-16 22:51:26 +08:00
|
|
|
func (v *Volume) Close() {
|
|
|
|
close(v.accessChannel)
|
2011-12-22 12:04:47 +08:00
|
|
|
v.nm.Close()
|
2011-12-16 22:51:26 +08:00
|
|
|
v.dataFile.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *Volume) write(n *Needle) {
|
|
|
|
counter := <-v.accessChannel
|
|
|
|
offset, _ := v.dataFile.Seek(0, 2)
|
|
|
|
n.Append(v.dataFile)
|
2011-12-20 10:34:53 +08:00
|
|
|
nv, ok := v.nm.get(n.Key)
|
2011-12-16 22:51:26 +08:00
|
|
|
if !ok || int64(nv.Offset)*8 < offset {
|
2011-12-20 10:34:53 +08:00
|
|
|
v.nm.put(n.Key, uint32(offset/8), n.Size)
|
2011-12-16 22:51:26 +08:00
|
|
|
}
|
|
|
|
v.accessChannel <- counter + 1
|
|
|
|
}
|
|
|
|
func (v *Volume) read(n *Needle) {
|
|
|
|
counter := <-v.accessChannel
|
2011-12-20 10:34:53 +08:00
|
|
|
nv, ok := v.nm.get(n.Key)
|
2011-12-16 22:51:26 +08:00
|
|
|
if ok && nv.Offset > 0 {
|
|
|
|
v.dataFile.Seek(int64(nv.Offset)*8, 0)
|
|
|
|
n.Read(v.dataFile, nv.Size)
|
|
|
|
}
|
|
|
|
v.accessChannel <- counter + 1
|
|
|
|
}
|