5
5
"context"
6
6
"fmt"
7
7
"io"
8
+ "os"
9
+ "strconv"
8
10
"testing"
9
11
"time"
10
12
@@ -228,24 +230,27 @@ func TestTransaction(t *testing.T) {
228
230
})
229
231
}
230
232
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"`
237
235
}
238
236
239
237
func waitForReplicaInit (client * mongo.Client ) error {
240
- ticker := time .NewTicker (time .Second * 5 )
238
+ ticker := time .NewTicker (time .Second * 1 )
241
239
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 ()
244
246
for {
245
247
select {
246
248
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 }})
249
254
r , err := result .DecodeBytes ()
250
255
if err != nil {
251
256
return err
@@ -254,12 +259,10 @@ func waitForReplicaInit(client *mongo.Client) error {
254
259
if err != nil {
255
260
return err
256
261
}
257
- if len (status .Members ) > 0 {
258
- if status .Members [0 ].StateStr == "PRIMARY" {
259
- return nil
260
- }
262
+ if status .IsMaster {
263
+ return nil
261
264
}
262
- case <- timeout .C :
265
+ case <- timeoutTimer .C :
263
266
return fmt .Errorf ("replica init timeout" )
264
267
}
265
268
}
0 commit comments