-
Notifications
You must be signed in to change notification settings - Fork 171
/
conn.go
72 lines (66 loc) · 1.73 KB
/
conn.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
package sql
import (
"context"
"database/sql"
"github.com/pydio/cells/v4/common/log"
"go.uber.org/zap"
"time"
"github.com/pydio/cells/v4/common/service/metrics"
)
var (
ConnectionOpenTimeout = 60 * time.Second
ConnectionOpenRetries = 10 * time.Second
)
func GetSqlConnection(ctx context.Context, driver string, dsn string) (*sql.DB, error) {
if db, err := sql.Open(driver, dsn); err != nil {
return nil, err
} else {
if err := pingWithRetries(ctx, db); err != nil {
return nil, err
}
computeStats(ctx, db)
return db, nil
}
}
func pingWithRetries(ctx context.Context, db *sql.DB) error {
var lastErr error
if err := db.Ping(); err == nil {
return nil
} else {
lastErr = err
log.Logger(ctx).Warn("[SQL] Server does not answer yet, will retry in 10 seconds...", zap.Error(err))
}
tick := time.NewTicker(ConnectionOpenRetries)
timeout := time.NewTimer(ConnectionOpenTimeout)
defer tick.Stop()
defer timeout.Stop()
for {
select {
case <-tick.C:
if err := db.Ping(); err == nil {
return nil
} else {
lastErr = err
log.Logger(ctx).Warn("[SQL] Server does not answer yet, will retry in 10 seconds...", zap.Error(err))
}
case <-timeout.C:
return lastErr
}
}
}
func computeStats(ctx context.Context, db *sql.DB) {
go func() {
for {
select {
case <-time.After(30 * time.Second):
s := db.Stats()
metrics.GetMetrics().Gauge("db_open_connections").Update(float64(s.OpenConnections))
metrics.GetMetrics().Gauge("db_max_open_connections").Update(float64(s.MaxOpenConnections))
metrics.GetMetrics().Gauge("db_in_use_connections").Update(float64(s.InUse))
metrics.GetMetrics().Gauge("db_idle_connections").Update(float64(s.Idle))
case <-ctx.Done():
return
}
}
}()
}