mirror of
https://github.com/etcd-io/etcd.git
synced 2024-09-27 06:25:44 +00:00
etcdserver: use simple PRNG for GenID
This commit is contained in:
parent
1c544667ff
commit
a42d52482c
@ -1,14 +1,11 @@
|
|||||||
package etcdserver
|
package etcdserver
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
|
"math/rand"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
crand "crypto/rand"
|
|
||||||
|
|
||||||
pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
|
pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
|
||||||
"github.com/coreos/etcd/raft"
|
"github.com/coreos/etcd/raft"
|
||||||
"github.com/coreos/etcd/raft/raftpb"
|
"github.com/coreos/etcd/raft/raftpb"
|
||||||
@ -27,6 +24,10 @@ var (
|
|||||||
ErrStopped = errors.New("etcdserver: server stopped")
|
ErrStopped = errors.New("etcdserver: server stopped")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rand.Seed(time.Now().UnixNano())
|
||||||
|
}
|
||||||
|
|
||||||
type SendFunc func(m []raftpb.Message)
|
type SendFunc func(m []raftpb.Message)
|
||||||
type SaveFunc func(st raftpb.HardState, ents []raftpb.Entry)
|
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?
|
// TODO: move the function to /id pkg maybe?
|
||||||
// GenID generates a random id that is not equal to 0.
|
// GenID generates a random id that is not equal to 0.
|
||||||
func GenID() int64 {
|
func GenID() (n int64) {
|
||||||
for {
|
for n == 0 {
|
||||||
b := make([]byte, 8)
|
n = rand.Int63()
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func getBool(v *bool) (vv bool, set bool) {
|
func getBool(v *bool) (vv bool, set bool) {
|
||||||
|
@ -635,3 +635,16 @@ func (p *storageRecorder) SaveSnap(st raftpb.Snapshot) {
|
|||||||
}
|
}
|
||||||
p.record("SaveSnap")
|
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!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user