-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpinger.go
94 lines (81 loc) · 2.23 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
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package apiserver
import (
"time"
"github.com/juju/clock"
"github.com/juju/errors"
"gopkg.in/tomb.v2"
"github.com/juju/juju/apiserver/facade"
"github.com/juju/juju/state"
)
// 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 facade.Resources, authorizer facade.Authorizer) (Pinger, error) {
pingTimeout, ok := resources.Get("pingTimeout").(*pingTimeout)
if !ok {
return nullPinger{}, nil
}
return pingTimeout, nil
}
// pinger describes a resource that can be pinged and stopped.
type Pinger interface {
Ping()
Stop() error
}
// 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()
clock clock.Clock
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(), clock clock.Clock, timeout time.Duration) Pinger {
pt := &pingTimeout{
action: action,
clock: clock,
timeout: timeout,
reset: make(chan struct{}),
}
pt.tomb.Go(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 {
for {
select {
case <-pt.tomb.Dying():
return tomb.ErrDying
case <-pt.reset:
case <-pt.clock.After(pt.timeout):
go pt.action()
return errors.New("ping timeout")
}
}
}
// nullPinger implements the pinger interface but just does nothing
type nullPinger struct{}
func (nullPinger) Ping() {}
func (nullPinger) Stop() error { return nil }