-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
228 lines (179 loc) · 5.14 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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptrace"
"os"
"time"
flag "github.com/ogier/pflag"
_ "net/http/pprof"
)
var (
transport = &http.Transport{DisableKeepAlives: true}
client = &http.Client{
Transport: transport,
Timeout: time.Duration(10) * time.Second,
}
// CLI flags
help bool
version bool
interval int64
count int64
)
const (
usage = `
httptraced [options...] url
httptraced will make a GET request to a URL and report on the timings.
`
helpUsage = "Display this help message"
helpDefault = false
intervalUsage = "positive number of seconds to wait between making requests"
intervalDefault = 2
countUsage = "positive number of requests to make. If set, then interval is assumed to be set"
countDefault = -1
)
func main() {
// parse flags
flag.BoolVarP(&help, "help", "h", helpDefault, helpUsage)
flag.BoolVarP(&version, "version", "v", false, "Display the version")
flag.Int64VarP(&interval, "interval", "i", intervalDefault, intervalUsage)
flag.Int64VarP(&count, "count", "c", countDefault, countUsage)
flag.Parse()
if version {
_, _ = fmt.Fprintf(os.Stderr, "httptraced: version 0.0.1\n")
os.Exit(1)
}
if help {
showUsage()
os.Exit(2)
}
// Enforce sensible defaults
if count < 0 {
count = countDefault
}
if interval < 0 {
interval = intervalDefault
}
URL := flag.Arg(0)
if URL == "" {
showUsage()
os.Exit(2)
}
poll(URL)
}
func showUsage() {
_, _ = fmt.Fprintf(os.Stderr, usage)
flag.PrintDefaults()
}
type JSONTimestamp time.Time
func (j *JSONTimestamp) MarshalJSON() ([]byte, error) {
stamp := fmt.Sprintf("\"%s\"", time.Time(*j).UTC().Format(time.RFC3339Nano))
return []byte(stamp), nil
}
type JSONError struct {
Detail string `json:"detail"`
}
type JSONOutput struct {
Data interface{} `json:"data,omitempty"`
Errors []JSONError `json:"errors,omitempty"`
}
type TimingContext struct {
StartTime JSONTimestamp `json:"timestamp"`
URL string `json:"url"`
GetConn float64 `json:"getConn"`
GotConn float64 `json:"gotConn"`
GotFirstResponseByte float64 `json:"ttfb"`
DNSStart float64 `json:"dnsStart"`
DNSDone float64 `json:"dnsDone"`
ConnectStart float64 `json:"connectStart"`
ConnectDone float64 `json:"connectDone"`
WroteRequest float64 `json:"wroteRequest"`
Total float64 `json:"total"`
}
func New(URL string) *TimingContext {
t := TimingContext{}
t.StartTime = JSONTimestamp(time.Now())
t.URL = URL
return &t
}
func (tc *TimingContext) Elapsed() float64 {
return time.Since(time.Time(tc.StartTime)).Seconds()
}
func poll(URL string) {
encoder := json.NewEncoder(os.Stdout)
tickInterval := time.Duration(interval) * time.Second
// channel used to do the initial poll
start := make(chan struct{})
// channel used to signal that we've done the required count of polls
done := make(chan struct{})
t := time.NewTicker(tickInterval)
if count != countDefault {
// stop the timer after count * interval seconds
go func() {
<-time.After(time.Duration(count-1) * tickInterval)
close(done)
}()
}
// This one weird trick to do the initial poll
go func() {
start <- struct{}{}
}()
for {
select {
case <-start:
doPoll(URL, encoder)
case <-done:
t.Stop()
return
case <-t.C:
doPoll(URL, encoder)
}
}
}
func doPoll(URL string, encoder *json.Encoder) {
tc, err := doIt(URL)
if err != nil {
write(encoder,
JSONOutput{
Errors: []JSONError{
{Detail: err.Error()},
},
})
return
}
write(encoder, JSONOutput{Data: tc})
}
func doIt(URL string) (*TimingContext, error) {
req, err := http.NewRequest("GET", URL, nil)
if err != nil {
return nil, err
}
timingContext := New(URL)
req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{
GetConn: func(hostPort string) { timingContext.GetConn = timingContext.Elapsed() },
GotConn: func(ci httptrace.GotConnInfo) { timingContext.GotConn = timingContext.Elapsed() },
GotFirstResponseByte: func() { timingContext.GotFirstResponseByte = timingContext.Elapsed() },
DNSStart: func(e httptrace.DNSStartInfo) { timingContext.DNSStart = timingContext.Elapsed() },
DNSDone: func(e httptrace.DNSDoneInfo) { timingContext.DNSDone = timingContext.Elapsed() },
ConnectStart: func(network, addr string) { timingContext.ConnectStart = timingContext.Elapsed() },
ConnectDone: func(network, addr string, err error) { timingContext.ConnectDone = timingContext.Elapsed() },
WroteRequest: func(e httptrace.WroteRequestInfo) { timingContext.WroteRequest = timingContext.Elapsed() },
}))
res, err := client.Do(req)
if err != nil {
return nil, err
}
if _, err := io.Copy(io.Discard, res.Body); err != nil {
return nil, err
}
timingContext.Total = timingContext.Elapsed()
_ = res.Body.Close()
return timingContext, nil
}
func write(encoder *json.Encoder, jo JSONOutput) {
if err := encoder.Encode(jo); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err.Error())
}
}