2018-07-19 15:48:08 +01:00
|
|
|
// Copyright (C) 2018 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information
|
|
|
|
|
2018-10-25 17:11:50 +01:00
|
|
|
package node
|
2018-07-19 15:48:08 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
2018-10-26 15:07:02 +01:00
|
|
|
|
|
|
|
"github.com/zeebo/errs"
|
|
|
|
|
|
|
|
"storj.io/storj/pkg/utils"
|
2018-07-19 15:48:08 +01:00
|
|
|
)
|
|
|
|
|
2018-10-26 15:07:02 +01:00
|
|
|
// Error defines a connection pool error
|
|
|
|
var Error = errs.Class("connection pool error")
|
|
|
|
|
|
|
|
// ConnectionPool is the in memory pool of node connections
|
2018-07-19 15:48:08 +01:00
|
|
|
type ConnectionPool struct {
|
|
|
|
mu sync.RWMutex
|
|
|
|
cache map[string]interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewConnectionPool initializes a new in memory pool
|
2018-10-08 16:09:37 +01:00
|
|
|
func NewConnectionPool() *ConnectionPool {
|
2018-10-26 15:07:02 +01:00
|
|
|
return &ConnectionPool{}
|
2018-07-19 15:48:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add takes a node ID as the key and a node client as the value to store
|
2018-10-25 17:11:50 +01:00
|
|
|
func (pool *ConnectionPool) Add(key string, value interface{}) error {
|
|
|
|
pool.mu.Lock()
|
|
|
|
defer pool.mu.Unlock()
|
|
|
|
pool.cache[key] = value
|
2018-07-19 15:48:08 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get retrieves a node connection with the provided nodeID
|
|
|
|
// nil is returned if the NodeID is not in the connection pool
|
2018-10-25 17:11:50 +01:00
|
|
|
func (pool *ConnectionPool) Get(key string) (interface{}, error) {
|
|
|
|
pool.mu.Lock()
|
|
|
|
defer pool.mu.Unlock()
|
|
|
|
return pool.cache[key], nil
|
2018-07-19 15:48:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Remove deletes a connection associated with the provided NodeID
|
2018-10-25 17:11:50 +01:00
|
|
|
func (pool *ConnectionPool) Remove(key string) error {
|
|
|
|
pool.mu.Lock()
|
|
|
|
defer pool.mu.Unlock()
|
|
|
|
pool.cache[key] = nil
|
2018-07-19 15:48:08 +01:00
|
|
|
return nil
|
|
|
|
}
|
2018-10-26 15:07:02 +01:00
|
|
|
|
|
|
|
// Disconnect closes the connection to the node and removes it from the connection pool
|
|
|
|
func (pool *ConnectionPool) Disconnect() error {
|
|
|
|
var err error
|
|
|
|
var errs []error
|
|
|
|
for k, v := range pool.cache {
|
|
|
|
conn, ok := v.(interface{ Close() error })
|
|
|
|
if !ok {
|
|
|
|
err = Error.New("connection pool value not a grpc client connection")
|
|
|
|
errs = append(errs, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
err = conn.Close()
|
|
|
|
if err != nil {
|
|
|
|
errs = append(errs, Error.Wrap(err))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
err = pool.Remove(k)
|
|
|
|
if err != nil {
|
|
|
|
errs = append(errs, Error.Wrap(err))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return utils.CombineErrors(errs...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Init initializes the cache
|
|
|
|
func (pool *ConnectionPool) Init() {
|
|
|
|
pool.cache = make(map[string]interface{})
|
|
|
|
}
|