forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroundtrip.go
152 lines (129 loc) Β· 3.38 KB
/
roundtrip.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
package request
import (
"bytes"
"io"
"net/http"
"net/http/httputil"
"strconv"
"strings"
"time"
"github.com/evcc-io/evcc/util"
"github.com/prometheus/client_golang/prometheus"
)
type roundTripper struct {
log *util.Logger
base http.RoundTripper
}
const max = 1024 * 64
var (
LogHeaders bool
reqMetric *prometheus.SummaryVec
resMetric *prometheus.CounterVec
)
func init() {
labels := []string{"host"}
reqMetric = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Namespace: "evcc",
Subsystem: "http",
Name: "request_duration_seconds",
Help: "A summary of HTTP request durations",
Objectives: map[float64]float64{
0.5: 0.05, // 50th percentile with a max. absolute error of 0.05
0.9: 0.01, // 90th percentile with a max. absolute error of 0.01
0.99: 0.001, // 99th percentile with a max. absolute error of 0.001
},
}, labels)
resMetric = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "evcc",
Subsystem: "http",
Name: "request_total",
Help: "Total count of HTTP requests",
}, append(labels, "status"))
prometheus.MustRegister(reqMetric, resMetric)
}
// NewTripper creates a logging roundtrip handler
func NewTripper(log *util.Logger, base http.RoundTripper) http.RoundTripper {
tripper := &roundTripper{
log: log,
base: base,
}
return tripper
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// copy of http.drainBody
func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
if b == nil || b == http.NoBody {
// No copying needed. Preserve the magic sentinel meaning of NoBody.
return http.NoBody, http.NoBody, nil
}
var buf bytes.Buffer
if _, err = buf.ReadFrom(b); err != nil {
return nil, b, err
}
if err = b.Close(); err != nil {
return nil, b, err
}
return io.NopCloser(&buf), io.NopCloser(bytes.NewReader(buf.Bytes())), nil
}
// dump http request/response body
func dump(r io.ReadCloser, w *strings.Builder) error {
body, err := io.ReadAll(r)
if err != nil {
return err
}
if w.Len() > 0 && len(body) > 0 {
w.WriteString("\n--\n")
}
_, err = w.Write(bytes.TrimSpace(body[:min(max, len(body))]))
return err
}
func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
r.log.TRACE.Printf("%s %s", req.Method, req.URL.String())
// dump without headers
var err error
var save io.ReadCloser
bld := new(strings.Builder)
if LogHeaders {
if body, err := httputil.DumpRequestOut(req, true); err == nil {
bld.WriteString("\n")
bld.Write(bytes.TrimSpace(body[:min(max, len(body))]))
}
} else {
if save, req.Body, err = drainBody(req.Body); err == nil {
err = dump(save, bld)
}
if err != nil {
return nil, err
}
}
startTime := time.Now()
resp, err := r.base.RoundTrip(req)
reqMetric.WithLabelValues(req.URL.Hostname()).Observe(time.Since(startTime).Seconds())
if err == nil {
resMetric.WithLabelValues(req.URL.Hostname(), strconv.Itoa(resp.StatusCode)).Add(1)
if LogHeaders {
if body, err := httputil.DumpResponse(resp, true); err == nil {
bld.WriteString("\n\n")
bld.Write(bytes.TrimSpace(body[:min(max, len(body))]))
}
} else {
if save, resp.Body, err = drainBody(resp.Body); err == nil {
err = dump(save, bld)
}
if err != nil {
return nil, err
}
}
} else {
resMetric.WithLabelValues(req.URL.Hostname(), "999").Add(1)
}
if bld.Len() > 0 {
r.log.TRACE.Println(bld.String())
}
return resp, err
}