This repository has been archived by the owner on Jun 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nuvolari.go
195 lines (170 loc) · 4.89 KB
/
nuvolari.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
// Package nuvolari implements a ndt7 client. The specification of ndt7 is
// available at https://github.com/m-lab/ndt-cloud/blob/master/spec/ndt7.md.
package nuvolari
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"net"
"net/http"
"net/url"
"time"
"github.com/gorilla/websocket"
)
// Settings contains the ndt7 Client settings.
type Settings struct {
// Hostname is the hostname of the ndt7 server.
Hostname string
// Port is the port of the ndt7 server.
Port string
// SkipTLSVerify indicates whether we should skip TLS verify.
SkipTLSVerify bool
}
// BBRInfo contains BBR information.
type BBRInfo struct {
// MaxBandwidth is the bandwidth measured in bits per second.
MaxBandwidth float64 `json:"max_bandwidth"`
// MinRTT is the round-trip time measured in milliseconds.
MinRTT float64 `json:"min_rtt"`
}
// Measurement is a performance measurement.
type Measurement struct {
// Elapsed is the number of seconds elapsed since the beginning.
Elapsed float64 `json:"elapsed"`
// BBRInfo is optional BBR information included when possible.
BBRInfo *BBRInfo `json:"bbr_info,omitempty"`
}
// Handler handles Client events.
type Handler interface {
// OnLogInfo receives an informational message.
OnLogInfo(string)
// OnServerDownloadMeasurement receives a server-side download measurement.
OnServerDownloadMeasurement(Measurement)
// OnClientDownloadMeasurement receives a client-side download measurement.
OnClientDownloadMeasurement(Measurement)
}
// Client is the default client implementation.
type Client struct {
// Settings contains client settings.
Settings Settings
// Handler for events.
Handler Handler
}
const downloadURLPath = "/ndt/v7/download"
// ErrInvalidHostname is returned when Settings.Hostname is invalid.
var ErrInvalidHostname = errors.New("Hostname is invalid")
func (cl Client) makeURL() (url.URL, error) {
var u url.URL
u.Scheme = "wss"
if cl.Settings.Port != "" {
ip := net.ParseIP(cl.Settings.Hostname)
if ip == nil || ip.To4() != nil {
u.Host = cl.Settings.Hostname
u.Host += ":"
u.Host += cl.Settings.Port
} else if ip.To16() != nil {
u.Host = "["
u.Host += cl.Settings.Hostname
u.Host += "]:"
u.Host += cl.Settings.Port
} else {
return url.URL{}, ErrInvalidHostname
}
} else {
u.Host = cl.Settings.Hostname
}
u.Path = downloadURLPath
return u, nil
}
func (cl Client) makeDialer() websocket.Dialer {
var d websocket.Dialer
if cl.Settings.SkipTLSVerify {
config := tls.Config{InsecureSkipVerify: true}
d.TLSClientConfig = &config
}
return d
}
const defaultDuration = 10
const defaultTimeout = 7 * time.Second
const secWebSocketProtocol = "net.measurementlab.ndt.v7"
const minMeasurementInterval = 250 * time.Millisecond
const minMaxMessageSize = 1 << 17
// ErrServerGoneWild is returned when the server runs a download for too much
// time, so that it's proper to stop the download from the client side.
var ErrServerGoneWild = errors.New("Server is running for too much time")
// RunDownload runs a ndt7 download test.
func (cl Client) RunDownload(ctx context.Context) error {
wsURL, err := cl.makeURL()
if err != nil {
return err
}
wsDialer := cl.makeDialer()
headers := http.Header{}
headers.Add("Sec-WebSocket-Protocol", secWebSocketProtocol)
wsDialer.HandshakeTimeout = defaultTimeout
if cl.Handler != nil {
cl.Handler.OnLogInfo("Connecting to: " + wsURL.String())
}
conn, _, err := wsDialer.Dial(wsURL.String(), headers)
if err != nil {
return err
}
conn.SetReadLimit(minMaxMessageSize)
defer conn.Close()
if cl.Handler != nil {
cl.Handler.OnLogInfo("Connection established")
}
t0 := time.Now()
tLast := t0
count := int64(0)
maxDuration := float64(time.Duration(defaultDuration)*time.Second) * 1.5
for {
// Check whether the user interrupted us
select {
case <-ctx.Done():
if cl.Handler != nil {
cl.Handler.OnLogInfo("Download interrupted by user")
}
return nil // No error because user interrupted us
default:
break
}
// Check whether we've run for too much time
now := time.Now()
elapsed := now.Sub(t0)
if float64(elapsed) >= maxDuration {
return ErrServerGoneWild
}
// Check whether it's time to run the next client-side measurement
if now.Sub(tLast) >= minMeasurementInterval {
if cl.Handler != nil {
cl.Handler.OnClientDownloadMeasurement(Measurement{
Elapsed: elapsed.Seconds(),
})
}
tLast = now
}
// Read and process the next WebSocket message
conn.SetReadDeadline(time.Now().Add(defaultTimeout))
mtype, mdata, err := conn.ReadMessage()
if err != nil {
if !websocket.IsCloseError(err, websocket.CloseNormalClosure) {
return err
}
break
}
count += int64(len(mdata))
if mtype == websocket.TextMessage {
var measurement Measurement
err := json.Unmarshal(mdata, &measurement)
if err != nil {
return err
}
if cl.Handler != nil {
cl.Handler.OnServerDownloadMeasurement(measurement)
}
}
}
return nil
}