-
Notifications
You must be signed in to change notification settings - Fork 12
/
server.go
201 lines (165 loc) · 4.11 KB
/
server.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
package fastdns
import (
"errors"
"log/slog"
"net"
"runtime"
"sync"
"time"
)
// Server implements a mutli-listener DNS server.
type Server struct {
// handler to invoke
Handler Handler
// Stats to invoke
Stats Stats
// ErrorLog specifies an optional logger for errors accepting
// connections, unexpected behavior from handlers, and
// underlying FileSystem errors.
// If nil, logging is disabled.
ErrorLog *slog.Logger
// The maximum number of procs the server may spawn. use runtime.NumCPU() if empty
MaxProcs int
// The maximum number of concurrent clients the server may serve.
Concurrency int
// Index indicates the index of Server instances.
index int
}
// ListenAndServe serves DNS requests from the given UDP addr.
func (s *Server) ListenAndServe(addr string) error {
if s.Index() == 0 {
// only prefork for linux(reuse_port)
return s.spawn(addr, s.MaxProcs)
}
conn, err := listen("udp", addr)
if err != nil {
if s.ErrorLog != nil {
s.ErrorLog.Error("server listen failed", "error", err, "index", s.Index(), "addr", addr)
}
return err
}
// s.ErrorLog.Printf("server-%d pid-%d serving dns on %s", s.Index(), os.Getpid(), conn.LocalAddr())
return serve(conn, s.Handler, s.Stats, s.ErrorLog, s.Concurrency)
}
// Index indicates the index of Server instances.
func (s *Server) Index() (index int) {
index = s.index
return
}
func (s *Server) spawn(addr string, maxProcs int) (err error) {
type racer struct {
index int
err error
}
if maxProcs == 0 {
maxProcs = runtime.NumCPU()
}
if runtime.GOOS != "linux" {
maxProcs = 1
}
ch := make(chan racer, maxProcs)
// create multiple receive worker for performance
for i := 1; i <= maxProcs; i++ {
go func(index int) {
server := &Server{
Handler: s.Handler,
Stats: s.Stats,
ErrorLog: s.ErrorLog,
MaxProcs: s.MaxProcs,
Concurrency: s.Concurrency,
index: index,
}
err := server.ListenAndServe(addr)
ch <- racer{index, err}
}(i)
}
var exited int
for sig := range ch {
if s.ErrorLog != nil {
s.ErrorLog.Error("server one of the child workers exited", "error", sig.err)
}
if exited++; exited > 200 {
if s.ErrorLog != nil {
s.ErrorLog.Error("server child workers exit too many times", "count", exited)
}
err = errors.New("server child workers exit too many times")
break
}
go func(index int) {
server := &Server{
Handler: s.Handler,
Stats: s.Stats,
ErrorLog: s.ErrorLog,
MaxProcs: s.MaxProcs,
Concurrency: s.Concurrency,
index: index,
}
err := server.ListenAndServe(addr)
ch <- racer{index, err}
}(sig.index)
}
return
}
type udpCtx struct {
rw *udpResponseWriter
req *Message
handler Handler
stats Stats
}
var udpCtxPool = &sync.Pool{
New: func() interface{} {
ctx := new(udpCtx)
ctx.rw = new(udpResponseWriter)
ctx.req = new(Message)
ctx.req.Raw = make([]byte, 0, 1024)
ctx.req.Domain = make([]byte, 0, 256)
return ctx
},
}
func serve(conn *net.UDPConn, handler Handler, stats Stats, logger *slog.Logger, concurrency int) error {
if concurrency == 0 {
concurrency = 256 * 1024
}
pool := &workerPool{
WorkerFunc: serveCtx,
MaxWorkersCount: concurrency,
LogAllErrors: false,
MaxIdleWorkerDuration: 2 * time.Minute,
Logger: logger,
}
pool.Start()
for {
ctx := udpCtxPool.Get().(*udpCtx)
ctx.req.Raw = ctx.req.Raw[:cap(ctx.req.Raw)]
n, addrPort, err := conn.ReadFromUDPAddrPort(ctx.req.Raw)
if err != nil {
udpCtxPool.Put(ctx)
time.Sleep(10 * time.Millisecond)
continue
}
ctx.req.Raw = ctx.req.Raw[:n]
ctx.rw.Conn = conn
ctx.rw.AddrPort = addrPort
ctx.handler = handler
ctx.stats = stats
pool.Serve(ctx)
}
}
func serveCtx(ctx *udpCtx) error {
var start time.Time
if ctx.stats != nil {
start = time.Now()
}
rw, req := ctx.rw, ctx.req
err := ParseMessage(req, req.Raw, false)
if err != nil {
Error(rw, req, RcodeFormErr)
} else {
ctx.handler.ServeDNS(rw, req)
}
if ctx.stats != nil {
ctx.stats.UpdateStats(rw.RemoteAddr(), req, time.Since(start))
}
udpCtxPool.Put(ctx)
return err
}