From 01bd8152f776350c699128169da088957f271f8f Mon Sep 17 00:00:00 2001 From: "Aeneas Rekkas (arekkas)" Date: Fri, 13 Jan 2017 11:38:39 +0100 Subject: [PATCH] sql: limit maximum open connections, document timeout options through DSN - closes #359 --- config/backend_connections.go | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/config/backend_connections.go b/config/backend_connections.go index 1cbad76ddbf..e08b30d4c2f 100644 --- a/config/backend_connections.go +++ b/config/backend_connections.go @@ -19,6 +19,7 @@ import ( r "gopkg.in/dancannon/gorethink.v2" "gopkg.in/redis.v5" "strings" + "runtime" ) type MemoryConnection struct{} @@ -53,9 +54,54 @@ func (c *SQLConnection) GetDatabase() *sqlx.DB { logrus.Fatalf("Could not connect to SQL: %s", err) } + + + maxConns := maxParallelism() * 2 + if v := c.URL.Query().Get("max_conns"); v != "" { + s, err := strconv.ParseInt(v, 10, 64) + if err != nil { + logrus.Warnf("max_conns value %s could not be parsed to int: %s", v, err) + } else { + maxConns = int(s) + } + } + + maxIdleConns := maxParallelism() + if v := c.URL.Query().Get("max_idle_conns"); v != "" { + s, err := strconv.ParseInt(v, 10, 64) + if err != nil { + logrus.Warnf("max_idle_conns value %s could not be parsed to int: %s", v, err) + } else { + maxIdleConns = int(s) + } + } + + maxConnLifetime := time.Duration(0) + if v := c.URL.Query().Get("max_idle_conns"); v != "" { + s, err := time.ParseDuration(maxConnLifetime) + if err != nil { + logrus.Warnf("max_idle_conns value %s could not be parsed to int: %s", v, err) + } else { + maxConnLifetime = s + } + } + + c.db.SetMaxOpenConns(maxConns) + c.db.SetMaxIdleConns(maxIdleConns) + c.db.SetConnMaxLifetime(maxConnLifetime) + return c.db } +func maxParallelism() int { + maxProcs := runtime.GOMAXPROCS(0) + numCPU := runtime.NumCPU() + if maxProcs < numCPU { + return maxProcs + } + return numCPU +} + type RethinkDBConnection struct { session *r.Session URL *url.URL