Skip to content

Commit

Permalink
Local cache to reuse db connection
Browse files Browse the repository at this point in the history
migrate library not closing the db connection db show those connections
are in 'idle' state. When the count reaches the limit database is not
accessible.

so cache the db connection in a map with resouce name as key.
  • Loading branch information
jkraj committed Jul 5, 2018
1 parent b2f7292 commit b477722
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions atlas-db-controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import (

"github.com/infobloxopen/atlas-db/pkg/server"
"github.com/infobloxopen/atlas-db/pkg/server/plugin"
"github.com/golang-migrate/migrate/database"
)

const controllerAgentName = "atlas-db-controller"
Expand Down Expand Up @@ -66,6 +67,7 @@ const (
)

var schemaStatusMsg string
var dbDriverMap = make(map[string]database.Driver)

// Controller is the controller implementation for DatabaseServer resources
type Controller struct {
Expand Down Expand Up @@ -386,16 +388,29 @@ func (c *Controller) syncSchema(key string) error {
}
}

mgrt, err := migrate.New(gitURL, dsn)
// migrate package is not closing the dbconnnection so using a local cache reuse dbconnection.
// TODO when same resource with different dsn arrives; need to unset local cache during schema resource deletion.
dbDriver, ok := dbDriverMap[schema.Namespace + schema.Name]
if !ok {
dbDriver, err = database.Open(dsn)
if err != nil {
schemaStatusMsg = fmt.Sprintf("failed to open dbconnection: %s", err)
c.updateDatabaseSchemaStatus(key, schema, StateError, schemaStatusMsg)
err = fmt.Errorf(schemaStatusMsg)
runtime.HandleError(err)
return err
}
dbDriverMap[schema.Namespace + schema.Name] = dbDriver
}

mgrt, err := migrate.NewWithDatabaseInstance(gitURL, dbName, dbDriver)
if err != nil {
schemaStatusMsg = fmt.Sprintf("failed to initialize migrate engine: %s", err)
c.updateDatabaseSchemaStatus(key, schema, StateError, schemaStatusMsg)
err = fmt.Errorf(schemaStatusMsg)
runtime.HandleError(err)
return err
}
defer mgrt.Close()

ver, dirt, err := mgrt.Version()
if err != nil {
if err == migrate.ErrNilVersion {
Expand Down

0 comments on commit b477722

Please sign in to comment.