Browse Source

Merge pull request #1092 from jonboulle/dumb_gen_id

GenID: use a fast prnd
Jonathan Boulle 11 năm trước cách đây
mục cha
commit
655efca308
2 tập tin đã thay đổi với 22 bổ sung14 xóa
  1. 9 14
      etcdserver/server.go
  2. 13 0
      etcdserver/server_test.go

+ 9 - 14
etcdserver/server.go

@@ -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) {

+ 13 - 0
etcdserver/server_test.go

@@ -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!")
+	}
+}