forked from kedacore/http-add-on
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue_pinger.go
259 lines (239 loc) · 6.08 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
// This file contains the implementation for the HTTP request queue used by the
// KEDA external scaler implementation
package main
import (
"context"
"fmt"
"net/http"
"sync"
"time"
"github.com/go-logr/logr"
"golang.org/x/sync/errgroup"
"github.com/kedacore/http-add-on/pkg/k8s"
"github.com/kedacore/http-add-on/pkg/queue"
)
type PingerStatus int32
const (
PingerUNKNOWN PingerStatus = 0
PingerACTIVE PingerStatus = 1
PingerERROR PingerStatus = 2
)
// 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
interceptorServiceName string
adminPort string
pingMut *sync.RWMutex
lastPingTime time.Time
allCounts map[string]queue.Count
lggr logr.Logger
status PingerStatus
}
func newQueuePinger(
lggr logr.Logger,
getEndpointsFn k8s.GetEndpointsFunc,
ns,
svcName,
deplName,
adminPort string,
) *queuePinger {
pingMut := new(sync.RWMutex)
pinger := &queuePinger{
getEndpointsFn: getEndpointsFn,
interceptorNS: ns,
interceptorSvcName: svcName,
interceptorServiceName: deplName,
adminPort: adminPort,
pingMut: pingMut,
lggr: lggr,
allCounts: map[string]queue.Count{},
}
return pinger
}
// start starts the queuePinger
func (q *queuePinger) start(
ctx context.Context,
ticker *time.Ticker,
endpCache k8s.EndpointsCache,
) error {
endpoWatchIface, err := endpCache.Watch(q.interceptorNS, q.interceptorServiceName)
if err != nil {
return err
}
endpEvtChan := endpoWatchIface.ResultChan()
defer endpoWatchIface.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",
)
q.status = PingerERROR
return fmt.Errorf("context marked done. stopping queuePinger loop: %w", ctx.Err())
// do our regularly scheduled work
case <-ticker.C:
err := q.fetchAndSaveCounts(ctx)
if err != nil {
lggr.Error(err, "getting request counts")
}
// handle changes to the interceptor fleet
// Endpoints
case <-endpEvtChan:
err := q.fetchAndSaveCounts(ctx)
if err != nil {
lggr.Error(
err,
"getting request counts after interceptor endpoints event",
)
}
}
}
}
func (q *queuePinger) counts() map[string]queue.Count {
q.pingMut.RLock()
defer q.pingMut.RUnlock()
return q.allCounts
}
// 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, err := fetchCounts(
ctx,
q.lggr,
q.getEndpointsFn,
q.interceptorNS,
q.interceptorSvcName,
q.adminPort,
)
if err != nil {
q.lggr.Error(err, "getting request counts")
q.status = PingerERROR
return err
}
q.status = PingerACTIVE
q.allCounts = counts
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]queue.Count, error) {
lggr = lggr.WithName("queuePinger.requestCounts")
endpointURLs, err := k8s.EndpointsForService(
ctx,
ns,
svcName,
adminPort,
endpointsFn,
)
if err != nil {
return nil, err
}
if len(endpointURLs) == 0 {
return nil, fmt.Errorf("there isn't any valid interceptor endpoint")
}
countsCh := make(chan *queue.Counts)
var wg sync.WaitGroup
fetchGrp, _ := 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(
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, err
}
totalCounts := make(map[string]queue.Count)
// 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 {
var responseCount queue.Count
var ok bool
if responseCount, ok = totalCounts[host]; !ok {
responseCount = queue.Count{}
}
responseCount.Concurrency += val.Concurrency
responseCount.RPS += val.RPS
totalCounts[host] = responseCount
}
}
return totalCounts, nil
}