/
udp.go
275 lines (243 loc) · 6.35 KB
/
udp.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
package frontend
import (
"context"
"io"
"math"
"net"
"sync"
"time"
"github.com/damnever/goctl/retry"
bytesext "github.com/damnever/libext-go/bytes"
"go.uber.org/atomic"
"go.uber.org/zap"
"github.com/damnever/goodog/internal/pkg/encoding"
)
// udpProxy can not guarantee every single packet will be written to backend.
//
// IDEA: we could send UDP packet like this `| addr | size | data |`, so that
// there is no need to keep checking stream if it is idle, just maintains a pool
// of upstream streams, but this requires backend to keep tracking the address
// related packet, this way looks same to me and it consumes more bandwidth.
type udpProxy struct {
conf Config
logger *zap.Logger
conn net.PacketConn
connector Connector
pool *bytesext.Pool
retrier retry.Retrier
upmu sync.RWMutex
ups map[string]*udpUpstreamWrapper
pendingUpstreams *counter
upstreams *counter
idleClosed *counter
connectErrors *counter
readWriteErrors *counter
}
func newUDPProxy(conf Config, connector Connector, logger *zap.Logger) (*udpProxy, error) {
conn, err := net.ListenPacket("udp", conf.ListenAddr)
if err != nil {
return nil, err
}
return &udpProxy{
conf: conf,
logger: logger.Named("udp"),
conn: conn,
connector: connector,
pool: bytesext.NewPoolWith(7, 512), // Max: math.MaxUint16
retrier: retry.New(retry.ConstantBackoffs(2, 10*time.Millisecond)),
ups: map[string]*udpUpstreamWrapper{},
pendingUpstreams: newCounter("udp.pending-upstreams"),
upstreams: newCounter("udp.upstreams"),
idleClosed: newCounter("udp.idle-timeouts"),
connectErrors: newCounter("udp.errors.connect"),
readWriteErrors: newCounter("udp.errors.read-write"),
}, nil
}
func (p *udpProxy) Close() error {
p.upmu.Lock()
defer p.upmu.Unlock()
for _, w := range p.ups {
w.Close()
}
return p.conn.Close()
}
func (p *udpProxy) Serve(ctx context.Context) error {
go p.timeoutLoop(ctx)
buf := make([]byte, math.MaxUint16, math.MaxUint16)
for {
n, addr, err := p.conn.ReadFrom(buf)
if err != nil {
return err
}
data := p.pool.Get(n)
copy(data, buf[:n])
go func(data []byte) {
// FIXME(damnever): try to resuse this goroutine?
p.handle(ctx, addr, data)
p.pool.Put(data)
}(data)
}
}
func (p *udpProxy) timeoutLoop(ctx context.Context) {
// FIXME(damnever): magic number
timeout := 10 * time.Second
if p.conf.Timeout > timeout { // Is that ok?
timeout = p.conf.Timeout
}
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
addrs := []string{}
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
timedout := time.Now().Add(-timeout)
p.upmu.RLock()
for _, up := range p.ups {
if !up.ActiveAt().After(timedout) {
addrs = append(addrs, up.Addr())
}
}
p.upmu.RUnlock()
if len(addrs) > 0 {
count := 0
p.upmu.Lock()
for _, addr := range addrs {
up, ok := p.ups[addr]
if ok && !up.ActiveAt().After(timedout) {
up.Close()
delete(p.ups, addr)
count++
}
}
p.upmu.Unlock()
addrs = addrs[:0]
if count > 0 {
p.logger.Info("idle check", zap.Int("closed", count))
p.idleClosed.Add(uint32(count))
}
}
}
}
}
func (p *udpProxy) handle(ctx context.Context, downstreamAddr net.Addr, data []byte) {
err := p.retrier.Run(ctx, func() (st retry.State, err0 error) {
var upstream *udpUpstreamWrapper
upstream, err0 = p.getRemoteWriter(ctx, downstreamAddr)
if err0 != nil {
return
}
if err0 = upstream.WritePacket(data); err0 != nil {
upstream.Close()
p.upmu.Lock()
delete(p.ups, downstreamAddr.String())
p.upmu.Unlock()
}
return
})
if err != nil {
p.readWriteErrors.Inc()
p.logger.Debug("downstream->upstream done",
zap.String("upstream", p.conf.ServerHost()),
zap.String("downstream", downstreamAddr.String()),
zap.Error(err),
)
}
}
func (p *udpProxy) getRemoteWriter(ctx context.Context, downstreamAddr net.Addr) (*udpUpstreamWrapper, error) {
addrStr := downstreamAddr.String()
p.upmu.RLock()
w, ok := p.ups[addrStr]
p.upmu.RUnlock()
if ok {
return w, nil
}
p.pendingUpstreams.Inc()
upstream, err := p.connector.Connect(ctx)
if err != nil {
p.pendingUpstreams.Dec()
p.connectErrors.Inc()
p.logger.Error("connect to upstream failed",
zap.String("upstream", p.conf.ServerHost()),
zap.String("downstream", downstreamAddr.String()),
zap.Error(err),
)
return nil, err
}
p.pendingUpstreams.Dec()
p.upmu.Lock()
defer p.upmu.Unlock()
if w, ok := p.ups[addrStr]; ok {
upstream.Close()
return w, nil
}
p.upstreams.Inc()
upstream = tryWrapWithCompression(upstream, p.conf.Compression)
upstreamWrapper := newUDPUpstreamWrapper(addrStr, upstream)
p.ups[addrStr] = upstreamWrapper
go p.serveAddr(ctx, downstreamAddr, upstreamWrapper)
return upstreamWrapper, nil
}
func (p *udpProxy) serveAddr(_ context.Context, downstreamAddr net.Addr, upstream *udpUpstreamWrapper) {
var (
n int
err error
buf = p.pool.Get(math.MaxUint16)
)
for {
// TODO: timeout??
if n, err = upstream.ReadPacket(buf); err != nil {
p.readWriteErrors.Inc()
break
}
if _, err = p.conn.WriteTo(buf[:n], downstreamAddr); err != nil {
p.readWriteErrors.Inc()
break
}
}
p.pool.Put(buf)
p.logger.Debug("upstream->downstream done",
zap.String("upstream", p.conf.ServerHost()),
zap.String("downstream", downstreamAddr.String()),
zap.Error(err),
)
p.upmu.Lock()
delete(p.ups, downstreamAddr.String())
p.upmu.Unlock()
upstream.Close()
p.upstreams.Dec()
}
type udpUpstreamWrapper struct {
addr string
activeAt atomic.Value
upstream io.ReadWriteCloser
}
func newUDPUpstreamWrapper(addr string, upstream io.ReadWriteCloser) *udpUpstreamWrapper {
u := &udpUpstreamWrapper{addr: addr, upstream: upstream}
u.activeAt.Store(time.Now())
return u
}
func (u *udpUpstreamWrapper) Addr() string {
return u.addr
}
func (u *udpUpstreamWrapper) ReadPacket(p []byte) (int, error) {
n, err := encoding.ReadU16SizedBytes(u.upstream, p)
if err == nil {
u.activeAt.Store(time.Now())
}
return n, err
}
func (u *udpUpstreamWrapper) WritePacket(p []byte) error {
err := encoding.WriteU16SizedBytes(u.upstream, p)
if err == nil {
u.activeAt.Store(time.Now())
}
return err
}
func (u *udpUpstreamWrapper) ActiveAt() time.Time {
return u.activeAt.Load().(time.Time)
}
func (u *udpUpstreamWrapper) Close() error {
return u.upstream.Close()
}