-
Notifications
You must be signed in to change notification settings - Fork 13
/
ssh_session.go
136 lines (118 loc) · 1.89 KB
/
ssh_session.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
package socker
import (
"sync"
"sync/atomic"
"time"
)
const (
sessionActive int32 = iota
sessionIdle
sessionInvalid
)
type session struct {
status int32
pool *sessionPool
}
func (s *session) Release() {
if !atomic.CompareAndSwapInt32(&s.status, sessionActive, sessionIdle) {
return
}
s.pool.put(s)
}
func (s *session) Drop() {
if !atomic.CompareAndSwapInt32(&s.status, sessionActive, sessionInvalid) {
return
}
}
type sessionPool struct {
size int
mu sync.RWMutex
c chan struct{}
}
func initPoolChan(size int) chan struct{} {
c := make(chan struct{}, size)
for i := 0; i < size; i++ {
c <- struct{}{}
}
return c
}
func newSessionPool(size int) *sessionPool {
const defaultMaxSession = 10
var c chan struct{}
if size == 0 {
size = defaultMaxSession
}
if size > 0 {
c = initPoolChan(size)
}
return &sessionPool{
size: size,
c: c,
}
}
func (p *sessionPool) Size() int {
return p.size
}
func (p *sessionPool) Close() {
if p.size <= 0 {
return
}
if p.c != nil {
p.mu.Lock()
if p.c != nil {
close(p.c)
p.c = nil
}
p.mu.Unlock()
}
}
func (p *sessionPool) takeWithTimeout() bool {
timer := time.NewTimer(time.Millisecond * 10)
select {
case <-p.c:
timer.Stop()
return true
case <-timer.C:
return false
}
}
func (p *sessionPool) Take() (*session, bool) {
if p.size <= 0 {
return &session{pool: p, status: sessionActive}, true
}
if p.c != nil {
var taken bool
p.mu.RLock()
if p.c != nil {
<-p.c
taken = true
}
p.mu.RUnlock()
if taken {
return &session{pool: p, status: sessionActive}, true
}
}
return nil, false
}
func (p *sessionPool) put(s *session) bool {
if p != s.pool {
return false
}
if p.size <= 0 {
return true
}
if p.c == nil {
return false
}
var putted bool
p.mu.RLock()
if p.c != nil {
select {
case p.c <- struct{}{}:
putted = true
default:
}
}
p.mu.RUnlock()
return putted
}