You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
4 years ago
|
package log
|
||
4 years ago
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
|
||
4 years ago
|
"github.com/hashicorp/raft"
|
||
4 years ago
|
"github.com/hashicorp/raft-boltdb"
|
||
|
)
|
||
|
|
||
4 years ago
|
// Log is an object that can return information about the Raft log.
|
||
4 years ago
|
type Log struct {
|
||
4 years ago
|
*raftboltdb.BoltStore
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
// NewLog returns an instantiated Log object.
|
||
4 years ago
|
func NewLog(path string) (*Log, error) {
|
||
|
bs, err := raftboltdb.NewBoltStore(path)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("new bolt store: %s", err)
|
||
4 years ago
|
}
|
||
4 years ago
|
return &Log{bs}, nil
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
// Indexes returns the first and last indexes.
|
||
|
func (l *Log) Indexes() (uint64, uint64, error) {
|
||
|
fi, err := l.FirstIndex()
|
||
4 years ago
|
if err != nil {
|
||
4 years ago
|
return 0, 0, fmt.Errorf("failed to get first index: %s", err)
|
||
4 years ago
|
}
|
||
4 years ago
|
li, err := l.LastIndex()
|
||
4 years ago
|
if err != nil {
|
||
4 years ago
|
return 0, 0, fmt.Errorf("failed to get last index: %s", err)
|
||
4 years ago
|
}
|
||
4 years ago
|
return fi, li, nil
|
||
4 years ago
|
}
|
||
4 years ago
|
|
||
4 years ago
|
// LastCommandIndex returns the index of the last Command
|
||
|
// log entry written to the Raft log. Returns an index of
|
||
|
// zero if no such log exists.
|
||
|
func (l *Log) LastCommandIndex() (uint64, error) {
|
||
|
fi, li, err := l.Indexes()
|
||
|
if err != nil {
|
||
|
return 0, fmt.Errorf("get indexes: %s", err)
|
||
|
}
|
||
|
|
||
4 years ago
|
// Check for empty log.
|
||
|
if li == 0 {
|
||
|
return 0, nil
|
||
4 years ago
|
}
|
||
|
|
||
|
var rl raft.Log
|
||
|
for i := li; i >= fi; i-- {
|
||
4 years ago
|
if err := l.GetLog(i, &rl); err != nil {
|
||
|
return 0, fmt.Errorf("get log at index %d: %s", i, err)
|
||
4 years ago
|
}
|
||
|
if rl.Type == raft.LogCommand {
|
||
|
return i, nil
|
||
|
}
|
||
|
}
|
||
|
return 0, nil
|
||
|
}
|