postgresql: Configurable max open connections to the database

This commit is contained in:
vishalnayak
2015-10-01 20:11:24 -04:00
parent 614d1e804b
commit bc5ad114e4
3 changed files with 34 additions and 5 deletions

View File

@@ -6,9 +6,9 @@ import (
"strings"
"sync"
"github.com/lib/pq"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
"github.com/lib/pq"
)
func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
@@ -70,11 +70,13 @@ func (b *backend) DB(s logical.Storage) (*sql.DB, error) {
fmt.Errorf("configure the DB connection with config/connection first")
}
var conn string
if err := entry.DecodeJSON(&conn); err != nil {
var connConfig connectionConfig
if err := entry.DecodeJSON(&connConfig); err != nil {
return nil, err
}
conn := connConfig.ConnectionString
// Ensure timezone is set to UTC for all the conenctions
if strings.HasPrefix(conn, "postgres://") || strings.HasPrefix(conn, "postgresql://") {
var err error
@@ -92,7 +94,7 @@ func (b *backend) DB(s logical.Storage) (*sql.DB, error) {
// Set some connection pool settings. We don't need much of this,
// since the request rate shouldn't be high.
b.db.SetMaxOpenConns(2)
b.db.SetMaxOpenConns(connConfig.MaxOpenConnections)
return b.db, nil
}

View File

@@ -17,6 +17,10 @@ func pathConfigConnection(b *backend) *framework.Path {
Type: framework.TypeString,
Description: "DB connection string",
},
"max_open_connections": &framework.FieldSchema{
Type: framework.TypeInt,
Description: "Maximum number of open connections to the database",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
@@ -32,6 +36,11 @@ func (b *backend) pathConnectionWrite(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
connString := data.Get("value").(string)
maxOpenConns := data.Get("max_open_connections").(int)
if maxOpenConns == 0 {
maxOpenConns = 2
}
// Verify the string
db, err := sql.Open("postgres", connString)
if err != nil {
@@ -45,7 +54,10 @@ func (b *backend) pathConnectionWrite(
}
// Store it
entry, err := logical.StorageEntryJSON("config/connection", connString)
entry, err := logical.StorageEntryJSON("config/connection", connectionConfig{
ConnectionString: connString,
MaxOpenConnections: maxOpenConns,
})
if err != nil {
return nil, err
}
@@ -59,6 +71,11 @@ func (b *backend) pathConnectionWrite(
return nil, nil
}
type connectionConfig struct {
ConnectionString string `json:"value"`
MaxOpenConnections int `json:"max_open_connections"`
}
const pathConfigConnectionHelpSyn = `
Configure the connection string to talk to PostgreSQL.
`