-
Notifications
You must be signed in to change notification settings - Fork 33
/
session_manager.go
471 lines (424 loc) · 12.7 KB
/
session_manager.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/*
* Copyright 2023 CloudWeGo Authors
*
* 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.
*/
package shmipc
import (
"context"
"errors"
"math/rand"
"net"
"os"
"strconv"
"sync"
"sync/atomic"
"time"
)
const (
sessionRoundRobinThreshold = 32
)
var (
sessionManagerHandlers = []sessionManagerHandler{
typeHotRestart: handleSessionManagerHotRestart,
}
)
type sessionManagerHandler func(manager *SessionManager, params interface{})
type sessionManagerHotRestartParams struct {
epoch uint64
session *Session
}
// SessionManager will start multi Session with the peer process.
// when peer process was crashed or the underlying connection was closed, SessionManager could retry connect.
// and SessionManager could cooperate with peer process to finish hot restart.
type SessionManager struct {
ctx context.Context
cancelFunc context.CancelFunc
wg sync.WaitGroup
config *SessionManagerConfig
pools []*streamPool
// holds the stream pool prior to hot restart. Normally, it is closed by server
reservePools map[int]*streamPool
count uint64
epoch uint64
randID uint64
state sessionSateType
sync.RWMutex
}
// SessionManagerConfig is the configuration of SessionManager
type SessionManagerConfig struct {
*Config
UnixPath string //Deprecated , please use Network and Address.
Network string //tcp or unix
Address string //tcp address or unix domain socket path
//SessionNum is similar to concurrency.
//A session have dependent io queue, dependent tcp/unix connection.
//we recommend the value equal peer process' thread count, and every thread keep a session.
//if the peer process written by golang, recommend SessionNum = cpu cores / 4
SessionNum int
//Max number of stream per session's stream pool
MaxStreamNum int
//The idle time to close a stream
StreamMaxIdleTime time.Duration
}
type streamPool struct {
sync.Mutex
session atomic.Value
streams []*Stream
head uint64
tail uint64
capacity uint32
}
var (
globalSM *SessionManager
smMux sync.Mutex
)
// GlobalSessionManager return a global SessionManager. return nil if global SessionManager hadn't initialized
func GlobalSessionManager() *SessionManager {
smMux.Lock()
defer smMux.Unlock()
return globalSM
}
// DefaultSessionManagerConfig return the default SessionManager's configuration
func DefaultSessionManagerConfig() *SessionManagerConfig {
return &SessionManagerConfig{
Config: DefaultConfig(),
Address: "",
SessionNum: 1,
MaxStreamNum: 4096,
StreamMaxIdleTime: time.Second * 30,
}
}
// InitGlobalSessionManager initializes a global SessionManager and could use in every where in process
func InitGlobalSessionManager(config *SessionManagerConfig) (*SessionManager, error) {
smMux.Lock()
defer smMux.Unlock()
if globalSM != nil {
return globalSM, nil
}
sm, err := NewSessionManager(config)
if err != nil {
return nil, err
}
globalSM = sm
return globalSM, nil
}
// NewSessionManager return a SessionManager with giving configuration
func NewSessionManager(config *SessionManagerConfig) (*SessionManager, error) {
sm := &SessionManager{
config: config,
pools: make([]*streamPool, 0, config.SessionNum),
ctx: context.Background(),
}
for i := 0; i < config.SessionNum; i++ {
session, err := newClientSession(i, 0, 0, config)
if err != nil {
for k := 0; k < len(sm.pools); k++ {
sm.pools[k].close()
}
return nil, err
}
session.manager = sm
p := newStreamPool(uint32(config.MaxStreamNum))
p.session.Store(session)
sm.pools = append(sm.pools, p)
}
sm.background()
return sm, nil
}
func newStreamPool(poolCapacity uint32) *streamPool {
return &streamPool{streams: make([]*Stream, poolCapacity), capacity: poolCapacity}
}
// Close will shutdown the SessionManager's background goroutine and close all stream in stream pool
func (sm *SessionManager) Close() error {
sm.cancelFunc()
sm.wg.Wait()
for i := 0; i < len(sm.pools); i++ {
sm.pools[i].close()
}
return nil
}
// GetStream return a shmipc's Stream from stream pool.
// Every stream should explicitly call PutBack() to return it to SessionManager for next time using,
// otherwise it will cause resource leak.
func (sm *SessionManager) GetStream() (*Stream, error) {
i := (atomic.AddUint64(&sm.count, 1) / sessionRoundRobinThreshold) % uint64(len(sm.pools))
return sm.pools[i].getOrOpenStream()
}
// PutBack is used to return unused stream to stream pool for next time using.
func (sm *SessionManager) PutBack(stream *Stream) {
if stream != nil && stream.pool != nil {
stream.pool.putOrCloseStream(stream)
}
}
func (sm *SessionManager) background() {
sm.ctx, sm.cancelFunc = context.WithCancel(sm.ctx)
sm.wg.Add(len(sm.pools))
for i := 0; i < len(sm.pools); i++ {
go func(id int) {
defer sm.wg.Done()
for {
sm.RLock()
if sm.state == hotRestartState {
sm.RUnlock()
time.Sleep(500 * time.Millisecond)
continue
}
pool := sm.pools[id]
sm.RUnlock()
select {
case <-pool.Session().CloseChan():
sm.RLock()
// in hotrestart state break this select and wait for hotrestar done
if sm.state == hotRestartState {
sm.RUnlock()
break
}
sm.RUnlock()
pool.close()
for {
if sm.config.rebuildInterval == 0 {
sm.config.rebuildInterval = sessionRebuildInterval
}
rebuildTimer := time.NewTimer(sm.config.rebuildInterval)
select {
case <-sm.ctx.Done():
return
case <-rebuildTimer.C:
}
sm.Lock()
// after rebuildTimer, check if Session.CloseChan caused by hotrestart,
// pool.epochId != sm.pools[id].epochId represent the pools has been replaced by the new epoch pools,
// this time Session.CloseChan will not rebuild session.
sessionHadChangedByHotrestart := sm.pools[id].Session().epochID != pool.Session().epochID
if sessionHadChangedByHotrestart {
sm.Unlock()
break
}
// both new epoch pools and old epoch pools which has not been replaced will use new epochId to rebuild session
session, err := newClientSession(id, sm.epoch, sm.randID, sm.config)
sm.Unlock()
if err != nil {
internalLogger.errorf("rebuild stream pool's sessionID %d %s failed, reason:%s. retry after %s", id, pool.Session().name, err.Error(), sessionRebuildInterval.String())
continue
}
session.manager = sm
pool.session.Store(session)
internalLogger.warnf("rebuild stream pool's sessionID %d %s success", id, pool.Session().name)
break
}
case <-sm.ctx.Done():
return
}
}
}(i)
}
}
func (sm *SessionManager) checkHotRestart() {
timeout := time.NewTimer(hotRestartCheckTimeout)
defer timeout.Stop()
ticker := time.NewTicker(hotRestartCheckInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
sm.Lock()
if len(sm.reservePools) == len(sm.pools) {
sm.state = defaultState
for _, p := range sm.reservePools {
if err := p.Session().hotRestart(sm.epoch, typeHotRestartAck); err != nil {
internalLogger.warnf("SessionManager [epoch:%d] ack hotRestart error %+v", sm.epoch, err)
}
}
internalLogger.warnf("SessionManager [epoch:%d] checkHotRestart done", sm.epoch)
sm.Unlock()
return
}
sm.Unlock()
case <-timeout.C:
sm.Lock()
sm.state = defaultState
for _, p := range sm.reservePools {
p.close()
}
sm.reservePools = nil
internalLogger.errorf("SessionManager [epoch:%d] checkHotRestart timeout", sm.epoch)
sm.Unlock()
return
}
}
}
func (sm *SessionManager) handleEvent(event eventType, param interface{}) {
if int(event) >= len(sessionManagerHandlers) || sessionManagerHandlers[event] == nil {
internalLogger.errorf("SessionManager handle unsupported event %d %s", event, event.String())
return
}
sessionManagerHandlers[event](sm, param)
}
func handleSessionManagerHotRestart(sm *SessionManager, params interface{}) {
defer func() {
if err := recover(); err != nil {
internalLogger.warnf("SessionManager [epoch:%d] handleSessionManagerHotRestart params %+v recover error %+v", sm.epoch, params, err)
}
}()
sm.Lock()
defer sm.Unlock()
hParams := params.(*sessionManagerHotRestartParams)
if sm.state == hotRestartState && sm.epoch != hParams.epoch {
internalLogger.warnf("SessionManager [epoch:%d] handleSessionManagerHotRestart get invalid params %+v ", sm.epoch, params)
return
}
// the first session to receive hot restart event will clear reservePools and set state
if sm.state != hotRestartState {
sm.state = hotRestartState
sm.epoch = hParams.epoch
sm.randID = uint64(time.Now().UnixNano()) + rand.Uint64()
for _, p := range sm.reservePools {
p.close()
}
sm.reservePools = nil
go func() {
sm.checkHotRestart()
}()
}
if sm.reservePools[hParams.session.sessionID] != nil {
internalLogger.warnf("SessionManager [epoch:%d] handleSessionManagerHotRestart get repeat sessionID:%d ", sm.epoch, hParams.session.sessionID)
return
}
newSession, err := newClientSession(hParams.session.sessionID, sm.epoch, sm.randID, sm.config)
if err != nil {
internalLogger.warnf("SessionManager [epoch:%d] handleSessionManagerHotRestart newClientSession sessionID:%d error %+v", sm.epoch, hParams.session.sessionID, err)
return
}
newSession.manager = sm
p := newStreamPool(uint32(sm.config.MaxStreamNum))
p.session.Store(newSession)
if sm.pools[hParams.session.sessionID] == nil {
internalLogger.warnf("SessionManager [epoch:%d] handleSessionManagerHotRestart pools sessionID:%d absence", sm.epoch, hParams.session.sessionID)
return
}
if len(sm.reservePools) == 0 {
sm.reservePools = make(map[int]*streamPool, 0)
}
sm.reservePools[hParams.session.sessionID] = sm.pools[hParams.session.sessionID]
sm.pools[hParams.session.sessionID] = p
}
func newClientSession(sessionID int, epochID, randID uint64, config *SessionManagerConfig) (*Session, error) {
var conn net.Conn
var err error
if config.UnixPath != "" {
conn, err = net.DialTimeout("unix", config.UnixPath, config.ConnectionWriteTimeout)
} else {
conn, err = net.DialTimeout(config.Network, config.Address, config.ConnectionWriteTimeout)
}
if err != nil {
return nil, err
}
conf := *config.Config
conf.ShareMemoryPathPrefix += "_" + strconv.Itoa(os.Getpid())
if config.MemMapType == MemMapTypeDevShmFile {
if len(conf.ShareMemoryPathPrefix)+epochInfoMaxLen+queueInfoMaxLen > fileNameMaxLen {
return nil, ErrFileNameTooLong
}
}
if epochID > 0 {
conf.ShareMemoryPathPrefix += "_epoch_" + strconv.FormatUint(epochID, 10) + "_" + strconv.FormatUint(randID, 10)
}
if conf.ShareMemoryPathPrefix != "" {
conf.QueuePath = conf.ShareMemoryPathPrefix + "_queue_" + strconv.Itoa(sessionID)
}
session, err := newSession(&conf, conn, true)
if err != nil {
return nil, err
}
session.sessionID = sessionID
session.epochID = epochID
session.randID = randID
return session, nil
}
func (p *streamPool) Session() *Session {
load := p.session.Load()
if load != nil {
return load.(*Session)
}
return nil
}
func (p *streamPool) close() {
if p.session.Load() != nil {
p.session.Load().(*Session).Close()
}
for {
s := p.pop()
if s == nil {
break
}
s.Close()
}
}
func (p *streamPool) getOrOpenStream() (*Stream, error) {
if !p.Session().IsHealthy() {
return nil, ErrSessionUnhealthy
}
for stream := p.pop(); stream != nil; stream = p.pop() {
if !stream.Session().IsClosed() {
// ensure return an open stream
if stream.IsOpen() {
return stream, nil
}
}
}
stream, err := p.Session().OpenStream()
if err != nil {
return nil, err
}
stream.pool = p
return stream, nil
}
func (p *streamPool) putOrCloseStream(s *Stream) {
// if the stream is in fallback state, we will not reuse it
if s.inFallbackState {
s.Close()
return
}
if err := s.reset(); err == nil {
s.ReleaseReadAndReuse()
if p.push(s) != nil {
s.Close()
}
} else {
s.Close()
}
}
func (p *streamPool) pop() *Stream {
p.Lock()
if p.tail > p.head {
s := p.streams[p.head%uint64(p.capacity)]
p.head++
p.Unlock()
return s
}
p.Unlock()
return nil
}
var errPoolFull = errors.New("stream pool is full")
func (p *streamPool) push(s *Stream) error {
p.Lock()
if p.tail-p.head < uint64(p.capacity) {
p.streams[p.tail%uint64(p.capacity)] = s
p.tail++
p.Unlock()
return nil
}
p.Unlock()
return errPoolFull
}