add known working replset initiation code

This commit is contained in:
Late Night Defender 2024-05-27 15:02:05 +07:00
parent aa8d6c05c7
commit 77d9030e80

View file

@ -2,44 +2,43 @@ package main
import ( import (
"context" "context"
"time"
"fmt" "fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
) )
func initReplMongo() { func initReplMongo() {
// Create a new client and connect to the servers ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:30000")) defer cancel()
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// Get a handle to the admin database // Create a new replica set client
admin := client.Database("admin") client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://sasha:12345@localhost:30000/?directConnection=true"))
if err != nil {
panic(err)
}
// Define the replica set configuration db := client.Database("admin")
config := bson.M{
"_id": replicasetName,
"members": []bson.M{},
}
for i := 0; i < int(numberOfContainers); i++ { members := make([]bson.M, numberOfContainers)
member := bson.M{ for i := 0; i < numberOfContainers; i++ {
members[i] = bson.M{
"_id": i, "_id": i,
"host": fmt.Sprintf("mongo%d", i), "host": fmt.Sprintf("mongo%d", i),
} }
config["members"] = append(config["members"].([]bson.M), member)
} }
// Initiate the replica set config := bson.M{
res, err := admin.RunCommand(context.TODO(), bson.D{{"replSetInitiate", config}}).Raw() "_id": replicasetName,
"members": members,
}
command := bson.D{{"replSetInitiate", config}}
var result bson.M
err = db.RunCommand(context.TODO(), command).Decode(&result)
if err != nil { if err != nil {
panic(err) panic(err)
} }
client.Disconnect(ctx)
fmt.Println(res)
} }