forked from nknorg/mockconn-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uniconn.go
305 lines (255 loc) · 6.77 KB
/
uniconn.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
package mockconn
import (
"context"
"errors"
"fmt"
"log"
"math/rand"
"net"
"time"
"golang.org/x/time/rate"
)
var (
zeroTime time.Time
ErrClosedConn error = errors.New("connection is closed")
ErrNilPointer error = errors.New("data pointer is nil")
ErrZeroLengh error = errors.New("zero length data to write")
ErrUnknown error = errors.New("UniConn unknown error")
)
// To trace time consuming.
type dataWithTime struct {
data []byte
t time.Time
}
// unidirectional channel, can only send data from localAddr to remoteAddr
type UniConn struct {
localAddr string
remoteAddr string
throughput uint
bufferSize uint
latency time.Duration
loss float32
writeTimeout time.Duration // default timeout for writing
readTimeout time.Duration // default timeout for reading
sendCh chan *dataWithTime
bufferCh chan *dataWithTime
recvCh chan *dataWithTime
unreadData []byte // save unread data
// for metrics
nSendPacket int64 // number of packets sent
nRecvPacket int64 // number of packets received
nLoss int64 // number of packets are random lost
averageLatency time.Duration // average latency of all packets
// one time deadline and cancel
readCtx context.Context
readCancel context.CancelFunc
writeCtx context.Context
writeCancel context.CancelFunc
// close UniConn
closeWriteCtx context.Context
closeWriteCtxCancel context.CancelFunc
closeReadCtx context.Context
closeReadCtxCancel context.CancelFunc
}
func init() {
rand.Seed(time.Now().UnixNano())
}
func NewUniConn(conf *ConnConfig) (*UniConn, error) {
bufferSize := conf.BufferSize
if bufferSize == 0 {
bufferSize = uint(2 * float64(conf.Throughput) * conf.Latency.Seconds())
}
uc := &UniConn{throughput: conf.Throughput, bufferSize: bufferSize, latency: conf.Latency, loss: conf.Loss,
writeTimeout: conf.WriteTimeout, readTimeout: conf.ReadTimeout,
sendCh: make(chan *dataWithTime), bufferCh: make(chan *dataWithTime, bufferSize),
recvCh: make(chan *dataWithTime), localAddr: conf.Addr1, remoteAddr: conf.Addr2}
uc.closeWriteCtx, uc.closeWriteCtxCancel = context.WithCancel(context.Background())
uc.closeReadCtx, uc.closeReadCtxCancel = context.WithCancel(context.Background())
uc.SetDeadline(zeroTime)
go uc.throughputRead()
go uc.latencyRead()
return uc, nil
}
func (uc *UniConn) Write(b []byte) (n int, err error) {
if err = uc.writeCtx.Err(); err != nil {
return 0, err
}
if len(b) == 0 {
return 0, ErrZeroLengh
}
var timeoutCtx context.Context
var timeoutCancel context.CancelFunc
if uc.writeTimeout > 0 {
timeoutCtx, timeoutCancel = context.WithTimeout(uc.writeCtx, uc.writeTimeout)
} else {
timeoutCtx, timeoutCancel = context.WithCancel(uc.writeCtx)
}
defer timeoutCancel()
dt := &dataWithTime{data: b}
select {
case uc.sendCh <- dt:
uc.nSendPacket++
case <-timeoutCtx.Done():
return 0, timeoutCtx.Err()
}
return len(b), nil
}
func (uc *UniConn) randomLoss() bool {
if uc.loss > 0 {
l := rand.Float32()
if l < uc.loss {
uc.nLoss++
return true
}
}
return false
}
// The routine to stimulate throughput by rate Limiter
func (uc *UniConn) throughputRead() error {
defer close(uc.bufferCh)
r := rate.NewLimiter(rate.Limit(uc.throughput), 1)
for {
err := r.Wait(uc.closeWriteCtx)
if err != nil {
return err
}
select {
case <-uc.closeWriteCtx.Done():
return uc.closeWriteCtx.Err()
case dt := <-uc.sendCh:
if dt != nil {
if !uc.randomLoss() {
dt.t = time.Now()
uc.bufferCh <- dt
}
}
}
}
}
// The routine to stimulate latency
func (uc *UniConn) latencyRead() error {
defer close(uc.recvCh)
for {
select {
case <-uc.closeReadCtx.Done():
return uc.closeReadCtx.Err()
case dt := <-uc.bufferCh:
if dt != nil {
dur := time.Since(dt.t)
if dur < uc.latency {
timer := time.NewTimer(uc.latency - dur)
select {
case <-uc.closeReadCtx.Done():
return uc.closeReadCtx.Err()
case <-timer.C:
}
}
uc.recvCh <- dt
}
}
}
}
func (uc *UniConn) Read(b []byte) (n int, err error) {
if err = uc.readCtx.Err(); err != nil {
return 0, err
}
// check buffered unread data
unreadLen := len(uc.unreadData)
if unreadLen > 0 {
if unreadLen <= len(b) {
copy(b, uc.unreadData)
uc.unreadData = make([]byte, 0)
return unreadLen, nil
} else {
copy(b, uc.unreadData[0:len(b)])
uc.unreadData = uc.unreadData[len(b):]
return len(b), nil
}
}
var timeoutCtx context.Context
var timeoutCancel context.CancelFunc
if uc.readTimeout > 0 {
timeoutCtx, timeoutCancel = context.WithTimeout(uc.readCtx, uc.readTimeout)
} else {
timeoutCtx, timeoutCancel = context.WithCancel(uc.readCtx)
}
defer timeoutCancel()
for {
if err := uc.readCtx.Err(); err != nil {
return 0, err
}
select {
case dt := <-uc.recvCh:
if dt != nil {
if len(dt.data) > len(b) {
dt.data = dt.data[0:len(b)]
n = len(b)
uc.unreadData = dt.data[len(b):]
} else {
n = len(dt.data)
}
copy(b, dt.data)
uc.nRecvPacket++
uc.averageLatency = time.Duration(float64(uc.averageLatency)*(float64(uc.nRecvPacket-1)/float64(uc.nRecvPacket)) +
float64(time.Since(dt.t))/float64(uc.nRecvPacket))
return n, nil
}
case <-timeoutCtx.Done():
return 0, timeoutCtx.Err()
}
}
}
func (uc *UniConn) CloseWrite() error {
uc.closeWriteCtxCancel()
close(uc.sendCh)
return nil
}
func (uc *UniConn) CloseRead() error {
uc.closeReadCtxCancel()
return nil
}
func (uc *UniConn) Close() error {
uc.CloseWrite()
uc.CloseRead()
return nil
}
func (uc *UniConn) LocalAddr() net.Addr {
return ClientAddr{addr: uc.localAddr}
}
func (uc *UniConn) RemoteAddr() net.Addr {
return ClientAddr{addr: uc.remoteAddr}
}
func (uc *UniConn) SetDeadline(t time.Time) error {
err := uc.SetReadDeadline(t)
if err != nil {
return err
}
err = uc.SetWriteDeadline(t)
if err != nil {
return err
}
return nil
}
func (uc *UniConn) SetReadDeadline(t time.Time) error {
if t == zeroTime {
uc.readCtx, uc.readCancel = context.WithCancel(uc.closeReadCtx)
} else {
uc.readCtx, uc.readCancel = context.WithDeadline(uc.closeReadCtx, t)
}
return nil
}
func (uc *UniConn) SetWriteDeadline(t time.Time) error {
if t == zeroTime {
uc.writeCtx, uc.writeCancel = context.WithCancel(uc.closeWriteCtx)
} else {
uc.writeCtx, uc.writeCancel = context.WithDeadline(uc.closeWriteCtx, t)
}
return nil
}
func (uc *UniConn) PrintMetrics() {
log.Printf("%v to %v, %v packets are sent, %v packets are received, %v packets are lost, average latency is %v, loss rate is %.3f\n",
uc.localAddr, uc.remoteAddr, uc.nSendPacket, uc.nRecvPacket, uc.nLoss, uc.averageLatency, float64(uc.nLoss)/float64(uc.nRecvPacket))
}
func (uc *UniConn) String() string {
return fmt.Sprintf("UniConn from %v to %v", uc.localAddr, uc.remoteAddr)
}