seaweedfs/go/sequence/sequence.go

79 lines
2.1 KiB
Go
Raw Normal View History

2012-09-03 22:41:24 +00:00
package sequence
import (
2013-01-17 08:56:56 +00:00
"encoding/gob"
"code.google.com/p/weed-fs/go/glog"
2013-01-17 08:56:56 +00:00
"os"
"path"
"sync"
2012-09-03 22:41:24 +00:00
)
const (
FileIdSaveInterval = 10000
)
type Sequencer interface {
NextFileId(count int) (uint64, int)
}
type SequencerImpl struct {
dir string
fileName string
volumeLock sync.Mutex
sequenceLock sync.Mutex
FileIdSequence uint64
fileIdCounter uint64
}
func NewSequencer(dirname string, filename string) (m *SequencerImpl) {
2013-01-17 08:56:56 +00:00
m = &SequencerImpl{dir: dirname, fileName: filename}
2012-09-03 22:41:24 +00:00
2013-01-17 08:56:56 +00:00
seqFile, se := os.OpenFile(path.Join(m.dir, m.fileName+".seq"), os.O_RDONLY, 0644)
if se != nil {
m.FileIdSequence = FileIdSaveInterval
glog.V(0).Infoln("Setting file id sequence", m.FileIdSequence)
2013-01-17 08:56:56 +00:00
} else {
decoder := gob.NewDecoder(seqFile)
defer seqFile.Close()
2013-02-27 06:54:22 +00:00
if se = decoder.Decode(&m.FileIdSequence); se != nil {
glog.V(0).Infof("error decoding FileIdSequence: %s", se)
2013-02-27 06:54:22 +00:00
m.FileIdSequence = FileIdSaveInterval
glog.V(0).Infoln("Setting file id sequence", m.FileIdSequence)
2013-02-27 06:54:22 +00:00
} else {
glog.V(0).Infoln("Loading file id sequence", m.FileIdSequence, "=>", m.FileIdSequence+FileIdSaveInterval)
2013-02-27 06:54:22 +00:00
m.FileIdSequence += FileIdSaveInterval
}
2013-01-17 08:56:56 +00:00
//in case the server stops between intervals
}
return
2012-09-03 22:41:24 +00:00
}
//count should be 1 or more
func (m *SequencerImpl) NextFileId(count int) (uint64, int) {
if count <= 0 {
return 0, 0
}
m.sequenceLock.Lock()
defer m.sequenceLock.Unlock()
if m.fileIdCounter < uint64(count) {
m.fileIdCounter = FileIdSaveInterval
m.FileIdSequence += FileIdSaveInterval
m.saveSequence()
}
m.fileIdCounter = m.fileIdCounter - uint64(count)
2013-03-19 20:37:36 +00:00
return m.FileIdSequence - m.fileIdCounter - uint64(count), count
2012-09-03 22:41:24 +00:00
}
func (m *SequencerImpl) saveSequence() {
glog.V(0).Infoln("Saving file id sequence", m.FileIdSequence, "to", path.Join(m.dir, m.fileName+".seq"))
2013-01-17 08:56:56 +00:00
seqFile, e := os.OpenFile(path.Join(m.dir, m.fileName+".seq"), os.O_CREATE|os.O_WRONLY, 0644)
if e != nil {
glog.Fatalf("Sequence File Save [ERROR] %s", e)
2013-01-17 08:56:56 +00:00
}
defer seqFile.Close()
encoder := gob.NewEncoder(seqFile)
2013-02-27 06:54:22 +00:00
if e = encoder.Encode(m.FileIdSequence); e != nil {
glog.Fatalf("Sequence File Save [ERROR] %s", e)
2013-02-27 06:54:22 +00:00
}
2012-09-03 22:41:24 +00:00
}