-
Notifications
You must be signed in to change notification settings - Fork 507
/
Copy pathloadshed.go
51 lines (42 loc) · 1.06 KB
/
loadshed.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
package server
import (
"net"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"www.velocidex.com/golang/velociraptor/utils"
)
var (
loadshedCounter = promauto.NewCounter(prometheus.CounterOpts{
Name: "frontend_loadshed_count",
Help: "Number of connections rejected due to load shedding.",
})
)
type LoadSheddingListener struct {
net.Listener
throttler *utils.Throttler
}
func (self *LoadSheddingListener) Accept() (net.Conn, error) {
for {
res, err := self.Listener.Accept()
if err != nil {
return res, err
}
if self.throttler == nil || self.throttler.Ready() {
return res, err
}
// We are not ready to accept new connections, close
// this one and try again later.
loadshedCounter.Inc()
res.Close()
}
}
func (self *Server) NewLoadSheddingListener(addr string) (*LoadSheddingListener, error, func() error) {
ln, err := net.Listen("tcp", addr)
if err != nil {
return nil, err, nil
}
return &LoadSheddingListener{
Listener: ln,
throttler: self.throttler,
}, err, ln.Close
}