-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
355 lines (296 loc) · 8.27 KB
/
main.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package main
import (
"context"
"crypto/rand"
"crypto/tls"
"fmt"
"io"
"log/slog"
"math/big"
"net"
"net/http"
"net/http/httptrace"
"net/url"
"os"
"os/signal"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
workersCount = 1
logsLevel = slog.LevelInfo
requestIntervalInMS = 100
)
var client *http.Client
func initClient() {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxConnsPerHost = 64
transport.MaxIdleConnsPerHost = 8
transport.TLSClientConfig.MinVersion = tls.VersionTLS12 // maybe this is broken too ?
// force to use http2...
transport.TLSClientConfig.NextProtos = []string{"h2"}
transport.TLSClientConfig.KeyLogWriter = os.Stdout
client = &http.Client{
Transport: transport,
Timeout: 3 * time.Second,
}
}
var logger *slog.Logger
var logFile *os.File
func logsToFile() bool {
if os.Getenv("KUBERNETES_SERVICE_HOST") != "" {
// inside pod
return true
}
return false
}
func initLogger() {
stderrLogHandler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: logsLevel,
AddSource: true,
})
if logsToFile() {
f, err := os.OpenFile("/logs/log.json", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
panic(err)
}
logFile = f
jsonFileLoggerHandler := slog.NewJSONHandler(logFile, &slog.HandlerOptions{
Level: slog.LevelWarn,
AddSource: true,
})
logger = slog.New(MultiLogHandler(stderrLogHandler, jsonFileLoggerHandler))
} else {
logger = slog.New(stderrLogHandler)
}
}
var requestID int64
func nextRequestID() string {
nextID := atomic.AddInt64(&requestID, 1)
return fmt.Sprintf("%d", nextID)
}
func randInt(n int64) int64 {
rn, err := rand.Int(rand.Reader, big.NewInt(n))
if err != nil {
panic("failed to generate random number")
}
return rn.Int64()
}
func doRequest(ctx context.Context, workerId string) {
requestLogger := logger.With("req.id", nextRequestID(), "worker.id", workerId)
start := time.Now()
defer func() {
requestLogger.Debug("request duration", slog.Duration("duration", time.Since(start)))
}()
const tokenURL = "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/oauth2/token?api-version=1.0"
// NOTE: we don't care about the response
input := url.Values{}
input.Add("grant_type", "client_credentials")
input.Add("client_id", "fake-client-id")
input.Add("client_secret", "fake-client-secret")
input.Add("resource", "https://management.azure.com")
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
tokenURL,
strings.NewReader(input.Encode()),
)
if err != nil {
requestLogger.ErrorContext(ctx, "failed to create request", slog.String("error", err.Error()))
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
respStatusCode := 0
if resp != nil {
respStatusCode = resp.StatusCode
}
requestLogger.Error("failed to do request", slog.String("error", err.Error()), slog.Int("status", respStatusCode))
return
}
// "error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier 'fake-client-id' was not found in the directory 'Microsoft'
_, err = io.ReadAll(resp.Body) // drain the body to make a full request
if err != nil {
requestLogger.Error("failed to read response body", slog.String("error", err.Error()), slog.Int("status", resp.StatusCode))
return
}
requestLogger.Debug("request done", slog.Int("status", resp.StatusCode))
}
type ConnInfo struct {
conn net.Conn
protocol string
created time.Time
lastUsed time.Time
}
func main() {
initLogger()
defer func() {
if logFile != nil {
_ = logFile.Close()
}
}()
initClient()
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
bookkeepMutex := new(sync.Mutex)
connMaps := make(map[string]*ConnInfo)
bookkeepConn := func(connInfo httptrace.GotConnInfo, tlsState *tls.ConnectionState) {
bookkeepMutex.Lock()
defer bookkeepMutex.Unlock()
conn := connInfo.Conn
key := fmt.Sprintf("%s:%s", conn.RemoteAddr().String(), conn.LocalAddr().String())
if connInfo.Reused {
logger.Debug("reused connection", slog.String("key", key))
_, ok := connMaps[key]
if !ok {
// this happen if the connection is using http/1.1
logger.Debug("reused connection not found", slog.String("key", key))
return
}
connMaps[key].lastUsed = time.Now()
return
}
protocol := "unknown"
if tlsState != nil {
protocol = tlsState.NegotiatedProtocol
if protocol == "" {
logger.Info("closing non-h2 connection")
// http 1.1 we don't want that
if err := conn.Close(); err != nil {
logger.Error("failed to close connection", slog.String("error", err.Error()))
}
return
}
}
logger.Info("new connection", slog.String("key", key), slog.String("protocol", protocol))
connMaps[key] = &ConnInfo{
conn: conn,
protocol: protocol,
created: time.Now(),
lastUsed: time.Now(),
}
}
ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
GotConn: func(info httptrace.GotConnInfo) {
},
TLSHandshakeDone: func(cs tls.ConnectionState, err error) {
if err != nil {
logger.Error("tls handshake done with error", slog.String("error", err.Error()))
return
}
logger.Info("tls handshake done", slog.String("protocol", cs.NegotiatedProtocol))
},
})
var requestTimes int64
wg := new(sync.WaitGroup)
for i := 0; i < workersCount; i++ {
wg.Add(1)
go func(workerID string) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
func() {
var gotConnInfo *httptrace.GotConnInfo
var tlsState *tls.ConnectionState
reqCtx := httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
GotConn: func(info httptrace.GotConnInfo) {
gotConnInfo = &info
},
TLSHandshakeDone: func(cs tls.ConnectionState, err error) {
if err != nil {
logger.Error("tls handshake done with error", slog.String("error", err.Error()))
return
}
tlsState = &cs
},
})
doRequest(reqCtx, workerID)
if gotConnInfo != nil {
bookkeepConn(*gotConnInfo, tlsState)
} else {
logger.Error("gotConnInfo is nil")
}
if atomic.AddInt64(&requestTimes, 1)%100 == 0 {
logger.Info("request count", slog.Int("count", int(atomic.LoadInt64(&requestID))))
}
}()
time.Sleep(time.Duration(randInt(requestIntervalInMS)) * time.Millisecond)
}
}
}(fmt.Sprintf("%d", i))
}
<-ctx.Done()
wg.Wait()
for key, connInfo := range connMaps {
logger.Info(
"saw connection",
slog.String("key", key),
slog.String("protocol", connInfo.protocol),
slog.Duration("age", time.Since(connInfo.created)),
slog.Duration("lastUsed", time.Since(connInfo.lastUsed)),
)
}
logger.Info("total connection count", slog.Int("count", len(connMaps)))
}
// multiLogHandler is a slog.Handler that sends log records to multiple handlers.
// simplified version of: https://github.com/samber/slog-multi/blob/main/multi.go
type multiLogHandler struct {
handlers []slog.Handler
}
func MultiLogHandler(handlers ...slog.Handler) slog.Handler {
return &multiLogHandler{handlers: handlers}
}
var _ slog.Handler = (*multiLogHandler)(nil)
func (h *multiLogHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, h := range h.handlers {
if h.Enabled(ctx, level) {
return true
}
}
return false
}
func try(f func() error) (retErr error) {
defer func() {
if err := recover(); err != nil {
retErr = fmt.Errorf("panic: %+v", err)
return
}
}()
if err := f(); err != nil {
return err
}
return nil
}
func (h *multiLogHandler) Handle(ctx context.Context, r slog.Record) error {
for i := range h.handlers {
ch := h.handlers[i]
if ch.Enabled(ctx, r.Level) {
if err := try(func() error {
return ch.Handle(ctx, r)
}); err != nil {
return err
}
}
}
return nil
}
func (h *multiLogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
var handlers []slog.Handler
for _, ch := range h.handlers {
handlers = append(handlers, ch.WithAttrs(attrs))
}
return MultiLogHandler(handlers...)
}
func (*multiLogHandler) WithGroup(name string) slog.Handler {
var handlers []slog.Handler
for _, ch := range handlers {
handlers = append(handlers, ch.WithGroup(name))
}
return MultiLogHandler(handlers...)
}