Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 12b93a3

Browse files
author
DBobrov
committed
Change checking of mongo replica set initialization
1 parent 3fa0df7 commit 12b93a3

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

database/mongodb/mongodb_test.go

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"context"
66
"fmt"
77
"io"
8+
"os"
9+
"strconv"
810
"testing"
911
"time"
1012

@@ -228,24 +230,27 @@ func TestTransaction(t *testing.T) {
228230
})
229231
}
230232

231-
type replicaSetStatus struct {
232-
Members []replicaMember `bson:"members"`
233-
}
234-
235-
type replicaMember struct {
236-
StateStr string `bson:"stateStr"`
233+
type isMaster struct {
234+
IsMaster bool `bson:"ismaster"`
237235
}
238236

239237
func waitForReplicaInit(client *mongo.Client) error {
240-
ticker := time.NewTicker(time.Second * 5)
238+
ticker := time.NewTicker(time.Second * 1)
241239
defer ticker.Stop()
242-
timeout := time.NewTimer(time.Second * 30)
243-
defer timeout.Stop()
240+
timeout, err := strconv.Atoi(os.Getenv("MIGRATE_TEST_MONGO_REPLICA_SET_INIT_TIMEOUT"))
241+
if err != nil {
242+
timeout = 30
243+
}
244+
timeoutTimer := time.NewTimer(time.Duration(timeout) * time.Second)
245+
defer timeoutTimer.Stop()
244246
for {
245247
select {
246248
case <-ticker.C:
247-
status := replicaSetStatus{}
248-
result := client.Database("admin").RunCommand(context.TODO(), bson.D{{"replSetGetStatus", 1}})
249+
var status isMaster
250+
//Check that node is primary because
251+
//during replica set initialization, the first node first becomes a secondary and then becomes the primary
252+
//should consider that initialization is completed only after the node has become the primary
253+
result := client.Database("admin").RunCommand(context.TODO(), bson.D{{"isMaster", 1}})
249254
r, err := result.DecodeBytes()
250255
if err != nil {
251256
return err
@@ -254,12 +259,10 @@ func waitForReplicaInit(client *mongo.Client) error {
254259
if err != nil {
255260
return err
256261
}
257-
if len(status.Members) > 0 {
258-
if status.Members[0].StateStr == "PRIMARY" {
259-
return nil
260-
}
262+
if status.IsMaster {
263+
return nil
261264
}
262-
case <-timeout.C:
265+
case <-timeoutTimer.C:
263266
return fmt.Errorf("replica init timeout")
264267
}
265268
}

0 commit comments

Comments
 (0)