Skip to content
Snippets Groups Projects
mongo-connection.go 1.68 KiB
Newer Older
  • Learn to ignore specific revisions
  • 	"time"
    
    	"code.fbi.h-da.de/danet/gosdn/controller/config"
    
    	"code.fbi.h-da.de/danet/gosdn/controller/store"
    	"github.com/sirupsen/logrus"
    
    	"go.mongodb.org/mongo-driver/mongo"
    	"go.mongodb.org/mongo-driver/mongo/options"
    )
    
    const (
    
    	// Timeout operations after N seconds.
    
    	timeout = 5 * time.Second
    
    	// DatabaseName is the name of the mongoDB database used.
    	DatabaseName = "gosdn"
    
    
    	connectionRetries = 60
    	connectionTimeout = time.Second * 2
    
    // Connect Retrieves a client to the MongoDB.
    func Connect() (*mongo.Database, error) {
    
    	mongoConnection := config.DatabaseConnection
    
    	ctx, cancel := context.WithTimeout(context.Background(), timeout)
    	defer cancel()
    
    	client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoConnection))
    
    		return nil, fmt.Errorf("failed to create client: %w", err)
    
    	}
    
    	// Force a connection to verify our connection string
    	err = client.Ping(ctx, nil)
    	if err != nil {
    
    		return nil, fmt.Errorf("failed to connect to database: %w", err)
    
    	db := client.Database(DatabaseName)
    	if db == nil {
    		return nil, fmt.Errorf("can not connect to database %s", DatabaseName)
    	}
    
    	return db, nil
    }
    
    
    func GetDatabaseConnection() (*mongo.Database, error) {
    
    	var db *mongo.Database
    
    	storeMode := store.GetStoreMode()
    
    
    	switch storeMode {
    	case store.Database:
    		for i := 0; i < connectionRetries; i++ {
    			db, err := Connect()
    			if err == nil {
    				return db, nil
    			}
    			logrus.Errorf("could not connect to mongo with error: %s. Retrying in 2 seconds.", err.Error())
    			time.Sleep(connectionTimeout)
    
    		return nil, fmt.Errorf("could not connect to mongo after %d retries", connectionRetries)