Merge pull request #1092 from jonboulle/dumb_gen_id

GenID: use a fast prnd
This commit is contained in:
Jonathan Boulle 2014-09-17 16:00:25 -07:00
commit 655efca308
2 changed files with 22 additions and 14 deletions

View File

@ -1,14 +1,11 @@
package etcdserver
import (
"encoding/binary"
"errors"
"io"
"log"
"math/rand"
"time"
crand "crypto/rand"
pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
@ -27,6 +24,10 @@ var (
ErrStopped = errors.New("etcdserver: server stopped")
)
func init() {
rand.Seed(time.Now().UnixNano())
}
type SendFunc func(m []raftpb.Message)
type SaveFunc func(st raftpb.HardState, ents []raftpb.Entry)
@ -295,17 +296,11 @@ func (s *EtcdServer) snapshot() {
// TODO: move the function to /id pkg maybe?
// GenID generates a random id that is not equal to 0.
func GenID() int64 {
for {
b := make([]byte, 8)
if _, err := io.ReadFull(crand.Reader, b); err != nil {
panic(err) // really bad stuff happened
}
n := int64(binary.BigEndian.Uint64(b))
if n != 0 {
return n
}
func GenID() (n int64) {
for n == 0 {
n = rand.Int63()
}
return
}
func getBool(v *bool) (vv bool, set bool) {

View File

@ -635,3 +635,16 @@ func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) {
}
p.record("SaveSnap")
}
func TestGenID(t *testing.T) {
// Sanity check that the GenID function has been seeded appropriately
// (math/rand is seeded with 1 by default)
r := rand.NewSource(int64(1))
var n int64
for n == 0 {
n = r.Int63()
}
if n == GenID() {
t.Fatalf("GenID's rand seeded with 1!")
}
}