/
actions.go
354 lines (318 loc) · 9.65 KB
/
actions.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
// The MIT License (MIT)
// Copyright (c) 2014, 2016 traetox
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package speedtestdotnet
import (
"errors"
"fmt"
"io"
"net"
"sort"
"strconv"
"strings"
"time"
)
const (
maxDownstreamTestCount = 4
maxTransferSize = 64 * 1024 * 1024
defaultTransferSize = 16 * 1024 * 1024
pingTimeout = time.Second * 5
speedTestTimeout = time.Second * 10
cmdTimeout = time.Second
latencyMaxTestCount = 60
dataBlockSize = 32 * 1024 //128KB
)
var (
errInvalidServerResponse = errors.New("Invalid server response")
errPingFailure = errors.New("Failed to complete ping test")
errDontBeADick = errors.New("requested ping count too high")
startBlockSize = uint64(4096) //4KB
dataBlock []byte
ErrTimeout = errors.New("Timeout")
)
func init() {
base := []byte("ABCDEFGHIJ")
dataBlock = make([]byte, dataBlockSize)
for i := range dataBlock {
dataBlock[i] = base[i%len(base)]
}
}
type durations []time.Duration
func (ts *Testserver) ping(count int) ([]time.Duration, error) {
var errRet []time.Duration
if count > latencyMaxTestCount {
return errRet, errDontBeADick
}
//establish connection to the host
conn, err := net.DialTimeout("tcp", ts.Host, pingTimeout)
if err != nil {
return errRet, ErrTimeout
}
defer conn.Close()
durs := []time.Duration{}
buff := make([]byte, 256)
for i := 0; i < count; i++ {
t := time.Now()
fmt.Fprintf(conn, "PING %d\n", uint(t.UnixNano()/1000000))
conn.SetReadDeadline(time.Now().Add(pingTimeout))
n, err := conn.Read(buff)
if err != nil {
return errRet, err
}
conn.SetReadDeadline(time.Time{})
d := time.Since(t)
flds := strings.Fields(strings.TrimRight(string(buff[0:n]), "\n"))
if len(flds) != 2 {
return errRet, errInvalidServerResponse
}
if flds[0] != "PONG" {
return errRet, errInvalidServerResponse
}
if _, err = strconv.ParseInt(flds[1], 10, 64); err != nil {
return errRet, errInvalidServerResponse
}
durs = append(durs, d)
}
if len(durs) != count {
return errRet, errPingFailure
}
return durs, nil
}
// MedianPing runs a latency test against the server and stores the median latency
func (ts *Testserver) MedianPing(count int) (time.Duration, error) {
var errRet time.Duration
durs, err := ts.ping(count)
if err != nil {
return errRet, err
}
sort.Sort(durations(durs))
ts.Latency = durs[count/2]
return durs[count/2], nil
}
// Ping will run count number of latency tests and return the results of each
func (ts *Testserver) Ping(count int) ([]time.Duration, error) {
return ts.ping(count)
}
// throwBytes chucks bytes at the remote server then listens for a response
func throwBytes(conn io.ReadWriter, count uint64) error {
var writeBytes uint64
var b []byte
buff := make([]byte, 128)
for writeBytes < count {
if (count - writeBytes) >= uint64(len(dataBlock)) {
b = dataBlock
} else {
b = dataBlock[0:(count - writeBytes)]
}
n, err := conn.Write(b)
if err != nil {
return err
}
writeBytes += uint64(n)
}
//read the response
n, err := conn.Read(buff)
if err != nil {
return err
}
if n == 0 {
return fmt.Errorf("Failed to get OK on upload")
}
if !strings.HasPrefix(string(buff[0:n]), "OK ") {
return fmt.Errorf("Failed to get OK on upload")
}
return nil
}
// readBytes reads until we get a newline or an error
func readBytes(rdr io.Reader, count uint64) error {
var rBytes uint64
buff := make([]byte, 4096)
for rBytes < count {
n, err := rdr.Read(buff)
if err != nil {
return err
}
rBytes += uint64(n)
if n == 0 {
break
}
if buff[n-1] == '\n' {
break
}
}
if rBytes != count {
return fmt.Errorf("Failed entire read: %d != %d", rBytes, count)
}
return nil
}
// Upstream measures upstream bandwidth in bps
func (ts *Testserver) Upstream(duration int, interface_id string) (uint64, error) {
var currBps uint64
sz := startBlockSize
var localAddr *net.TCPAddr
if interface_id != `` {
// if a source interface is specified, resolve it and set the localAddr for the dialer
intf, err := net.InterfaceByName(interface_id)
if err != nil {
return 0, err
}
addrs, err := intf.Addrs()
if err != nil {
return 0, err
}
// Create a TCP address using the IP address of the interface
localAddr = &net.TCPAddr{
IP: addrs[0].(*net.IPNet).IP,
}
}
// Create a Dialer with LocalAddr set to the IP address of the interface
dialer := net.Dialer{
LocalAddr: localAddr,
Timeout: speedTestTimeout,
}
// Establish a connection to the speed test server
conn, err := dialer.Dial("tcp", ts.Host)
if err != nil {
return 0, err
}
targetTestDuration := time.Second * time.Duration(duration)
defer conn.Close()
//we repeat the tests until we have a test that lasts at least N seconds
for i := 0; i < maxDownstreamTestCount; i++ {
//request a download of size sz and set a deadline
if err = conn.SetWriteDeadline(time.Now().Add(cmdTimeout)); err != nil {
return 0, err
}
cmdStr := fmt.Sprintf("UPLOAD %d 0\n", sz)
if _, err := conn.Write([]byte(cmdStr)); err != nil {
return 0, err
}
if err = conn.SetWriteDeadline(time.Time{}); err != nil {
return 0, err
}
ts := time.Now() //set start time mark
if err = conn.SetWriteDeadline(time.Now().Add(speedTestTimeout)); err != nil {
return 0, err
}
if err := throwBytes(conn, sz-uint64(len(cmdStr))); err != nil {
return 0, err
}
if err = conn.SetReadDeadline(time.Time{}); err != nil {
return 0, err
}
//check if our test was a reasonable timespan
dur := time.Since(ts)
currBps = bps(sz, dur)
if dur.Nanoseconds() > targetTestDuration.Nanoseconds() || sz >= maxTransferSize {
_, err = fmt.Fprintf(conn, "QUIT\n")
return bps(sz, dur), err
}
//test was too short, try again
sz = calcNextSize(sz, dur)
if sz > maxTransferSize {
sz = maxTransferSize
}
}
_, err = fmt.Fprintf(conn, "QUIT\n")
return currBps, err
}
// Downstream measures upstream bandwidth in bps
func (ts *Testserver) Downstream(duration int, interface_id string) (uint64, error) {
var currBps uint64
sz := startBlockSize
var localAddr *net.TCPAddr
if interface_id != `` {
// if a source interface is specified, resolve it and set the localAddr for the dialer
intf, err := net.InterfaceByName(interface_id)
if err != nil {
return 0, err
}
addrs, err := intf.Addrs()
if err != nil {
return 0, err
}
// Create a TCP address using the IP address of the interface
localAddr = &net.TCPAddr{
IP: addrs[0].(*net.IPNet).IP,
}
}
// Create a Dialer with LocalAddr set to the IP address of the interface
dialer := net.Dialer{
LocalAddr: localAddr,
Timeout: speedTestTimeout,
}
// Establish a connection to the speed test server
conn, err := dialer.Dial("tcp", ts.Host)
if err != nil {
return 0, err
}
defer conn.Close()
targetTestDuration := time.Second * time.Duration(duration)
//we repeat the tests until we have a test that lasts at least N seconds
for i := 0; i < maxDownstreamTestCount; i++ {
//request a download of size sz and set a deadline
if err = conn.SetWriteDeadline(time.Now().Add(cmdTimeout)); err != nil {
return 0, err
}
fmt.Fprintf(conn, "DOWNLOAD %d\n", sz)
if err = conn.SetWriteDeadline(time.Time{}); err != nil {
return 0, err
}
ts := time.Now() //set start time mark
if err = conn.SetReadDeadline(time.Now().Add(speedTestTimeout)); err != nil {
return 0, err
}
//read until we get a newline
if err = readBytes(conn, sz); err != nil {
return 0, err
}
if err = conn.SetReadDeadline(time.Time{}); err != nil {
return 0, err
}
//check if our test was a reasonable timespan
dur := time.Since(ts)
currBps = bps(sz, dur)
if dur.Nanoseconds() > targetTestDuration.Nanoseconds() || sz >= maxTransferSize {
_, err = fmt.Fprintf(conn, "QUIT\n")
return bps(sz, dur), err
}
//test was too short, try again
sz = calcNextSize(sz, dur)
if sz > maxTransferSize {
sz = maxTransferSize
}
}
_, err = fmt.Fprintf(conn, "QUIT\n")
return currBps, err
}
// calcNextSize takes the current preformance metrics and
// attempts to calculate what the next size should be
func calcNextSize(b uint64, dur time.Duration) uint64 {
if b == 0 {
return startBlockSize
}
target := time.Second * 5
return (b * uint64(target.Nanoseconds())) / uint64(dur.Nanoseconds())
}
// take the byte count and duration and calcuate a bits per second
func bps(byteCount uint64, dur time.Duration) uint64 {
bits := byteCount * 8
return uint64((bits * 1000000000) / uint64(dur.Nanoseconds()))
}
func (d durations) Len() int { return len(d) }
func (d durations) Less(i, j int) bool { return d[i].Nanoseconds() < d[j].Nanoseconds() }
func (d durations) Swap(i, j int) { d[i], d[j] = d[j], d[i] }