Skip to content
Snippets Groups Projects
mongo-connection.go 1.38 KiB
Newer Older
  • Learn to ignore specific revisions
  • 	"log"
    	"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"
    )
    
    
    // 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))
    
    		log.Printf("Failed to create client: %v", err)
    
    		return nil, err
    
    	}
    
    	// Force a connection to verify our connection string
    	err = client.Ping(ctx, nil)
    	if err != nil {
    		log.Printf("Failed to connect to database: %v\n", err)
    
    		return nil, 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 {
    	var db *mongo.Database
    
    	storeMode := store.GetStoreMode()
    	if storeMode == store.Database {
    		db, err := Connect()
    		if err != nil {
    			logrus.Infof("Could not connect to database")
    		}
    
    		return db
    	}
    
    	return db