@@ -17,6 +17,8 @@ import (
1717 corev1 "k8s.io/api/core/v1"
1818 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1919 "k8s.io/apimachinery/pkg/types"
20+ "k8s.io/apimachinery/pkg/util/wait"
21+ "k8s.io/client-go/util/retry"
2022 logf "sigs.k8s.io/controller-runtime/pkg/log"
2123
2224 api "github.com/percona/percona-server-mongodb-operator/pkg/apis/psmdb/v1"
@@ -719,8 +721,35 @@ func (r *ReconcilePerconaServerMongoDB) handleReplsetInit(ctx context.Context, c
719721 return nil , nil , fmt .Errorf ("exec rs.initiate: %v / %s / %s" , err , outb .String (), errb .String ())
720722 }
721723
724+ backoff := wait.Backoff {
725+ Steps : 5 ,
726+ Duration : 50 * time .Millisecond ,
727+ Factor : 5.0 ,
728+ Jitter : 0.1 ,
729+ }
730+ err = retry .OnError (backoff , func (err error ) bool { return true }, func () error {
731+ var stderr , stdout bytes.Buffer
732+
733+ hello := []string {"sh" , "-c" ,
734+ mongoCmd + " --eval 'db.runCommand({ hello: 1 }).isWritablePrimary'" }
735+ err = r .clientcmd .Exec (ctx , & pod , "mongod" , hello , nil , & stdout , & stderr , false )
736+ if err != nil {
737+ return errors .Wrapf (err , "run hello stdout: %s, stderr: %s" , stdout .String (), stderr .String ())
738+ }
739+
740+ out := strings .Trim (stdout .String (), "\n " )
741+ if out != "true" {
742+ return errors .New ("is not the writable primary" )
743+ }
744+
745+ log .Info (pod .Name + " is the writable primary" , "replset" , replsetName )
746+
747+ return nil
748+ })
749+ if err != nil {
750+ return nil , nil , errors .Wrap (err , "wait for replset initialization" )
751+ }
722752 log .Info ("replset initialized" , "replset" , replsetName , "pod" , pod .Name )
723- time .Sleep (time .Second * 5 )
724753
725754 log .Info ("creating user admin" , "replset" , replsetName , "pod" , pod .Name , "user" , api .RoleUserAdmin )
726755 userAdmin , err := getInternalCredentials (ctx , r .client , cr , api .RoleUserAdmin )
0 commit comments