-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
164 lines (131 loc) · 3.83 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package db
import (
"agent/config"
"agent/logger"
"database/sql"
"log"
nurl "net/url"
"os"
"strings"
"sync"
_ "github.com/jackc/pgx/v4/stdlib"
)
// Separating the sensitive client and URL state from the message struct below
// to ensure the URL and client are not leaked to other packages
type PostgresClient struct {
// DB client
client *Client
serverID *ServerID
// ex. postgres://<user>:<pass>@<host>:<port>/<db>
url string
// ex host from url
host string
platform string
maxConnections int64
version string
pgBouncerEnabled *bool
pgBouncerMaxServerConnections int64
pgBouncerVersion string
}
type Client struct {
config config.Config
conn *sql.DB
dbURL string
mu *sync.Mutex
}
func BuildPostgresClients(config config.Config) []*PostgresClient {
var postgresClients []*PostgresClient
for _, e := range os.Environ() {
configVar := strings.SplitN(e, "=", 2)
if strings.HasSuffix(configVar[0], "_URL") && strings.HasPrefix(configVar[1], "postgres://") {
postgresClient := NewPostgresClient(config, configVar)
postgresClients = append(postgresClients, postgresClient)
}
}
return postgresClients
}
func NewPostgresClient(config config.Config, configVar []string) *PostgresClient {
varName := configVar[0]
url := configVar[1]
// support both HEROKU_POSTGRESQL_BLUE_URL and BLUE_URL config vars
configName := strings.ReplaceAll(varName, "HEROKU_POSTGRESQL_", "")
configName = strings.ReplaceAll(configName, "_URL", "")
urlParts := strings.Split(url, "/")
database := urlParts[len(urlParts)-1]
var host string
parsedUrl, err := nurl.Parse(url)
if err != nil {
log.Println("Invalid URL!")
host = ""
} else {
hostAndPort := strings.Split(parsedUrl.Host, ":")
host = hostAndPort[0]
}
// set application name for db connections
url += "?application_name=postgres-monitor-agent"
url += "&statement_cache_mode=describe" // don't use prepared statements since pgbouncer doesn't support it
return &PostgresClient{
client: NewClient(config, url),
serverID: &ServerID{
ConfigName: configName,
ConfigVarName: varName,
Database: database,
},
url: url,
host: host,
}
}
func NewClient(config config.Config, dbURL string) *Client {
return &Client{
config: config,
conn: NewConn(dbURL, true),
dbURL: dbURL,
mu: &sync.Mutex{},
}
}
func NewConn(dbURL string, testPing bool) *sql.DB {
conn, err := sql.Open("pgx", dbURL)
// test connection
if err != nil {
logger.Error("Unable to connect to database", "err", err)
return nil
}
// restrict to a single connection to prevent opening too many connections
conn.SetMaxOpenConns(1)
// test connection - doesn't work with pgbouncer so make it configurable
if testPing {
if err := conn.Ping(); err != nil {
logger.Error("Unable to connect to database", "err", err)
return nil
}
}
return conn
}
func (c *PostgresClient) SetPgBouncerEnabled(enabled bool) {
c.pgBouncerEnabled = &enabled
}
// wrap pgx Query with mutex to ensure only one active connection is used at one time
func (c *Client) Query(query string) (*sql.Rows, error) {
c.mu.Lock()
defer c.mu.Unlock()
query = CleanQuery(query)
// We were seeing not all rows being returned by pgx - ex. FindIndexes was only returning 83 indexes
// vs the 304 indexes that we were seeing in psql. Standard database/sql worked correctly when using pgx
// as the backing driver.
return c.conn.Query(query)
}
// wrap pgx QueryRow with mutex to ensure only one active connection is used at a time
func (c *Client) QueryRow(query string) *sql.Row {
c.mu.Lock()
defer c.mu.Unlock()
query = CleanQuery(query)
return c.conn.QueryRow(query)
}
// should only be used for very specific use cases
// ex. raising a test log message
func (c *Client) Exec(query string) error {
c.mu.Lock()
defer c.mu.Unlock()
_, err := c.conn.Exec(query)
return err
}