-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
engine_unix.go
307 lines (269 loc) · 7.64 KB
/
engine_unix.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
306
307
// Copyright (c) 2019 The Gnet Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd
// +build darwin dragonfly freebsd linux netbsd openbsd
package gnet
import (
"context"
"errors"
"runtime"
"strings"
"sync/atomic"
"golang.org/x/sync/errgroup"
"github.com/panjf2000/gnet/v2/internal/gfd"
"github.com/panjf2000/gnet/v2/internal/netpoll"
"github.com/panjf2000/gnet/v2/internal/queue"
errorx "github.com/panjf2000/gnet/v2/pkg/errors"
"github.com/panjf2000/gnet/v2/pkg/logging"
)
type engine struct {
listeners map[int]*listener // listeners for accepting incoming connections
opts *Options // options with engine
ingress *eventloop // main event-loop that monitors all listeners
eventLoops loadBalancer // event-loops for handling events
inShutdown atomic.Bool // whether the engine is in shutdown
turnOff context.CancelFunc
eventHandler EventHandler // user eventHandler
concurrency struct {
*errgroup.Group
ctx context.Context
}
}
func (eng *engine) isShutdown() bool {
return eng.inShutdown.Load()
}
// shutdown signals the engine to shut down.
func (eng *engine) shutdown(err error) {
if err != nil && !errors.Is(err, errorx.ErrEngineShutdown) {
eng.opts.Logger.Errorf("engine is being shutdown with error: %v", err)
}
eng.turnOff()
}
func (eng *engine) closeEventLoops() {
eng.eventLoops.iterate(func(_ int, el *eventloop) bool {
for _, ln := range el.listeners {
ln.close()
}
_ = el.poller.Close()
return true
})
if eng.ingress != nil {
for _, ln := range eng.listeners {
ln.close()
}
err := eng.ingress.poller.Close()
if err != nil {
eng.opts.Logger.Errorf("failed to close poller when stopping engine: %v", err)
}
}
}
func (eng *engine) runEventLoops(ctx context.Context, numEventLoop int) error {
var el0 *eventloop
lns := eng.listeners
// Create loops locally and bind the listeners.
for i := 0; i < numEventLoop; i++ {
if i > 0 {
lns = make(map[int]*listener, len(eng.listeners))
for _, l := range eng.listeners {
ln, err := initListener(l.network, l.address, eng.opts)
if err != nil {
return err
}
lns[ln.fd] = ln
}
}
p, err := netpoll.OpenPoller()
if err != nil {
return err
}
el := new(eventloop)
el.listeners = lns
el.engine = eng
el.poller = p
el.buffer = make([]byte, eng.opts.ReadBufferCap)
el.connections.init()
el.eventHandler = eng.eventHandler
for _, ln := range lns {
if err = el.poller.AddRead(ln.packPollAttachment(el.accept), false); err != nil {
return err
}
}
eng.eventLoops.register(el)
// Start the ticker.
if eng.opts.Ticker && el.idx == 0 {
el0 = el
}
}
// Start event-loops in background.
eng.eventLoops.iterate(func(_ int, el *eventloop) bool {
eng.concurrency.Go(el.run)
return true
})
if el0 != nil {
eng.concurrency.Go(func() error {
el0.ticker(ctx)
return nil
})
}
return nil
}
func (eng *engine) activateReactors(ctx context.Context, numEventLoop int) error {
for i := 0; i < numEventLoop; i++ {
p, err := netpoll.OpenPoller()
if err != nil {
return err
}
el := new(eventloop)
el.listeners = eng.listeners
el.engine = eng
el.poller = p
el.buffer = make([]byte, eng.opts.ReadBufferCap)
el.connections.init()
el.eventHandler = eng.eventHandler
eng.eventLoops.register(el)
}
// Start sub reactors in background.
eng.eventLoops.iterate(func(_ int, el *eventloop) bool {
eng.concurrency.Go(el.orbit)
return true
})
p, err := netpoll.OpenPoller()
if err != nil {
return err
}
el := new(eventloop)
el.listeners = eng.listeners
el.idx = -1
el.engine = eng
el.poller = p
el.eventHandler = eng.eventHandler
for _, ln := range eng.listeners {
if err = el.poller.AddRead(ln.packPollAttachment(el.accept0), true); err != nil {
return err
}
}
eng.ingress = el
// Start main reactor in background.
eng.concurrency.Go(el.rotate)
// Start the ticker.
if eng.opts.Ticker {
eng.concurrency.Go(func() error {
eng.ingress.ticker(ctx)
return nil
})
}
return nil
}
func (eng *engine) start(ctx context.Context, numEventLoop int) error {
if eng.opts.ReusePort {
return eng.runEventLoops(ctx, numEventLoop)
}
return eng.activateReactors(ctx, numEventLoop)
}
func (eng *engine) stop(ctx context.Context, s Engine) {
// Wait on a signal for shutdown
<-ctx.Done()
eng.eventHandler.OnShutdown(s)
// Notify all event-loops to exit.
eng.eventLoops.iterate(func(i int, el *eventloop) bool {
err := el.poller.Trigger(queue.HighPriority, func(_ any) error { return errorx.ErrEngineShutdown }, nil)
if err != nil {
eng.opts.Logger.Errorf("failed to enqueue shutdown signal of high-priority for event-loop(%d): %v", i, err)
}
return true
})
if eng.ingress != nil {
err := eng.ingress.poller.Trigger(queue.HighPriority, func(_ any) error { return errorx.ErrEngineShutdown }, nil)
if err != nil {
eng.opts.Logger.Errorf("failed to enqueue shutdown signal of high-priority for main event-loop: %v", err)
}
}
if err := eng.concurrency.Wait(); err != nil {
eng.opts.Logger.Errorf("engine shutdown error: %v", err)
}
// Close all listeners and pollers of event-loops.
eng.closeEventLoops()
// Put the engine into the shutdown state.
eng.inShutdown.Store(true)
}
func run(eventHandler EventHandler, listeners []*listener, options *Options, addrs []string) error {
// Figure out the proper number of event-loop to run.
numEventLoop := 1
if options.Multicore {
numEventLoop = runtime.NumCPU()
}
if options.NumEventLoop > 0 {
numEventLoop = options.NumEventLoop
}
if numEventLoop > gfd.EventLoopIndexMax {
numEventLoop = gfd.EventLoopIndexMax
}
logging.Infof("Launching gnet with %d event-loops, listening on: %s",
numEventLoop, strings.Join(addrs, " | "))
lns := make(map[int]*listener, len(listeners))
for _, ln := range listeners {
lns[ln.fd] = ln
}
rootCtx, shutdown := context.WithCancel(context.Background())
eg, ctx := errgroup.WithContext(rootCtx)
eng := engine{
listeners: lns,
opts: options,
turnOff: shutdown,
eventHandler: eventHandler,
concurrency: struct {
*errgroup.Group
ctx context.Context
}{eg, ctx},
}
switch options.LB {
case RoundRobin:
eng.eventLoops = new(roundRobinLoadBalancer)
case LeastConnections:
eng.eventLoops = new(leastConnectionsLoadBalancer)
case SourceAddrHash:
eng.eventLoops = new(sourceAddrHashLoadBalancer)
}
e := Engine{&eng}
switch eng.eventHandler.OnBoot(e) {
case None, Close:
case Shutdown:
return nil
}
if err := eng.start(ctx, numEventLoop); err != nil {
eng.closeEventLoops()
eng.opts.Logger.Errorf("gnet engine is stopping with error: %v", err)
return err
}
defer eng.stop(rootCtx, e)
for _, addr := range addrs {
allEngines.Store(addr, &eng)
}
return nil
}
/*
func (eng *engine) sendCmd(cmd *asyncCmd, urgent bool) error {
if !gfd.Validate(cmd.fd) {
return errors.ErrInvalidConn
}
el := eng.eventLoops.index(cmd.fd.EventLoopIndex())
if el == nil {
return errors.ErrInvalidConn
}
if urgent {
return el.poller.Trigger(queue.LowPriority, el.execCmd, cmd)
}
return el.poller.Trigger(el.execCmd, cmd)
}
*/