-
Notifications
You must be signed in to change notification settings - Fork 18
/
channel_manager.go
83 lines (74 loc) · 1.72 KB
/
channel_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
// Copyright 2021 Converter Systems LLC. All rights reserved.
package server
import (
"sync"
"time"
)
// ChannelManager manages the secure channels for a server.
type ChannelManager struct {
sync.RWMutex
server *Server
channelsByID map[uint32]*serverSecureChannel
}
// NewChannelManager instantiates a new ChannelManager.
func NewChannelManager(server *Server) *ChannelManager {
m := &ChannelManager{server: server, channelsByID: make(map[uint32]*serverSecureChannel)}
go func(m *ChannelManager) {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
m.checkForClosedChannels()
case <-m.server.closed:
m.RLock()
for _, ch := range m.channelsByID {
ch.Close()
}
m.RUnlock()
return
}
}
}(m)
return m
}
// Get a secure channel from the server.
func (m *ChannelManager) Get(id uint32) (*serverSecureChannel, bool) {
m.RLock()
if ch, ok := m.channelsByID[id]; ok {
m.RUnlock()
return ch, ok
}
m.RUnlock()
return nil, false
}
// Add a secure channel to the server.
func (m *ChannelManager) Add(ch *serverSecureChannel) error {
m.Lock()
m.channelsByID[ch.channelID] = ch
m.Unlock()
return nil
}
// Delete the secure channel from the server.
func (m *ChannelManager) Delete(ch *serverSecureChannel) {
m.Lock()
delete(m.channelsByID, ch.channelID)
m.Unlock()
}
// Len returns the number of secure channel.
func (m *ChannelManager) Len() int {
m.RLock()
res := len(m.channelsByID)
m.RUnlock()
return res
}
func (m *ChannelManager) checkForClosedChannels() {
m.Lock()
for k, ch := range m.channelsByID {
if ch.closed {
delete(m.channelsByID, k)
// log.Printf("Deleted expired channel '%d'.\n", ch.channelId)
}
}
m.Unlock()
}