package main import ( "context" "time" "fmt" "log" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/bson" ) func initReplMongo() { if *localIpPtr{ ips, err := GetLocalIPs() if err != nil { log.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // Create a new replica set client uri := fmt.Sprintf("mongodb://%s:%s@localhost:30000/?directConnection=true", mongoInitdbRootUsername, mongoInitdbRootPassword) client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) if err != nil { panic(err) } db := client.Database("admin") members := make([]bson.M, numberOfContainers) for i := 0; i < numberOfContainers; i++ { members[i] = bson.M{ "_id": i, "host": fmt.Sprintf("%s:%d", ips[0], 30000+i), } } config := bson.M{ "_id": replicasetName, "members": members, } if *verbosePtr{ fmt.Println(config) } command := bson.D{{"replSetInitiate", config}} var result bson.M err = db.RunCommand(context.TODO(), command).Decode(&result) if err != nil { panic(err) } client.Disconnect(ctx) } else { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // Create a new replica set client uri := fmt.Sprintf("mongodb://%s:%s@localhost:30000/?directConnection=true", mongoInitdbRootUsername, mongoInitdbRootPassword) client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) if err != nil { panic(err) } db := client.Database("admin") members := make([]bson.M, numberOfContainers) for i := 0; i < numberOfContainers; i++ { members[i] = bson.M{ "_id": i, "host": fmt.Sprintf("mongo%d", i), } } config := bson.M{ "_id": replicasetName, "members": members, } if *verbosePtr{ fmt.Println(config) } command := bson.D{{"replSetInitiate", config}} var result bson.M err = db.RunCommand(context.TODO(), command).Decode(&result) if err != nil { panic(err) } client.Disconnect(ctx) } }