Permalink
Browse files

db: added one level of indirection to mgo.Session

This will allow us to collect old connections. We will mark collections
not used recently, and them cleanup everything :-)
  • Loading branch information...
1 parent 5ae7bd7 commit d3c3b8d850da518734d06c024adc23fc7dd591fd @fsouza fsouza committed Jan 21, 2013
Showing with 20 additions and 9 deletions.
  1. +18 −7 db/storage.go
  2. +2 −2 db/storage_test.go
View
@@ -15,27 +15,34 @@ import (
"github.com/globocom/config"
"labix.org/v2/mgo"
"sync"
+ "time"
)
var (
- conn = make(map[string]*mgo.Session) // pool of connections
- mut sync.RWMutex // for pool thread safety
+ conn = make(map[string]*session) // pool of connections
+ mut sync.RWMutex // for pool thread safety
+ ticker *time.Ticker // for garbage collection
)
+type session struct {
+ s *mgo.Session
+ used time.Time
+}
+
// Storage holds the connection with the database.
type Storage struct {
session *mgo.Session
dbname string
}
func open(addr, dbname string) (*Storage, error) {
- session, err := mgo.Dial(addr)
+ sess, err := mgo.Dial(addr)
if err != nil {
return nil, err
}
- storage := &Storage{session: session, dbname: dbname}
+ storage := &Storage{session: sess, dbname: dbname}
mut.Lock()
- conn[addr] = session
+ conn[addr] = &session{s: sess, used: time.Now()}
mut.Unlock()
return storage, nil
}
@@ -56,8 +63,12 @@ func Open(addr, dbname string) (storage *Storage, err error) {
mut.RLock()
if session, ok := conn[addr]; ok {
mut.RUnlock()
- if err = session.Ping(); err == nil {
- return &Storage{session, dbname}, nil
+ if err = session.s.Ping(); err == nil {
+ session.used = time.Now()
+ mut.Lock()
+ conn[addr] = session
+ mut.Unlock()
+ return &Storage{session.s, dbname}, nil
}
return open(addr, dbname)
}
View
@@ -55,7 +55,7 @@ func (s *S) TearDownSuite(c *C) {
}
func (s *S) TearDownTest(c *C) {
- conn = make(map[string]*mgo.Session)
+ conn = make(map[string]*session)
}
func (s *S) TestOpenConnectsToTheDatabase(c *C) {
@@ -69,7 +69,7 @@ func (s *S) TestOpenStoresConnectionInThePool(c *C) {
storage, err := Open("127.0.0.1:27017", "tsuru_storage_test")
c.Assert(err, IsNil)
defer storage.session.Close()
- c.Assert(storage.session, Equals, conn["127.0.0.1:27017"])
+ c.Assert(storage.session, Equals, conn["127.0.0.1:27017"].s)
}
func (s *S) TestOpenReusesConnection(c *C) {

0 comments on commit d3c3b8d

Please sign in to comment.