-
Notifications
You must be signed in to change notification settings - Fork 40
/
handler.go
289 lines (264 loc) · 9.49 KB
/
handler.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
// Package handler implements the WebSocket handler for ndt7.
package handler
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"regexp"
"strconv"
"time"
"github.com/gorilla/websocket"
"golang.org/x/exp/slices"
"github.com/m-lab/access/controller"
"github.com/m-lab/go/prometheusx"
"github.com/m-lab/go/warnonerror"
"github.com/m-lab/ndt-server/data"
"github.com/m-lab/ndt-server/logging"
"github.com/m-lab/ndt-server/metadata"
"github.com/m-lab/ndt-server/metrics"
"github.com/m-lab/ndt-server/ndt7/download"
"github.com/m-lab/ndt-server/ndt7/download/sender"
ndt7metrics "github.com/m-lab/ndt-server/ndt7/metrics"
"github.com/m-lab/ndt-server/ndt7/model"
"github.com/m-lab/ndt-server/ndt7/results"
"github.com/m-lab/ndt-server/ndt7/spec"
"github.com/m-lab/ndt-server/ndt7/upload"
"github.com/m-lab/ndt-server/netx"
"github.com/m-lab/ndt-server/version"
"github.com/m-lab/tcp-info/eventsocket"
"github.com/m-lab/tcp-info/inetdiag"
)
// Handler handles ndt7 subtests.
type Handler struct {
// DataDir is the directory where results are saved.
DataDir string
// SecurePort should contain the port used for secure, WSS tests.
SecurePort string
// InsecurePort should contain the port used for insecure, WS tests.
InsecurePort string
// ServerMetadata contains deployment-specific metadata.
ServerMetadata []metadata.NameValue
// CompressResults controls whether the result files saved by the server are compressed.
CompressResults bool
// Events is for reporting new connections to the event server.
Events eventsocket.Server
}
// warnAndClose emits message as a warning and the sends a Bad Request
// response to the client using writer.
func warnAndClose(writer http.ResponseWriter, message string) {
logging.Logger.Warn(message)
writer.Header().Set("Connection", "Close")
writer.WriteHeader(http.StatusBadRequest)
}
// Download handles the download subtest.
func (h *Handler) Download(rw http.ResponseWriter, req *http.Request) {
h.runMeasurement(spec.SubtestDownload, rw, req)
}
// Upload handles the upload subtest.
func (h *Handler) Upload(rw http.ResponseWriter, req *http.Request) {
h.runMeasurement(spec.SubtestUpload, rw, req)
}
// runMeasurement conditionally runs either download or upload based on kind.
// The kind argument must be spec.SubtestDownload or spec.SubtestUpload.
func (h *Handler) runMeasurement(kind spec.SubtestKind, rw http.ResponseWriter, req *http.Request) {
// Validate client request before opening the connection.
params, err := validateEarlyExit(req.URL.Query())
if err != nil {
warnAndClose(rw, err.Error())
return
}
// Setup websocket connection.
conn := setupConn(rw, req)
if conn == nil {
// TODO: test failure.
ndt7metrics.ClientConnections.WithLabelValues(string(kind), "websocket-error").Inc()
return
}
// Make sure that the connection is closed after (at most) MaxRuntime.
// Download and upload tests have their own timeouts, but we have observed
// that under particular network conditions the connection can remain open
// while the receiver goroutine is blocked on a read syscall, long after
// the client is gone. This is a workaround for that.
ctx, cancel := context.WithTimeout(req.Context(), spec.MaxRuntime)
defer cancel()
go func() {
<-ctx.Done()
warnonerror.Close(conn, "runMeasurement: ignoring conn.Close result")
}()
// Create measurement archival data.
data, err := getData(conn)
if err != nil {
// TODO: test failure.
ndt7metrics.ClientConnections.WithLabelValues(string(kind), "uuid-error").Inc()
return
}
// We are guaranteed to collect a result at this point (even if it's with an error)
ndt7metrics.ClientConnections.WithLabelValues(string(kind), "result").Inc()
// Collect most client metadata from request parameters.
appendClientMetadata(data, req.URL.Query())
data.ServerMetadata = h.ServerMetadata
// Create ultimate result.
result, id := setupResult(conn)
result.StartTime = time.Now().UTC()
h.Events.FlowCreated(result.StartTime, data.UUID, id)
// Guarantee results are written even if subtest functions panic.
defer func() {
result.EndTime = time.Now().UTC()
h.writeResult(data.UUID, kind, result)
h.Events.FlowDeleted(result.EndTime, data.UUID)
}()
// Run measurement.
var rate float64
if kind == spec.SubtestDownload {
result.Download = data
err = download.Do(ctx, conn, data, params)
rate = downRate(data.ServerMeasurements)
} else if kind == spec.SubtestUpload {
result.Upload = data
err = upload.Do(ctx, conn, data)
rate = upRate(data.ServerMeasurements)
}
proto := ndt7metrics.ConnLabel(conn)
ndt7metrics.ClientTestResults.WithLabelValues(
proto, string(kind), metrics.GetResultLabel(err, rate)).Inc()
if rate > 0 {
isMon := fmt.Sprintf("%t", controller.IsMonitoring(controller.GetClaim(req.Context())))
// Update the common (ndt5+ndt7) measurement rates histogram.
metrics.TestRate.WithLabelValues(proto, string(kind), isMon).Observe(rate)
}
}
// setupConn negotiates a websocket connection. The writer argument is the HTTP
// response writer. The request argument is the HTTP request that we received.
func setupConn(writer http.ResponseWriter, request *http.Request) *websocket.Conn {
logging.Logger.Debug("setupConn: upgrading to WebSockets")
if request.Header.Get("Sec-WebSocket-Protocol") != spec.SecWebSocketProtocol {
warnAndClose(
writer, "setupConn: missing Sec-WebSocket-Protocol in request")
return nil
}
headers := http.Header{}
headers.Add("Sec-WebSocket-Protocol", spec.SecWebSocketProtocol)
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Allow cross origin resource sharing
},
ReadBufferSize: spec.DefaultWebsocketBufferSize,
WriteBufferSize: spec.DefaultWebsocketBufferSize,
}
conn, err := upgrader.Upgrade(writer, request, headers)
if err != nil {
return nil
}
logging.Logger.Debug("setupConn: opening results file")
return conn
}
// setupResult creates an NDT7Result from the given conn.
func setupResult(conn *websocket.Conn) (*data.NDT7Result, inetdiag.SockID) {
// NOTE: unless we plan to run the NDT server over different protocols than TCP,
// then we expect RemoteAddr and LocalAddr to always return net.TCPAddr types.
clientAddr := netx.ToTCPAddr(conn.RemoteAddr())
if clientAddr == nil {
clientAddr = &net.TCPAddr{IP: net.ParseIP("::1"), Port: 1}
}
serverAddr := netx.ToTCPAddr(conn.LocalAddr())
if serverAddr == nil {
serverAddr = &net.TCPAddr{IP: net.ParseIP("::1"), Port: 1}
}
result := &data.NDT7Result{
GitShortCommit: prometheusx.GitShortCommit,
Version: version.Version,
ClientIP: clientAddr.IP.String(),
ClientPort: clientAddr.Port,
ServerIP: serverAddr.IP.String(),
ServerPort: serverAddr.Port,
}
id := inetdiag.SockID{
SrcIP: result.ServerIP,
DstIP: result.ClientIP,
SPort: uint16(result.ServerPort),
DPort: uint16(result.ClientPort),
Cookie: -1, // Note: we do not populate the socket cookie here.
}
return result, id
}
func (h Handler) writeResult(uuid string, kind spec.SubtestKind, result *data.NDT7Result) {
fp, err := results.NewFile(uuid, h.DataDir, kind, h.CompressResults)
if err != nil {
logging.Logger.WithError(err).Warn("results.NewFile failed")
return
}
if err := fp.WriteResult(result); err != nil {
logging.Logger.WithError(err).Warn("failed to write result")
}
warnonerror.Close(fp, string(kind)+": ignoring fp.Close error")
}
func getData(conn *websocket.Conn) (*model.ArchivalData, error) {
ci := netx.ToConnInfo(conn.UnderlyingConn())
uuid, err := ci.GetUUID()
if err != nil {
logging.Logger.WithError(err).Warn("conninfo.GetUUID failed")
return nil, err
}
data := &model.ArchivalData{
UUID: uuid,
}
return data, nil
}
func upRate(m []model.Measurement) float64 {
var mbps float64
// NOTE: on non-Linux platforms, TCPInfo will be nil.
if len(m) > 0 && m[len(m)-1].TCPInfo != nil {
// Convert to Mbps.
mbps = 8 * float64(m[len(m)-1].TCPInfo.BytesReceived) / float64(m[len(m)-1].TCPInfo.ElapsedTime)
}
return mbps
}
func downRate(m []model.Measurement) float64 {
var mbps float64
// NOTE: on non-Linux platforms, TCPInfo will be nil.
if len(m) > 0 && m[len(m)-1].TCPInfo != nil {
// Convert to Mbps.
mbps = 8 * float64(m[len(m)-1].TCPInfo.BytesAcked) / float64(m[len(m)-1].TCPInfo.ElapsedTime)
}
return mbps
}
// excludeKeyRe is a regexp for excluding request parameters from client metadata.
var excludeKeyRe = regexp.MustCompile("^server_")
// appendClientMetadata adds |values| to the archival client metadata contained
// in the request parameter values. Some select key patterns will be excluded.
func appendClientMetadata(data *model.ArchivalData, values url.Values) {
for name, values := range values {
if matches := excludeKeyRe.MatchString(name); matches {
continue // Skip variables that should be excluded.
}
data.ClientMetadata = append(
data.ClientMetadata,
metadata.NameValue{
Name: name,
Value: values[0], // NOTE: this will ignore multi-value parameters.
})
}
}
// validateEarlyExit verifies and returns the "early_exit" parameters.
func validateEarlyExit(values url.Values) (*sender.Params, error) {
for name, values := range values {
if name != spec.EarlyExitParameterName {
continue
}
value := values[0]
if !slices.Contains(spec.ValidEarlyExitValues, value) {
return nil, fmt.Errorf("invalid %s parameter value %s", name, value)
}
// Convert string to int64.
bytes, _ := strconv.ParseInt(value, 10, 64)
return &sender.Params{
IsEarlyExit: true,
MaxBytes: bytes * 1000000, // Conver MB to bytes.
}, nil
}
return &sender.Params{
IsEarlyExit: false,
}, nil
}