-
Notifications
You must be signed in to change notification settings - Fork 300
/
heartbeat.go
255 lines (204 loc) · 5.51 KB
/
heartbeat.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package kite
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/cenkalti/backoff"
"github.com/koding/kite/protocol"
)
type heartbeatReq struct {
ping func() error
interval time.Duration
}
func newHeartbeatReq(r *Request) (*heartbeatReq, error) {
if r.Args == nil {
return nil, errors.New("empty heartbeat request")
}
args, err := r.Args.SliceOfLength(2)
if err != nil {
return nil, err
}
d, err := args[0].Float64()
if err != nil {
return nil, err
}
ping, err := args[1].Function()
if err != nil {
return nil, err
}
return &heartbeatReq{
interval: time.Duration(d) * time.Second,
ping: func() error {
return ping.Call()
},
}, nil
}
func (k *Kite) processHeartbeats() {
var (
ping func() error
t = time.NewTicker(time.Second) // dummy initial value
)
t.Stop()
for {
select {
case <-t.C:
switch err := ping(); err {
case nil:
case errRegisterAgain:
t.Stop()
default:
k.Log.Error("%s", err)
}
case <-k.closeC:
t.Stop()
return
case req := <-k.heartbeatC:
t.Stop()
if req == nil {
continue
}
t = time.NewTicker(req.interval)
ping = req.ping
}
}
}
// RegisterHTTPForever is just like RegisterHTTP however it first tries to
// register forever until a response from kontrol is received. It's useful to
// use it during app initializations. After the registration a reconnect is
// automatically handled inside the RegisterHTTP method.
func (k *Kite) RegisterHTTPForever(kiteURL *url.URL) {
// Create the httpBackoffRegister that RegisterHTTPForever will
// use to backoff repeated register attempts.
httpRegisterBackOff := backoff.NewExponentialBackOff()
httpRegisterBackOff.InitialInterval = 30 * time.Second
httpRegisterBackOff.MaxInterval = 5 * time.Minute
httpRegisterBackOff.Multiplier = 1.7
httpRegisterBackOff.MaxElapsedTime = 0
register := func() error {
_, err := k.RegisterHTTP(kiteURL)
if err != nil {
k.Log.Error("Cannot register to Kontrol: %s Will retry after %d seconds",
err,
httpRegisterBackOff.NextBackOff()/time.Second)
return err
}
return nil
}
// this will retry register forever
err := backoff.Retry(register, httpRegisterBackOff)
if err != nil {
k.Log.Error("BackOff stopped retrying with Error '%s'", err)
}
}
func (k *Kite) getKontrolPath(path string) string {
heartbeatURL := k.Config.KontrolURL + "/" + path
if strings.HasSuffix(k.Config.KontrolURL, "/kite") {
heartbeatURL = strings.TrimSuffix(k.Config.KontrolURL, "/kite") + "/" + path
}
return heartbeatURL
}
// RegisterHTTP registers current Kite to Kontrol. After registration other Kites
// can find it via GetKites() or WatchKites() method. It registers again if
// connection to kontrol is lost.
func (k *Kite) RegisterHTTP(kiteURL *url.URL) (*registerResult, error) {
registerURL := k.getKontrolPath("register")
args := protocol.RegisterArgs{
URL: kiteURL.String(),
Kite: k.Kite(),
Auth: &protocol.Auth{
Type: "kiteKey",
Key: k.KiteKey(),
},
}
data, err := json.Marshal(&args)
if err != nil {
return nil, err
}
resp, err := k.Config.Client.Post(registerURL, "application/json", bytes.NewReader(data))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var rr protocol.RegisterResult
if err := json.NewDecoder(resp.Body).Decode(&rr); err != nil {
return nil, err
}
if rr.Error != "" {
return nil, errors.New(rr.Error)
}
if rr.HeartbeatInterval == 0 {
return nil, errors.New("heartbeat interval cannot be zero")
}
parsed, err := url.Parse(rr.URL)
if err != nil {
k.Log.Error("Cannot parse registered URL: %s", err.Error())
}
heartbeat := time.Duration(rr.HeartbeatInterval) * time.Second
k.Log.Info("Registered (via HTTP) with URL: '%s' and HeartBeat interval: '%s'",
rr.URL, heartbeat)
go k.sendHeartbeats(heartbeat, kiteURL)
k.callOnRegisterHandlers(&rr)
return ®isterResult{parsed}, nil
}
var errRegisterAgain = errors.New("register again")
func (k *Kite) sendHeartbeats(interval time.Duration, kiteURL *url.URL) {
heartbeatURL := k.getKontrolPath("heartbeat")
k.Log.Debug("Starting to send heartbeat to: %s", heartbeatURL)
u, err := url.Parse(heartbeatURL)
if err != nil {
k.Log.Fatal("HeartbeatURL is malformed: %s", err)
}
q := u.Query()
q.Set("id", k.Id)
u.RawQuery = q.Encode()
heartbeatFunc := func() error {
k.Log.Debug("Sending heartbeat to %s", u)
resp, err := k.Config.Client.Get(u.String())
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
// we are just receiving small size strings such as "pong",
// "registeragain" so we limit the reader to read just that
p, err := ioutil.ReadAll(io.LimitReader(resp.Body, 16))
if err != nil {
return err
}
p = bytes.TrimSpace(p)
k.Log.Debug("Heartbeat response received %q", p)
switch string(p) {
case "pong":
return nil
case "registeragain":
k.Log.Info("Disconnected from Kontrol, going to register again")
go func() {
k.RegisterHTTPForever(kiteURL)
}()
return errRegisterAgain
}
return fmt.Errorf("malformed heartbeat response: %s", p)
}
k.heartbeatC <- &heartbeatReq{
ping: heartbeatFunc,
interval: interval,
}
}
// handleHeartbeat pings the callback with the given interval seconds.
func (k *Kite) handleHeartbeat(r *Request) (interface{}, error) {
req, err := newHeartbeatReq(r)
if err != nil {
return nil, err
}
k.heartbeatC <- req
return nil, req.ping()
}