forked from google/go-cloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlhealth.go
100 lines (92 loc) · 2.35 KB
/
sqlhealth.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
// Copyright 2018 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package sqlhealth provides a health check for a SQL database connection.
package sqlhealth // import "github.com/kainoaseto/go-cloud/server/health/sqlhealth"
import (
"context"
"database/sql"
"errors"
"time"
)
// Checker checks the health of a SQL database.
type Checker struct {
cancel context.CancelFunc
stopped <-chan struct{}
healthy bool
}
// New starts a new asynchronous ping of the SQL database. Pings will be sent
// until one succeeds or Stop is called, whichever comes first.
func New(db *sql.DB) *Checker {
// We create a context here because we are detaching.
ctx, cancel := context.WithCancel(context.Background())
stopped := make(chan struct{})
c := &Checker{
cancel: cancel,
stopped: stopped,
}
go func() {
var timer *time.Timer
defer func() {
if timer != nil {
timer.Stop()
}
close(stopped)
}()
wait := 250 * time.Millisecond
const maxWait = 30 * time.Second
for {
if err := db.PingContext(ctx); err == nil {
c.healthy = true
return
}
if timer == nil {
timer = time.NewTimer(wait)
} else {
// Timer already fired, so resetting does not race.
timer.Reset(wait)
}
select {
case <-timer.C:
if wait < maxWait {
// Back off next ping.
wait *= 2
if wait > maxWait {
wait = maxWait
}
}
case <-ctx.Done():
return
}
}
}()
return c
}
// CheckHealth returns nil iff the ping started by New has returned
// success.
func (c *Checker) CheckHealth() error {
select {
case <-c.stopped:
if !c.healthy {
return errors.New("ping stopped before becoming healthy")
}
return nil
default:
return errors.New("still pinging database")
}
}
// Stop stops any ongoing ping of the database.
func (c *Checker) Stop() {
c.cancel()
<-c.stopped
}