mongo-replica-initializer/docker.go

95 lines
2.9 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"time"
"context"
"os"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
)
func dockerNetworkCreate() {
fmt.Printf("\033[1;32mCreating Docker network %s for MongoDB replica set %s\033[0m\n", networkName, replicasetName)
ExecSystem("docker network create " + networkName)
}
func dockerPullMongo() {
fmt.Printf("\033[1;32mPulling MongoDB Image\033[0m\n")
ExecSystem("docker pull mongo")
}
func checkDockerExistence() {
filePath := "/var/run/docker.sock"
_, err := os.Stat(filePath)
if os.IsNotExist(err) {
ExecSystem("dockerd &")
}
}
func dockerRunMongo() {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
panic(err)
}
for containerNumber := 0; containerNumber < numberOfContainers; containerNumber++ {
fmt.Printf("\033[1;32mStarting MongoDB Container %d with %s GB of memory\033[0m\n", containerNumber, getMemory())
//dockerRunCmd := fmt.Sprintf("docker run -d -p 3000%d:27017 --name mongo%d --net %s -e MONGO_INITDB_ROOT_USERNAME=%s -e MONGO_INITDB_ROOT_PASSWORD=%s -v %s/mongo%d:/data/db -v %s:/opt/keyfile --restart unless-stopped mongo mongod --replSet %s --wiredTigerCacheSizeGB %s --keyFile /opt/keyfile/mongodb-keyfile", containerNumber, containerNumber, networkName, mongoInitdbRootUsername, mongoInitdbRootPassword, mongoBasePath, containerNumber, mongoBasePath, replicasetName, get_memory())
containerName := "mongo" + fmt.Sprint(containerNumber)
config := &container.Config{
Image: "mongo:latest",
ExposedPorts: nat.PortSet{
"27017/tcp": struct{}{},
},
Env: []string{
fmt.Sprintf("MONGO_INITDB_ROOT_USERNAME=%s", mongoInitdbRootUsername),
fmt.Sprintf("MONGO_INITDB_ROOT_PASSWORD=%s", mongoInitdbRootPassword),
},
Cmd: []string{"mongod", "--replSet", replicasetName, "--wiredTigerCacheSizeGB", getMemory(), "--keyFile", "/opt/keyfile/mongodb-keyfile"},
Volumes: map[string]struct{}{
"/data/db": {},
"/opt/keyfile": {},
},
}
hostConfig := &container.HostConfig{
PortBindings: nat.PortMap{
"80/tcp": []nat.PortBinding{
{
HostIP: "0.0.0.0",
HostPort: fmt.Sprintf("3000%d", containerNumber),
},
},
},
Binds: []string{
fmt.Sprintf("%s/mongo%d:/data/db", mongoBasePath, containerNumber),
fmt.Sprintf("%s:/opt/keyfile", mongoBasePath),
},
NetworkMode: container.NetworkMode(networkName),
RestartPolicy: container.RestartPolicy{
Name: "unless-stopped",
},
}
resp, err := cli.ContainerCreate(context.Background(), config, hostConfig, nil, nil, containerName)
if err != nil {
panic(err)
}
if err := cli.ContainerStart(context.Background(), resp.ID, container.StartOptions{}); err != nil {
panic(err)
}
}
fmt.Printf("\033[1;32mWaiting for all containers to start\033[0m\n")
time.Sleep(10 * time.Second)
}