This repository has been archived by the owner on Mar 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
op_latency.go
298 lines (250 loc) · 7.21 KB
/
op_latency.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
package docks
import (
"bytes"
"context"
"fmt"
"time"
"github.com/safing/portbase/container"
"github.com/safing/portbase/formats/varint"
"github.com/safing/portbase/log"
"github.com/safing/portbase/rng"
"github.com/safing/spn/terminal"
)
const (
// LatencyTestOpType is the type ID of the latency test operation.
LatencyTestOpType = "latency"
latencyPingRequest = 1
latencyPingResponse = 2
latencyTestNonceSize = 16
latencyTestRuns = 10
)
var (
latencyTestPauseDuration = 1 * time.Second
latencyTestOpTimeout = latencyTestRuns * latencyTestPauseDuration * 3
)
// LatencyTestOp is used to measure latency.
type LatencyTestOp struct {
terminal.OperationBase
}
// LatencyTestClientOp is the client version of LatencyTestOp.
type LatencyTestClientOp struct {
LatencyTestOp
lastPingSentAt time.Time
lastPingNonce []byte
measuredLatencies []time.Duration
responses chan *terminal.Msg
testResult time.Duration
result chan *terminal.Error
}
// Type returns the type ID.
func (op *LatencyTestOp) Type() string {
return LatencyTestOpType
}
func init() {
terminal.RegisterOpType(terminal.OperationFactory{
Type: LatencyTestOpType,
Requires: terminal.IsCraneController,
Start: startLatencyTestOp,
})
}
// NewLatencyTestOp runs a latency test.
func NewLatencyTestOp(t terminal.Terminal) (*LatencyTestClientOp, *terminal.Error) {
// Create and init.
op := &LatencyTestClientOp{
responses: make(chan *terminal.Msg),
measuredLatencies: make([]time.Duration, 0, latencyTestRuns),
result: make(chan *terminal.Error, 1),
}
// Make ping request.
pingRequest, err := op.createPingRequest()
if err != nil {
return nil, terminal.ErrInternalError.With("%w", err)
}
// Send ping.
tErr := t.StartOperation(op, pingRequest, 1*time.Second)
if tErr != nil {
return nil, tErr
}
// Start handler.
module.StartWorker("op latency handler", op.handler)
return op, nil
}
func (op *LatencyTestClientOp) handler(ctx context.Context) error {
returnErr := terminal.ErrStopping
defer func() {
// Linters don't get that returnErr is used when directly used as defer.
op.Stop(op, returnErr)
}()
var nextTest <-chan time.Time
opTimeout := time.After(latencyTestOpTimeout)
for {
select {
case <-ctx.Done():
return nil
case <-opTimeout:
return nil
case <-nextTest:
// Create ping request msg.
pingRequest, err := op.createPingRequest()
if err != nil {
returnErr = terminal.ErrInternalError.With("%w", err)
return nil
}
msg := op.NewEmptyMsg()
msg.Unit.MakeHighPriority()
msg.Data = pingRequest
// Send it.
tErr := op.Send(msg, latencyTestOpTimeout)
if tErr != nil {
returnErr = tErr.Wrap("failed to send ping request")
return nil
}
op.Flush(1 * time.Second)
nextTest = nil
case msg := <-op.responses:
// Check if the op ended.
if msg == nil {
return nil
}
// Handle response
tErr := op.handleResponse(msg)
if tErr != nil {
returnErr = tErr
return nil //nolint:nilerr
}
// Check if we have enough latency tests.
if len(op.measuredLatencies) >= latencyTestRuns {
returnErr = op.reportMeasuredLatencies()
return nil
}
// Schedule next latency test, if not yet scheduled.
if nextTest == nil {
nextTest = time.After(latencyTestPauseDuration)
}
}
}
}
func (op *LatencyTestClientOp) createPingRequest() (*container.Container, error) {
// Generate nonce.
nonce, err := rng.Bytes(latencyTestNonceSize)
if err != nil {
return nil, fmt.Errorf("failed to create ping nonce")
}
// Set client request state.
op.lastPingSentAt = time.Now()
op.lastPingNonce = nonce
return container.New(
varint.Pack8(latencyPingRequest),
nonce,
), nil
}
func (op *LatencyTestClientOp) handleResponse(msg *terminal.Msg) *terminal.Error {
defer msg.Finish()
rType, err := msg.Data.GetNextN8()
if err != nil {
return terminal.ErrMalformedData.With("failed to get response type: %w", err)
}
switch rType {
case latencyPingResponse:
// Check if the ping nonce matches.
if !bytes.Equal(op.lastPingNonce, msg.Data.CompileData()) {
return terminal.ErrIntegrity.With("ping nonce mismatch")
}
op.lastPingNonce = nil
// Save latency.
op.measuredLatencies = append(op.measuredLatencies, time.Since(op.lastPingSentAt))
return nil
default:
return terminal.ErrIncorrectUsage.With("unknown response type")
}
}
func (op *LatencyTestClientOp) reportMeasuredLatencies() *terminal.Error {
// Find lowest value.
lowestLatency := time.Hour
for _, latency := range op.measuredLatencies {
if latency < lowestLatency {
lowestLatency = latency
}
}
op.testResult = lowestLatency
// Save the result to the crane.
if controller, ok := op.Terminal().(*CraneControllerTerminal); ok {
if controller.Crane.ConnectedHub != nil {
controller.Crane.ConnectedHub.GetMeasurements().SetLatency(op.testResult)
log.Infof("spn/docks: measured latency to %s: %s", controller.Crane.ConnectedHub, op.testResult)
return nil
} else if controller.Crane.IsMine() {
return terminal.ErrInternalError.With("latency operation was run on %s without a connected hub set", controller.Crane)
}
} else if !runningTests {
return terminal.ErrInternalError.With("latency operation was run on terminal that is not a crane controller, but %T", op.Terminal())
}
return nil
}
// Deliver delivers a message to the operation.
func (op *LatencyTestClientOp) Deliver(msg *terminal.Msg) *terminal.Error {
// Optimized delivery with 1s timeout.
select {
case op.responses <- msg:
default:
select {
case op.responses <- msg:
case <-time.After(1 * time.Second):
return terminal.ErrTimeout
}
}
return nil
}
// HandleStop gives the operation the ability to cleanly shut down.
// The returned error is the error to send to the other side.
// Should never be called directly. Call Stop() instead.
func (op *LatencyTestClientOp) HandleStop(tErr *terminal.Error) (errorToSend *terminal.Error) {
close(op.responses)
select {
case op.result <- tErr:
default:
}
return tErr
}
// Result returns the result (end error) of the operation.
func (op *LatencyTestClientOp) Result() <-chan *terminal.Error {
return op.result
}
func startLatencyTestOp(t terminal.Terminal, opID uint32, data *container.Container) (terminal.Operation, *terminal.Error) {
// Create operation.
op := &LatencyTestOp{}
op.InitOperationBase(t, opID)
// Handle first request.
msg := op.NewEmptyMsg()
msg.Data = data
tErr := op.Deliver(msg)
if tErr != nil {
return nil, tErr
}
return op, nil
}
// Deliver delivers a message to the operation.
func (op *LatencyTestOp) Deliver(msg *terminal.Msg) *terminal.Error {
// Get request type.
rType, err := msg.Data.GetNextN8()
if err != nil {
return terminal.ErrMalformedData.With("failed to get response type: %w", err)
}
switch rType {
case latencyPingRequest:
// Keep the nonce and just replace the msg type.
msg.Data.PrependNumber(latencyPingResponse)
msg.Type = terminal.MsgTypeData
msg.Unit.ReUse()
msg.Unit.MakeHighPriority()
// Send response.
tErr := op.Send(msg, latencyTestOpTimeout)
if tErr != nil {
return tErr.Wrap("failed to send ping response")
}
op.Flush(1 * time.Second)
return nil
default:
return terminal.ErrIncorrectUsage.With("unknown request type")
}
}