-
Notifications
You must be signed in to change notification settings - Fork 0
/
pinger.go
113 lines (97 loc) · 2.5 KB
/
pinger.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
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package apiserver
import (
"errors"
"time"
"launchpad.net/tomb"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/state"
)
func init() {
common.RegisterStandardFacade("Pinger", 0, NewPinger)
}
// NewPinger returns an object that can be pinged by calling its Ping method.
// If this method is not called frequently enough, the connection will be
// dropped.
func NewPinger(
st *state.State, resources *common.Resources, authorizer common.Authorizer,
) (
pinger, error,
) {
pingTimeout, ok := resources.Get("pingTimeout").(*pingTimeout)
if !ok {
return nullPinger{}, nil
}
return pingTimeout, nil
}
// pinger describes a type that can be pinged.
type pinger interface {
Ping()
}
// pingTimeout listens for pings and will call the
// passed action in case of a timeout. This way broken
// or inactive connections can be closed.
type pingTimeout struct {
tomb tomb.Tomb
action func()
timeout time.Duration
reset chan struct{}
}
// newPingTimeout returns a new pingTimeout instance
// that invokes the given action asynchronously if there
// is more than the given timeout interval between calls
// to its Ping method.
func newPingTimeout(action func(), timeout time.Duration) *pingTimeout {
pt := &pingTimeout{
action: action,
timeout: timeout,
reset: make(chan struct{}),
}
go func() {
defer pt.tomb.Done()
pt.tomb.Kill(pt.loop())
}()
return pt
}
// Ping is used by the client heartbeat monitor and resets
// the killer.
func (pt *pingTimeout) Ping() {
select {
case <-pt.tomb.Dying():
case pt.reset <- struct{}{}:
}
}
// Stop terminates the ping timeout.
func (pt *pingTimeout) Stop() error {
pt.tomb.Kill(nil)
return pt.tomb.Wait()
}
// loop waits for a reset signal, otherwise it performs
// the initially passed action.
func (pt *pingTimeout) loop() error {
timer := newTimer(pt.timeout)
defer timer.Stop()
for {
select {
case <-pt.tomb.Dying():
return nil
case <-timer.C:
go pt.action()
return errors.New("ping timeout")
case <-pt.reset:
resetTimer(timer, pt.timeout)
}
}
}
// newTimer is patched out during some tests.
var newTimer = func(d time.Duration) *time.Timer {
return time.NewTimer(d)
}
// resetTimer is patched out during some tests.
var resetTimer = func(timer *time.Timer, d time.Duration) bool {
return timer.Reset(d)
}
// nullPinger implements the pinger interface but just does nothing
type nullPinger struct{}
func (nullPinger) Ping() {}