You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
backy/pkg/backy/mongo.go

97 lines
2.6 KiB

package backy
import (
"context"
"errors"
"fmt"
"os"
"time"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
const mongoConfigKey = "global.mongo"
func (opts *BackyConfigOpts) InitMongo() {
if !opts.viper.GetBool(getMongoConfigKey("enabled")) {
return
}
var (
err error
client *mongo.Client
)
// TODO: Get uri and creditials from config
host := opts.viper.GetString(getMongoConfigKey("host"))
port := opts.viper.GetInt32(getMongoConfigKey("port"))
client, err = mongo.NewClient(options.Client().ApplyURI(fmt.Sprintf("mongo://%s:%d", host, port)))
if opts.viper.GetBool(getMongoConfigKey("prod")) {
mongoEnvFileSet := opts.viper.IsSet(getMongoConfigKey("env"))
if mongoEnvFileSet {
getMongoConfigFromEnv(opts)
}
auth := options.Credential{}
auth.Password = opts.viper.GetString("global.mongo.password")
auth.Username = opts.viper.GetString("global.mongo.username")
client, err = mongo.NewClient(options.Client().SetAuth(auth).ApplyURI("mongodb://localhost:27017"))
}
if err != nil {
opts.ConfigFile.Logger.Fatal().Err(err).Send()
}
ctx, ctxCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer ctxCancel()
err = client.Connect(ctx)
if err != nil {
opts.ConfigFile.Logger.Fatal().Err(err).Send()
}
defer client.Disconnect(ctx)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
opts.ConfigFile.Logger.Fatal().Err(err).Send()
}
databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
opts.ConfigFile.Logger.Fatal().Err(err).Send()
}
fmt.Println(databases)
backyDB := client.Database("backy")
backyDB.CreateCollection(context.Background(), "cmds")
backyDB.CreateCollection(context.Background(), "cmd-lists")
backyDB.CreateCollection(context.Background(), "logs")
opts.DB = backyDB
}
func getMongoConfigFromEnv(opts *BackyConfigOpts) error {
mongoEnvFile, err := os.Open(opts.viper.GetString("global.mongo.env"))
if err != nil {
return err
}
mongoMap, mongoErr := godotenv.Parse(mongoEnvFile)
if mongoErr != nil {
return err
}
mongoPW, mongoPWFound := mongoMap["MONGO_PASSWORD"]
if !mongoPWFound {
return errors.New("MONGO_PASSWORD not set in " + mongoEnvFile.Name())
}
mongoUser, mongoUserFound := mongoMap["MONGO_USER"]
if !mongoUserFound {
return errors.New("MONGO_PASSWORD not set in " + mongoEnvFile.Name())
}
opts.viper.Set(mongoConfigKey+".password", mongoPW)
opts.viper.Set(mongoConfigKey+".username", mongoUser)
return nil
}
func getMongoConfigKey(key string) string {
return fmt.Sprintf("global.mongo.%s", key)
}