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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
|
package main
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net/http/httptrace"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/request"
)
// RequestLatency provides latencies for the SDK API request and its attempts.
type RequestLatency struct {
Latency time.Duration
Validate time.Duration
Build time.Duration
Attempts []RequestAttemptLatency
}
// RequestAttemptLatency provides latencies for an individual request attempt.
type RequestAttemptLatency struct {
Latency time.Duration
Err error
Sign time.Duration
Send time.Duration
HTTP HTTPLatency
Unmarshal time.Duration
UnmarshalError time.Duration
WillRetry bool
Retry time.Duration
}
// HTTPLatency provides latencies for an HTTP request.
type HTTPLatency struct {
Latency time.Duration
ConnReused bool
GetConn time.Duration
DNS time.Duration
Connect time.Duration
TLS time.Duration
WriteHeader time.Duration
WriteRequest time.Duration
WaitResponseFirstByte time.Duration
ReadHeader time.Duration
ReadBody time.Duration
}
// RequestTrace provides the structure to store SDK request attempt latencies.
// Use TraceRequest as a API operation request option to capture trace metrics
// for the individual request.
type RequestTrace struct {
Start, Finish time.Time
ValidateStart, ValidateDone time.Time
BuildStart, BuildDone time.Time
ReadResponseBody bool
Attempts []*RequestAttemptTrace
}
// Latency returns the latencies of the request trace components.
func (t RequestTrace) Latency() RequestLatency {
var attempts []RequestAttemptLatency
for _, a := range t.Attempts {
attempts = append(attempts, a.Latency())
}
latency := RequestLatency{
Latency: safeTimeDelta(t.Start, t.Finish),
Validate: safeTimeDelta(t.ValidateStart, t.ValidateDone),
Build: safeTimeDelta(t.BuildStart, t.BuildDone),
Attempts: attempts,
}
return latency
}
// TraceRequest is a SDK request Option that will add request handlers to an
// individual request to track request latencies per attempt. Must be used only
// for a single request call per RequestTrace value.
func (t *RequestTrace) TraceRequest(r *request.Request) {
t.Start = time.Now()
r.Handlers.Complete.PushBack(t.onComplete)
r.Handlers.Validate.PushFront(t.onValidateStart)
r.Handlers.Validate.PushBack(t.onValidateDone)
r.Handlers.Build.PushFront(t.onBuildStart)
r.Handlers.Build.PushBack(t.onBuildDone)
var attempt *RequestAttemptTrace
// Signing and Start attempt
r.Handlers.Sign.PushFront(func(rr *request.Request) {
attempt = &RequestAttemptTrace{Start: time.Now()}
attempt.SignStart = attempt.Start
})
r.Handlers.Sign.PushBack(func(rr *request.Request) {
attempt.SignDone = time.Now()
})
// Ensure that the http trace added to the request always uses the original
// context instead of each following attempt's context to prevent conflict
// with previous http traces used.
origContext := r.Context()
// Send
r.Handlers.Send.PushFront(func(rr *request.Request) {
attempt.SendStart = time.Now()
attempt.HTTPTrace = NewHTTPTrace(origContext)
rr.SetContext(attempt.HTTPTrace)
})
r.Handlers.Send.PushBack(func(rr *request.Request) {
attempt.SendDone = time.Now()
defer func() {
attempt.HTTPTrace.Finish = time.Now()
}()
if rr.Error != nil {
return
}
attempt.HTTPTrace.ReadHeaderDone = time.Now()
if t.ReadResponseBody {
attempt.HTTPTrace.ReadBodyStart = time.Now()
var w bytes.Buffer
if _, err := io.Copy(&w, rr.HTTPResponse.Body); err != nil {
rr.Error = err
return
}
rr.HTTPResponse.Body.Close()
rr.HTTPResponse.Body = ioutil.NopCloser(&w)
attempt.HTTPTrace.ReadBodyDone = time.Now()
}
})
// Unmarshal
r.Handlers.Unmarshal.PushFront(func(rr *request.Request) {
attempt.UnmarshalStart = time.Now()
})
r.Handlers.Unmarshal.PushBack(func(rr *request.Request) {
attempt.UnmarshalDone = time.Now()
})
// Unmarshal Error
r.Handlers.UnmarshalError.PushFront(func(rr *request.Request) {
attempt.UnmarshalErrorStart = time.Now()
})
r.Handlers.UnmarshalError.PushBack(func(rr *request.Request) {
attempt.UnmarshalErrorDone = time.Now()
})
// Retry handling and delay
r.Handlers.Retry.PushFront(func(rr *request.Request) {
attempt.RetryStart = time.Now()
attempt.Err = rr.Error
})
r.Handlers.AfterRetry.PushBack(func(rr *request.Request) {
attempt.RetryDone = time.Now()
attempt.WillRetry = rr.WillRetry()
})
// Complete Attempt
r.Handlers.CompleteAttempt.PushBack(func(rr *request.Request) {
attempt.Finish = time.Now()
t.Attempts = append(t.Attempts, attempt)
})
}
func (t *RequestTrace) String() string {
var w strings.Builder
l := t.Latency()
writeDurField(&w, "Latency", l.Latency)
writeDurField(&w, "Validate", l.Validate)
writeDurField(&w, "Build", l.Build)
writeField(&w, "Attempts", "%d", len(t.Attempts))
for i, a := range t.Attempts {
fmt.Fprintf(&w, "\n\tAttempt: %d, %s", i, a)
}
return w.String()
}
func (t *RequestTrace) onComplete(*request.Request) {
t.Finish = time.Now()
}
func (t *RequestTrace) onValidateStart(*request.Request) { t.ValidateStart = time.Now() }
func (t *RequestTrace) onValidateDone(*request.Request) { t.ValidateDone = time.Now() }
func (t *RequestTrace) onBuildStart(*request.Request) { t.BuildStart = time.Now() }
func (t *RequestTrace) onBuildDone(*request.Request) { t.BuildDone = time.Now() }
// RequestAttemptTrace provides a structure for storing trace information on
// the SDK's request attempt.
type RequestAttemptTrace struct {
Start, Finish time.Time
Err error
SignStart, SignDone time.Time
SendStart, SendDone time.Time
HTTPTrace *HTTPTrace
UnmarshalStart, UnmarshalDone time.Time
UnmarshalErrorStart, UnmarshalErrorDone time.Time
WillRetry bool
RetryStart, RetryDone time.Time
}
// Latency returns the latencies of the request attempt trace components.
func (t *RequestAttemptTrace) Latency() RequestAttemptLatency {
return RequestAttemptLatency{
Latency: safeTimeDelta(t.Start, t.Finish),
Err: t.Err,
Sign: safeTimeDelta(t.SignStart, t.SignDone),
Send: safeTimeDelta(t.SendStart, t.SendDone),
HTTP: t.HTTPTrace.Latency(),
Unmarshal: safeTimeDelta(t.UnmarshalStart, t.UnmarshalDone),
UnmarshalError: safeTimeDelta(t.UnmarshalErrorStart, t.UnmarshalErrorDone),
WillRetry: t.WillRetry,
Retry: safeTimeDelta(t.RetryStart, t.RetryDone),
}
}
func (t *RequestAttemptTrace) String() string {
var w strings.Builder
l := t.Latency()
writeDurField(&w, "Latency", l.Latency)
writeDurField(&w, "Sign", l.Sign)
writeDurField(&w, "Send", l.Send)
writeDurField(&w, "Unmarshal", l.Unmarshal)
writeDurField(&w, "UnmarshalError", l.UnmarshalError)
writeField(&w, "WillRetry", "%t", l.WillRetry)
writeDurField(&w, "Retry", l.Retry)
fmt.Fprintf(&w, "\n\t\tHTTP: %s", t.HTTPTrace)
if t.Err != nil {
fmt.Fprintf(&w, "\n\t\tError: %v", t.Err)
}
return w.String()
}
// HTTPTrace provides the trace time stamps of the HTTP request's segments.
type HTTPTrace struct {
context.Context
Start, Finish time.Time
GetConnStart, GetConnDone time.Time
Reused bool
DNSStart, DNSDone time.Time
ConnectStart, ConnectDone time.Time
TLSHandshakeStart, TLSHandshakeDone time.Time
WriteHeaderDone time.Time
WriteRequestDone time.Time
FirstResponseByte time.Time
ReadHeaderStart, ReadHeaderDone time.Time
ReadBodyStart, ReadBodyDone time.Time
}
// NewHTTPTrace returns a initialized HTTPTrace for an
// httptrace.ClientTrace, based on the context passed.
func NewHTTPTrace(ctx context.Context) *HTTPTrace {
t := &HTTPTrace{
Start: time.Now(),
}
trace := &httptrace.ClientTrace{
GetConn: t.getConn,
GotConn: t.gotConn,
PutIdleConn: t.putIdleConn,
GotFirstResponseByte: t.gotFirstResponseByte,
Got100Continue: t.got100Continue,
DNSStart: t.dnsStart,
DNSDone: t.dnsDone,
ConnectStart: t.connectStart,
ConnectDone: t.connectDone,
TLSHandshakeStart: t.tlsHandshakeStart,
TLSHandshakeDone: t.tlsHandshakeDone,
WroteHeaders: t.wroteHeaders,
Wait100Continue: t.wait100Continue,
WroteRequest: t.wroteRequest,
}
t.Context = httptrace.WithClientTrace(ctx, trace)
return t
}
// Latency returns the latencies for an HTTP request.
func (t *HTTPTrace) Latency() HTTPLatency {
latency := HTTPLatency{
Latency: safeTimeDelta(t.Start, t.Finish),
ConnReused: t.Reused,
WriteHeader: safeTimeDelta(t.GetConnDone, t.WriteHeaderDone),
WriteRequest: safeTimeDelta(t.GetConnDone, t.WriteRequestDone),
WaitResponseFirstByte: safeTimeDelta(t.WriteRequestDone, t.FirstResponseByte),
ReadHeader: safeTimeDelta(t.ReadHeaderStart, t.ReadHeaderDone),
ReadBody: safeTimeDelta(t.ReadBodyStart, t.ReadBodyDone),
}
if !t.Reused {
latency.GetConn = safeTimeDelta(t.GetConnStart, t.GetConnDone)
latency.DNS = safeTimeDelta(t.DNSStart, t.DNSDone)
latency.Connect = safeTimeDelta(t.ConnectStart, t.ConnectDone)
latency.TLS = safeTimeDelta(t.TLSHandshakeStart, t.TLSHandshakeDone)
} else {
latency.GetConn = safeTimeDelta(t.Start, t.GetConnDone)
}
return latency
}
func (t *HTTPTrace) String() string {
var w strings.Builder
l := t.Latency()
writeDurField(&w, "Latency", l.Latency)
writeField(&w, "ConnReused", "%t", l.ConnReused)
writeDurField(&w, "GetConn", l.GetConn)
writeDurField(&w, "WriteHeader", l.WriteHeader)
writeDurField(&w, "WriteRequest", l.WriteRequest)
writeDurField(&w, "WaitResponseFirstByte", l.WaitResponseFirstByte)
writeDurField(&w, "ReadHeader", l.ReadHeader)
writeDurField(&w, "ReadBody", l.ReadBody)
if !t.Reused {
fmt.Fprintf(&w, "\n\t\t\tConn: ")
writeDurField(&w, "DNS", l.DNS)
writeDurField(&w, "Connect", l.Connect)
writeDurField(&w, "TLS", l.TLS)
}
return w.String()
}
func (t *HTTPTrace) getConn(hostPort string) {
t.GetConnStart = time.Now()
}
func (t *HTTPTrace) gotConn(info httptrace.GotConnInfo) {
t.GetConnDone = time.Now()
t.Reused = info.Reused
}
func (t *HTTPTrace) putIdleConn(err error) {}
func (t *HTTPTrace) gotFirstResponseByte() {
t.FirstResponseByte = time.Now()
t.ReadHeaderStart = t.FirstResponseByte
}
func (t *HTTPTrace) got100Continue() {}
func (t *HTTPTrace) dnsStart(info httptrace.DNSStartInfo) {
t.DNSStart = time.Now()
}
func (t *HTTPTrace) dnsDone(info httptrace.DNSDoneInfo) {
t.DNSDone = time.Now()
}
func (t *HTTPTrace) connectStart(network, addr string) {
t.ConnectStart = time.Now()
}
func (t *HTTPTrace) connectDone(network, addr string, err error) {
t.ConnectDone = time.Now()
}
func (t *HTTPTrace) tlsHandshakeStart() {
t.TLSHandshakeStart = time.Now()
}
func (t *HTTPTrace) tlsHandshakeDone(state tls.ConnectionState, err error) {
t.TLSHandshakeDone = time.Now()
}
func (t *HTTPTrace) wroteHeaders() {
t.WriteHeaderDone = time.Now()
}
func (t *HTTPTrace) wait100Continue() {}
func (t *HTTPTrace) wroteRequest(info httptrace.WroteRequestInfo) {
t.WriteRequestDone = time.Now()
}
func safeTimeDelta(start, end time.Time) time.Duration {
if start.IsZero() || end.IsZero() || start.After(end) {
return 0
}
return end.Sub(start)
}
func writeField(w io.Writer, field string, format string, args ...interface{}) error {
_, err := fmt.Fprintf(w, "%s: "+format+", ", append([]interface{}{field}, args...)...)
return err
}
func writeDurField(w io.Writer, field string, dur time.Duration) error {
if dur == 0 {
return nil
}
_, err := fmt.Fprintf(w, "%s: %s, ", field, dur)
return err
}
|