Debian Codegraph @

util/redialer.go

raw
1 /*
2 Copyright 2013-2014 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 // Package util contains the redialer.
18 package util
19
20 import (
21 "sync"
22 "time"
23 )
24
25 // A Dialer is an object that knows how to establish a connection, and
26 // where you'd usually want some kind of backoff if that connection
27 // fails.
28 type Dialer interface {
29 Dial() error
30 }
31
32 // A Jitterer is a Dialer that wants to vary the backoff a little (to avoid a
33 // thundering herd, for example).
34 type Jitterer interface {
35 Dialer
36 Jitter(time.Duration) time.Duration
37 }
38
39 // The timeouts used during backoff.
40 var timeouts []time.Duration
41 var trwlock sync.RWMutex
42
43 // Retrieve the list of timeouts used for exponential backoff.
44 func Timeouts() []time.Duration {
45 trwlock.RLock()
46 defer trwlock.RUnlock()
47 return timeouts
48 }
49
50 // For testing: change the default timeouts with the provided ones,
51 // returning the defaults (the idea being you reset them on test
52 // teardown).
53 func SwapTimeouts(newTimeouts []time.Duration) (oldTimeouts []time.Duration) {
54 trwlock.Lock()
55 defer trwlock.Unlock()
56 oldTimeouts, timeouts = timeouts, newTimeouts
57 return
58 }
59
60 // An AutoRedialer's Redial() method retries its dialer's Dial() method until
61 // it stops returning an error. It does exponential backoff (optionally
62 // jittered).
63 type AutoRedialer interface {
64 Redial() uint32 // Redial keeps on calling Dial until it stops returning an error.
65 Stop() // Stop shuts down the given AutoRedialer, if it is still retrying.
66 }
67
68 type redialerState uint32
69
70 const (
71 Unconfigured redialerState = iota
72 Redialing
73 Stopped
74 )
75
76 func (s *redialerState) String() string {
77 return [3]string{"Unconfigured", "Redialing", "Stopped"}[uint32(*s)]
78 }
79
80 type autoRedialer struct {
81 stateLock sync.RWMutex
82 stateValue redialerState
83 stopping chan struct{}
84 reallyStopped chan struct{}
85 dial func() error
86 jitter func(time.Duration) time.Duration
87 }
88
89 func (ar *autoRedialer) state() redialerState {
90 ar.stateLock.RLock()
91 defer ar.stateLock.RUnlock()
92 return ar.stateValue
93 }
94
95 func (ar *autoRedialer) setState(s redialerState) {
96 ar.stateLock.Lock()
97 defer ar.stateLock.Unlock()
98 ar.stateValue = s
99 }
100
101 func (ar *autoRedialer) setStateIfEqual(oldState, newState redialerState) bool {
102 ar.stateLock.Lock()
103 defer ar.stateLock.Unlock()
104 if ar.stateValue != oldState {
105 return false
106 }
107 ar.stateValue = newState
108 return true
109 }
110
111 func (ar *autoRedialer) setStateStopped() {
112 ar.stateLock.Lock()
113 defer ar.stateLock.Unlock()
114 switch ar.stateValue {
115 case Stopped:
116 return
117 case Unconfigured:
118 close(ar.reallyStopped)
119 }
120 ar.stateValue = Stopped
121 close(ar.stopping)
122 }
123
124 func (ar *autoRedialer) Stop() {
125 if ar != nil {
126 ar.setStateStopped()
127 <-ar.reallyStopped
128 }
129 }
130
131 // Redial keeps on calling Dial until it stops returning an error. It does
132 // exponential backoff, adding back the output of Jitter at each step.
133 func (ar *autoRedialer) Redial() uint32 {
134 if ar == nil {
135 // at least it's better than a segfault...
136 panic("you can't Redial a nil AutoRedialer")
137 }
138 if !ar.setStateIfEqual(Unconfigured, Redialing) {
139 // XXX log this
140 return 0
141 }
142 defer close(ar.reallyStopped)
143
144 var timeout time.Duration
145 var dialAttempts uint32 = 0 // unsigned so it can wrap safely ...
146 timeouts := Timeouts()
147 var numTimeouts uint32 = uint32(len(timeouts))
148 for {
149 if ar.state() != Redialing {
150 return dialAttempts
151 }
152 if ar.dial() == nil {
153 return dialAttempts + 1
154 }
155 if dialAttempts < numTimeouts {
156 timeout = timeouts[dialAttempts]
157 } else {
158 timeout = timeouts[numTimeouts-1]
159 }
160 if ar.jitter != nil {
161 timeout += ar.jitter(timeout)
162 }
163 dialAttempts++
164 select {
165 case <-ar.stopping:
166 case <-time.After(timeout):
167 }
168 }
169 }
170
171 // Returns a stoppable AutoRedialer using the provided Dialer. If the Dialer
172 // is also a Jitterer, the backoff will be jittered.
173 func NewAutoRedialer(dialer Dialer) AutoRedialer {
174 ar := &autoRedialer{
175 stateValue: Unconfigured,
176 dial: dialer.Dial,
177 reallyStopped: make(chan struct{}),
178 stopping: make(chan struct{}),
179 }
180 jitterer, ok := dialer.(Jitterer)
181 if ok {
182 ar.jitter = jitterer.Jitter
183 }
184 return ar
185 }
186
187 func init() {
188 ps := []int{1, 2, 5, 11, 19, 37, 67, 113, 191} // 3 pₙ₊₁ ≥ 5 pₙ
189 timeouts := make([]time.Duration, len(ps))
190 for i, n := range ps {
191 timeouts[i] = time.Duration(n) * time.Second
192 }
193 SwapTimeouts(timeouts)
194 }