-
Notifications
You must be signed in to change notification settings - Fork 17
/
client.go
294 lines (261 loc) · 6.32 KB
/
client.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package fastclient
import (
"flag"
"io"
"log"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/valyala/fasthttp"
)
var (
httpClientRequestTimeout = flag.Duration("httpClientRequestTimeout", time.Second*10, "Maximum time to wait for http response")
httpClientKeepAlivePeriod = flag.Duration("httpClientKeepAlivePeriod", time.Second*5, "Interval for sending keep-alive messages"+
"on keepalive connections. Zero disables keep-alive messages")
httpClientReadBufferSize = flag.Int("httpClientReadBufferSize", 8*1024, "Per-connection read buffer size for httpclient")
httpClientWriteBufferSize = flag.Int("httpClientWriteBufferSize", 8*1024, "Per-connection write buffer size for httpclient")
)
const (
jobCapacity = 10000
maxIdleConnDuration = time.Second
maxConns = 1<<31 - 1
)
func init() {
registerMetrics()
}
// Client is a wrapper for fasthttp.HostClient
// It allows to send requests and collect metrics while sending
type Client struct {
// Jobsch is a channel of tasks(requests) which should be done
Jobsch chan struct{}
*fasthttp.HostClient
wg sync.WaitGroup
request *fasthttp.Request
successStatusCode int
sync.Mutex
workers int
statusCodeLabels map[int]prometheus.Labels
errorMessages map[string]prometheus.Labels
}
// New creates new client
func New(request *fasthttp.Request, timeout time.Duration, sc int) *Client {
flushMetrics()
addr, isTLS := acquireAddr(request)
return &Client{
Jobsch: make(chan struct{}, jobCapacity),
request: request,
statusCodeLabels: make(map[int]prometheus.Labels),
errorMessages: make(map[string]prometheus.Labels),
successStatusCode: sc,
HostClient: &fasthttp.HostClient{
Addr: addr,
IsTLS: isTLS,
Dial: dial,
MaxIdleConnDuration: maxIdleConnDuration,
MaxConns: maxConns,
ReadTimeout: timeout,
WriteTimeout: timeout,
},
}
}
// Amount return number of created workers
// after Flush() workers would flushed too
func (c *Client) Amount() int {
c.Lock()
defer c.Unlock()
return c.workers
}
// Overflow return length of job-channel
// after calling Flush(), channel would flushed too
func (c *Client) Overflow() int {
c.Lock()
defer c.Unlock()
return len(c.Jobsch)
}
func drainChan(ch chan struct{}) {
for {
select {
case <-ch:
continue
default:
return
}
}
}
// Flush dropping out and re-init all counters and metrics
func (c *Client) Flush() {
drainChan(c.Jobsch)
close(c.Jobsch)
c.wg.Wait()
flushMetrics()
c.workers = 0
c.Jobsch = make(chan struct{}, jobCapacity)
}
// RunWorkers runs n goroutines to serve jobs from Jobsch
func (c *Client) RunWorkers(n int) {
if n < 1 {
n = 1
}
for i := 0; i < n; i++ {
c.wg.Add(1)
go func() {
c.Lock()
c.workers++
c.Unlock()
c.run()
c.wg.Done()
}()
}
}
func (c *Client) run() {
var resp fasthttp.Response
r := new(fasthttp.Request)
c.request.CopyTo(r)
for range c.Jobsch {
s := time.Now()
err := c.Do(r, &resp)
if err != nil {
if err == fasthttp.ErrTimeout {
timeouts.Inc()
}
errors.Inc()
c.withErrorMessage(err.Error()).Inc()
}
sc := resp.StatusCode()
if c.successStatusCode == sc {
requestSuccess.Inc()
}
c.withStatusCode(sc).Inc()
requestDuration.Observe(float64(time.Since(s).Seconds()))
requestSum.Inc()
}
}
func (c *Client) withStatusCode(code int) prometheus.Counter {
var label prometheus.Labels
var ok bool
c.Lock()
if label, ok = c.statusCodeLabels[code]; !ok {
label = prometheus.Labels{"code": strconv.Itoa(code)}
c.statusCodeLabels[code] = label
}
c.Unlock()
return statusCodes.With(label)
}
func (c *Client) withErrorMessage(msg string) prometheus.Counter {
var label prometheus.Labels
var ok bool
c.Lock()
if label, ok = c.errorMessages[msg]; !ok {
label = prometheus.Labels{"message": msg}
c.errorMessages[msg] = label
}
c.Unlock()
return errorMessages.With(label)
}
type hostConn struct {
net.Conn
addr string
closed uint32
connOpen prometheus.Gauge
readError prometheus.Counter
writeError prometheus.Counter
bytesWritten prometheus.Counter
bytesRead prometheus.Counter
}
func dial(addr string) (net.Conn, error) {
conn, err := fasthttp.DialTimeout(addr, *httpClientRequestTimeout)
if err != nil {
return nil, err
}
if err = setupTCPConn(conn); err != nil {
connError.Inc()
conn.Close()
return nil, err
}
connOpen.Inc()
return &hostConn{
Conn: conn,
addr: addr,
connOpen: connOpen,
readError: readError,
writeError: writeError,
bytesWritten: bytesWritten,
bytesRead: bytesRead,
}, nil
}
func setupTCPConn(conn net.Conn) error {
c, ok := conn.(*net.TCPConn)
if !ok {
return nil
}
var err error
if *httpClientReadBufferSize > 0 {
if err = c.SetReadBuffer(*httpClientReadBufferSize); err != nil {
return err
}
}
if *httpClientWriteBufferSize > 0 {
if err = c.SetWriteBuffer(*httpClientWriteBufferSize); err != nil {
return err
}
}
if *httpClientKeepAlivePeriod > 0 {
if err = c.SetKeepAlive(true); err != nil {
return err
}
if err = c.SetKeepAlivePeriod(*httpClientKeepAlivePeriod); err != nil {
return err
}
}
return nil
}
func (hc *hostConn) Close() error {
if atomic.AddUint32(&hc.closed, 1) == 1 {
hc.connOpen.Dec()
}
return hc.Conn.Close()
}
func (hc *hostConn) Write(p []byte) (int, error) {
n, err := hc.Conn.Write(p)
hc.bytesWritten.Add(float64(n))
if err != nil {
hc.writeError.Inc()
}
return n, err
}
func (hc *hostConn) Read(p []byte) (int, error) {
n, err := hc.Conn.Read(p)
hc.bytesRead.Add(float64(n))
if err != nil && err != io.EOF {
hc.readError.Inc()
}
return n, err
}
func acquireAddr(req *fasthttp.Request) (string, bool) {
addr := string(req.URI().Host())
if len(addr) == 0 {
log.Fatalf("address cannot be empty")
}
isTLS := string(req.URI().Scheme()) == "https"
tmp := strings.SplitN(addr, ":", 2)
if len(tmp) != 2 {
port := ":80"
if isTLS {
port = ":443"
}
return tmp[0] + port, isTLS
}
port := tmp[1]
portInt, err := strconv.Atoi(port)
if err != nil {
log.Fatalf("cannot parse port %q of addr %q: %s", port, addr, err)
}
if portInt < 0 {
log.Fatalf("upstreamHosts port %d cannot be negative: %q", portInt, addr)
}
return addr, isTLS
}