forked from kedacore/http-add-on
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathqueue_pinger.go
276 lines (257 loc) · 6.42 KB
/
queue_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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// This file contains the implementation for the HTTP request queue used by the
// KEDA external scaler implementation
package main
import (
"context"
"net/http"
"sync"
"time"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/kedacore/http-add-on/pkg/k8s"
"github.com/kedacore/http-add-on/pkg/queue"
"github.com/kedacore/http-add-on/pkg/routing"
)
// queuePinger has functionality to ping all interceptors
// behind a given `Service`, fetch their pending queue counts,
// and aggregate all of those counts together.
//
// It's capable of doing that work in parallel when possible
// as well.
//
// Sample usage:
//
// pinger, err := newQueuePinger(ctx, lggr, getEndpointsFn, ns, svcName, adminPort)
// if err != nil {
// panic(err)
// }
// // make sure to start the background pinger loop.
// // you can shut this loop down by using a cancellable
// // context
// go pinger.start(ctx, ticker)
type queuePinger struct {
getEndpointsFn k8s.GetEndpointsFunc
interceptorNS string
interceptorSvcName string
interceptorDeplName string
adminPort string
pingMut *sync.RWMutex
lastPingTime time.Time
allCounts map[string]int
aggregateCount int
lggr logr.Logger
}
func newQueuePinger(
ctx context.Context,
lggr logr.Logger,
getEndpointsFn k8s.GetEndpointsFunc,
ns,
svcName,
deplName,
adminPort string,
) (*queuePinger, error) {
pingMut := new(sync.RWMutex)
pinger := &queuePinger{
getEndpointsFn: getEndpointsFn,
interceptorNS: ns,
interceptorSvcName: svcName,
interceptorDeplName: deplName,
adminPort: adminPort,
pingMut: pingMut,
lggr: lggr,
allCounts: map[string]int{},
aggregateCount: 0,
}
return pinger, pinger.fetchAndSaveCounts(ctx)
}
// start starts the queuePinger
func (q *queuePinger) start(
ctx context.Context,
ticker *time.Ticker,
deplCache k8s.DeploymentCache,
) error {
deployWatchIface, err := deplCache.Watch(q.interceptorNS, q.interceptorDeplName)
if err != nil {
return err
}
deployEvtChan := deployWatchIface.ResultChan()
defer deployWatchIface.Stop()
lggr := q.lggr.WithName("scaler.queuePinger.start")
defer ticker.Stop()
for {
select {
// handle cancellations/timeout
case <-ctx.Done():
lggr.Error(
ctx.Err(),
"context marked done. stopping queuePinger loop",
)
return errors.Wrap(
ctx.Err(),
"context marked done. stopping queuePinger loop",
)
// do our regularly scheduled work
case <-ticker.C:
err := q.fetchAndSaveCounts(ctx)
if err != nil {
lggr.Error(err, "getting request counts")
return errors.Wrap(
err,
"error getting request counts",
)
}
// handle changes to the interceptor fleet
// Deployment
case <-deployEvtChan:
err := q.fetchAndSaveCounts(ctx)
if err != nil {
lggr.Error(
err,
"getting request counts after interceptor deployment event",
)
}
}
}
}
func (q *queuePinger) counts() map[string]int {
q.pingMut.RLock()
defer q.pingMut.RUnlock()
return q.allCounts
}
// mergeCountsWithRoutingTable ensures that all hosts in routing table
// are present in combined counts, if count is not present value is set to 0
func (q *queuePinger) mergeCountsWithRoutingTable(
table routing.TableReader,
) map[string]int {
q.pingMut.RLock()
defer q.pingMut.RUnlock()
mergedCounts := make(map[string]int)
for _, host := range table.Hosts() {
mergedCounts[host] = 0
}
for key, value := range q.allCounts {
mergedCounts[key] = value
}
return mergedCounts
}
func (q *queuePinger) aggregate() int {
q.pingMut.RLock()
defer q.pingMut.RUnlock()
return q.aggregateCount
}
// fetchAndSaveCounts calls fetchCounts, and then
// saves them to internal state in q
func (q *queuePinger) fetchAndSaveCounts(ctx context.Context) error {
q.pingMut.Lock()
defer q.pingMut.Unlock()
counts, agg, err := fetchCounts(
ctx,
q.lggr,
q.getEndpointsFn,
q.interceptorNS,
q.interceptorSvcName,
q.adminPort,
)
if err != nil {
q.lggr.Error(err, "getting request counts")
return err
}
q.allCounts = counts
q.aggregateCount = agg
q.lastPingTime = time.Now()
return nil
}
// fetchCounts fetches all counts from every endpoint returned
// by endpointsFn for the given service named svcName on the
// port adminPort, in namespace ns.
//
// Requests to fetch endpoints are made concurrently and
// aggregated when all requests return successfully.
//
// Upon any failure, a non-nil error is returned and the
// other two return values are nil and 0, respectively.
func fetchCounts(
ctx context.Context,
lggr logr.Logger,
endpointsFn k8s.GetEndpointsFunc,
ns,
svcName,
adminPort string,
) (map[string]int, int, error) {
lggr = lggr.WithName("queuePinger.requestCounts")
endpointURLs, err := k8s.EndpointsForService(
ctx,
ns,
svcName,
adminPort,
endpointsFn,
)
if err != nil {
return nil, 0, err
}
countsCh := make(chan *queue.Counts)
var wg sync.WaitGroup
fetchGrp, ctx := errgroup.WithContext(ctx)
for _, endpoint := range endpointURLs {
// capture the endpoint in a loop-local
// variable so that the goroutine can
// use it
u := endpoint
// have the errgroup goroutine send to
// a "private" goroutine, which we'll
// then forward on to countsCh
ch := make(chan *queue.Counts)
wg.Add(1)
fetchGrp.Go(func() error {
counts, err := queue.GetCounts(
ctx,
lggr,
http.DefaultClient,
*u,
)
if err != nil {
lggr.Error(
err,
"getting queue counts from interceptor",
"interceptorAddress",
u.String(),
)
return err
}
ch <- counts
return nil
})
// forward the "private" goroutine
// on to countsCh separately
go func() {
defer wg.Done()
res := <-ch
countsCh <- res
}()
}
// close countsCh after all goroutines are done sending
// to their "private" channels, so that we can range
// over countsCh normally below
go func() {
wg.Wait()
close(countsCh)
}()
if err := fetchGrp.Wait(); err != nil {
lggr.Error(err, "fetching all counts failed")
return nil, 0, err
}
// consume the results of the counts channel
agg := 0
totalCounts := make(map[string]int)
// range through the result of each endpoint
for count := range countsCh {
// each endpoint returns a map of counts, one count
// per host. add up the counts for each host
for host, val := range count.Counts {
agg += val
totalCounts[host] += val
}
}
return totalCounts, agg, nil
}