/
ping.go
52 lines (43 loc) · 1.32 KB
/
ping.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
package checks
import (
"context"
"net"
"time"
"github.com/pkg/errors"
)
// PingContext verifies a resource is still alive.
// This would normally be a TCP dial check, a db.PingContext() or something similar.
type Pinger interface {
PingContext(ctx context.Context) error
}
// PingContextFunc type is an adapter to allow the use of ordinary functions as Pingers.
type PingContextFunc func(ctx context.Context) error
// PingContext calls f(ctx).
func (f PingContextFunc) PingContext(ctx context.Context) error {
return f(ctx)
}
// NewPingCheck returns a Check that pings using the specified Pinger and fails on timeout or ping failure
func NewPingCheck(name string, pinger Pinger, timeout time.Duration) (Check, error) {
if pinger == nil {
return nil, errors.New("Pinger must not be nil")
}
return &CustomCheck{
CheckName: name,
CheckFunc: func() (details interface{}, err error) {
pingCtx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return nil, pinger.PingContext(pingCtx)
},
}, nil
}
// NewDialPinger returns a Pinger that pings the specified address
func NewDialPinger(network, address string) PingContextFunc {
var d net.Dialer
return func(ctx context.Context) error {
conn, err := d.DialContext(ctx, network, address)
if err == nil {
_ = conn.Close()
}
return err
}
}